blob: e02531674312b95e12dee2f777ce21c0f968288b [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>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070032#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080034#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080035
36#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070037#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080038#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080039#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080040#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070041#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070042#include <system/audio_effects/effect_ns.h>
43#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080045
46// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070047#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080048#include <media/nbaio/AudioStreamOutSink.h>
49#include <media/nbaio/MonoPipe.h>
50#include <media/nbaio/MonoPipeReader.h>
51#include <media/nbaio/Pipe.h>
52#include <media/nbaio/PipeReader.h>
53#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080054#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080055
56#include <powermanager/PowerManager.h>
57
Eric Laurent81784c32012-11-19 14:55:58 -080058#include "AudioFlinger.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
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700100#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700101#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 Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
446 default:
447 return "unknown";
448 }
449}
450
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700451std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800452{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 }
459 return result;
460}
461
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700462std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800463{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464 std::string result;
465 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800466 return result;
467}
468
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700469std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700470{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471 std::string result;
472 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700473 return result;
474}
475
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800476const char *sourceToString(audio_source_t source)
477{
478 switch (source) {
479 case AUDIO_SOURCE_DEFAULT: return "default";
480 case AUDIO_SOURCE_MIC: return "mic";
481 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
482 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
483 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
484 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
485 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
486 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
487 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800488 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800489 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
490 case AUDIO_SOURCE_HOTWORD: return "hotword";
491 default: return "unknown";
492 }
493}
494
Eric Laurent81784c32012-11-19 14:55:58 -0800495AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700496 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800497 : Thread(false /*canCallJava*/),
498 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700499 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700500 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800501 // are set by PlaybackThread::readOutputParameters_l() or
502 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700503 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800504 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700505 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
506 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800507 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700508 mDeathRecipient(new PMDeathRecipient(this)),
Andy Hungdae27702016-10-31 14:01:16 -0700509 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800510{
Eric Laurent296fb132015-05-01 11:38:42 -0700511 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800512}
513
514AudioFlinger::ThreadBase::~ThreadBase()
515{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700516 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700517 mConfigEvents.clear();
518
Eric Laurent81784c32012-11-19 14:55:58 -0800519 // do not lock the mutex in destructor
520 releaseWakeLock_l();
521 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800522 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800523 binder->unlinkToDeath(mDeathRecipient);
524 }
525}
526
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700527status_t AudioFlinger::ThreadBase::readyToRun()
528{
529 status_t status = initCheck();
530 if (status == NO_ERROR) {
531 ALOGI("AudioFlinger's thread %p ready to run", this);
532 } else {
533 ALOGE("No working audio driver found.");
534 }
535 return status;
536}
537
Eric Laurent81784c32012-11-19 14:55:58 -0800538void AudioFlinger::ThreadBase::exit()
539{
540 ALOGV("ThreadBase::exit");
541 // do any cleanup required for exit to succeed
542 preExit();
543 {
544 // This lock prevents the following race in thread (uniprocessor for illustration):
545 // if (!exitPending()) {
546 // // context switch from here to exit()
547 // // exit() calls requestExit(), what exitPending() observes
548 // // exit() calls signal(), which is dropped since no waiters
549 // // context switch back from exit() to here
550 // mWaitWorkCV.wait(...);
551 // // now thread is hung
552 // }
553 AutoMutex lock(mLock);
554 requestExit();
555 mWaitWorkCV.broadcast();
556 }
557 // When Thread::requestExitAndWait is made virtual and this method is renamed to
558 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
559 requestExitAndWait();
560}
561
562status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
563{
Eric Laurent81784c32012-11-19 14:55:58 -0800564 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
565 Mutex::Autolock _l(mLock);
566
Eric Laurent10351942014-05-08 18:49:52 -0700567 return sendSetParameterConfigEvent_l(keyValuePairs);
568}
569
570// sendConfigEvent_l() must be called with ThreadBase::mLock held
571// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
572status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
573{
574 status_t status = NO_ERROR;
575
Eric Laurent72e3f392015-05-20 14:43:50 -0700576 if (event->mRequiresSystemReady && !mSystemReady) {
577 event->mWaitStatus = false;
578 mPendingConfigEvents.add(event);
579 return status;
580 }
Eric Laurent10351942014-05-08 18:49:52 -0700581 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700582 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800583 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700584 mLock.unlock();
585 {
586 Mutex::Autolock _l(event->mLock);
587 while (event->mWaitStatus) {
588 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
589 event->mStatus = TIMED_OUT;
590 event->mWaitStatus = false;
591 }
592 }
593 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800594 }
Eric Laurent10351942014-05-08 18:49:52 -0700595 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800596 return status;
597}
598
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700599void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800600{
601 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800603}
604
605// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700606void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800607{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700609 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800610}
611
Eric Laurent72e3f392015-05-20 14:43:50 -0700612void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
613{
614 Mutex::Autolock _l(mLock);
615 sendPrioConfigEvent_l(pid, tid, prio);
616}
617
Eric Laurent81784c32012-11-19 14:55:58 -0800618// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
619void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
620{
Eric Laurent10351942014-05-08 18:49:52 -0700621 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
622 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800623}
624
Eric Laurent10351942014-05-08 18:49:52 -0700625// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
626status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
Andy Hung2ddee192015-12-18 17:34:44 -0800628 sp<ConfigEvent> configEvent;
629 AudioParameter param(keyValuePair);
630 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700631 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800632 setMasterMono_l(value != 0);
633 if (param.size() == 1) {
634 return NO_ERROR; // should be a solo parameter - we don't pass down
635 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700636 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800637 configEvent = new SetParameterConfigEvent(param.toString());
638 } else {
639 configEvent = new SetParameterConfigEvent(keyValuePair);
640 }
Eric Laurent10351942014-05-08 18:49:52 -0700641 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700642}
643
Eric Laurent1c333e22014-05-20 10:48:17 -0700644status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
645 const struct audio_patch *patch,
646 audio_patch_handle_t *handle)
647{
648 Mutex::Autolock _l(mLock);
649 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
650 status_t status = sendConfigEvent_l(configEvent);
651 if (status == NO_ERROR) {
652 CreateAudioPatchConfigEventData *data =
653 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
654 *handle = data->mHandle;
655 }
656 return status;
657}
658
659status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
660 const audio_patch_handle_t handle)
661{
662 Mutex::Autolock _l(mLock);
663 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
664 return sendConfigEvent_l(configEvent);
665}
666
667
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700668// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700669void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700670{
Eric Laurent10351942014-05-08 18:49:52 -0700671 bool configChanged = false;
672
Eric Laurent81784c32012-11-19 14:55:58 -0800673 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700674 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700675 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800676 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700677 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700678 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700679 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
680 // FIXME Need to understand why this has to be done asynchronously
681 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 true /*asynchronous*/);
683 if (err != 0) {
684 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700685 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 }
687 } break;
688 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700689 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700690 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700691 } break;
692 case CFG_EVENT_SET_PARAMETER: {
693 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
694 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
695 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700696 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700697 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700698 case CFG_EVENT_CREATE_AUDIO_PATCH: {
699 CreateAudioPatchConfigEventData *data =
700 (CreateAudioPatchConfigEventData *)event->mData.get();
701 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
702 } break;
703 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
704 ReleaseAudioPatchConfigEventData *data =
705 (ReleaseAudioPatchConfigEventData *)event->mData.get();
706 event->mStatus = releaseAudioPatch_l(data->mHandle);
707 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700708 default:
Eric Laurent10351942014-05-08 18:49:52 -0700709 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700710 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800711 }
Eric Laurent10351942014-05-08 18:49:52 -0700712 {
713 Mutex::Autolock _l(event->mLock);
714 if (event->mWaitStatus) {
715 event->mWaitStatus = false;
716 event->mCond.signal();
717 }
718 }
719 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
720 }
721
722 if (configChanged) {
723 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800724 }
Eric Laurent81784c32012-11-19 14:55:58 -0800725}
726
Marco Nelissenb2208842014-02-07 14:00:50 -0800727String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
728 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700729 const audio_channel_representation_t representation =
730 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700731
732 switch (representation) {
733 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
734 if (output) {
735 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
736 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
737 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
738 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
739 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
740 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
741 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
742 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
743 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
744 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
745 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
746 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
747 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
748 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
752 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
753 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
754 } else {
755 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
756 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
757 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
758 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
759 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
760 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
761 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
762 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
764 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
765 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
766 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
767 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
768 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
769 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
770 }
771 const int len = s.length();
772 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700773 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700774 s.unlockBuffer(len - 2); // remove trailing ", "
775 }
776 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800777 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700778 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
779 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
780 return s;
781 default:
782 s.appendFormat("unknown mask, representation:%d bits:%#x",
783 representation, audio_channel_mask_get_bits(mask));
784 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800785 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800786}
787
Glenn Kasten0f11b512014-01-31 16:18:54 -0800788void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800789{
790 const size_t SIZE = 256;
791 char buffer[SIZE];
792 String8 result;
793
794 bool locked = AudioFlinger::dumpTryLock(mLock);
795 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700796 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800797 }
798
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800799 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700800 dprintf(fd, " I/O handle: %d\n", mId);
801 dprintf(fd, " TID: %d\n", getTid());
802 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700803 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700804 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700805 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700806 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700807 dprintf(fd, " Channel count: %u\n", mChannelCount);
808 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800809 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700810 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700811 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700812 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800813 size_t numConfig = mConfigEvents.size();
814 if (numConfig) {
815 for (size_t i = 0; i < numConfig; i++) {
816 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700817 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800818 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800820 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800822 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700823 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
824 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800825 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800826
827 if (locked) {
828 mLock.unlock();
829 }
830}
831
832void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
833{
834 const size_t SIZE = 256;
835 char buffer[SIZE];
836 String8 result;
837
Marco Nelissenb2208842014-02-07 14:00:50 -0800838 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000839 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800840 write(fd, buffer, strlen(buffer));
841
Marco Nelissenb2208842014-02-07 14:00:50 -0800842 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800843 sp<EffectChain> chain = mEffectChains[i];
844 if (chain != 0) {
845 chain->dump(fd, args);
846 }
847 }
848}
849
Andy Hungdae27702016-10-31 14:01:16 -0700850void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800851{
852 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700853 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800854}
855
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100856String16 AudioFlinger::ThreadBase::getWakeLockTag()
857{
858 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800859 case MIXER:
860 return String16("AudioMix");
861 case DIRECT:
862 return String16("AudioDirectOut");
863 case DUPLICATING:
864 return String16("AudioDup");
865 case RECORD:
866 return String16("AudioIn");
867 case OFFLOAD:
868 return String16("AudioOffload");
869 default:
870 ALOG_ASSERT(false);
871 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100872 }
873}
874
Andy Hungdae27702016-10-31 14:01:16 -0700875void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800876{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800877 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800878 if (mPowerManager != 0) {
879 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700880 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
881 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700882 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100883 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700884 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700885 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800886 if (status == NO_ERROR) {
887 mWakeLockToken = binder;
888 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800889 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800890 }
Wei Jia3f273d12015-11-24 09:06:49 -0800891
Andy Hung3f0c9022016-01-15 17:49:46 -0800892 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800893 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
894 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800895}
896
897void AudioFlinger::ThreadBase::releaseWakeLock()
898{
899 Mutex::Autolock _l(mLock);
900 releaseWakeLock_l();
901}
902
903void AudioFlinger::ThreadBase::releaseWakeLock_l()
904{
Andy Hung3f0c9022016-01-15 17:49:46 -0800905 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800907 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800908 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700909 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
910 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800911 }
912 mWakeLockToken.clear();
913 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800914}
915
916void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700917 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800918 // use checkService() to avoid blocking if power service is not up yet
919 sp<IBinder> binder =
920 defaultServiceManager()->checkService(String16("power"));
921 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800922 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800923 } else {
924 mPowerManager = interface_cast<IPowerManager>(binder);
925 binder->linkToDeath(mDeathRecipient);
926 }
927 }
928}
929
Andy Hungd01b0f12016-11-07 16:10:30 -0800930void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800931 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700932
933#if !LOG_NDEBUG
934 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800935 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700936 s << uid << " ";
937 }
938 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
939#endif
940
Andy Hung438e7572015-12-14 15:51:17 -0800941 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
942 if (mSystemReady) {
943 ALOGE("no wake lock to update, but system ready!");
944 } else {
945 ALOGW("no wake lock to update, system not ready yet");
946 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800947 return;
948 }
949 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800950 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
951 status_t status = mPowerManager->updateWakeLockUids(
952 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
953 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800954 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800955 }
956}
957
Eric Laurent81784c32012-11-19 14:55:58 -0800958void AudioFlinger::ThreadBase::clearPowerManager()
959{
960 Mutex::Autolock _l(mLock);
961 releaseWakeLock_l();
962 mPowerManager.clear();
963}
964
Glenn Kasten0f11b512014-01-31 16:18:54 -0800965void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800966{
967 sp<ThreadBase> thread = mThread.promote();
968 if (thread != 0) {
969 thread->clearPowerManager();
970 }
971 ALOGW("power manager service died !!!");
972}
973
974void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800975 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800976{
977 Mutex::Autolock _l(mLock);
978 setEffectSuspended_l(type, suspend, sessionId);
979}
980
981void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800982 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800983{
984 sp<EffectChain> chain = getEffectChain_l(sessionId);
985 if (chain != 0) {
986 if (type != NULL) {
987 chain->setEffectSuspended_l(type, suspend);
988 } else {
989 chain->setEffectSuspendedAll_l(suspend);
990 }
991 }
992
993 updateSuspendedSessions_l(type, suspend, sessionId);
994}
995
996void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
997{
998 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
999 if (index < 0) {
1000 return;
1001 }
1002
1003 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1004 mSuspendedSessions.valueAt(index);
1005
1006 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001007 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001008 for (int j = 0; j < desc->mRefCount; j++) {
1009 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1010 chain->setEffectSuspendedAll_l(true);
1011 } else {
1012 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1013 desc->mType.timeLow);
1014 chain->setEffectSuspended_l(&desc->mType, true);
1015 }
1016 }
1017 }
1018}
1019
1020void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1021 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001022 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001023{
1024 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1025
1026 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1027
1028 if (suspend) {
1029 if (index >= 0) {
1030 sessionEffects = mSuspendedSessions.valueAt(index);
1031 } else {
1032 mSuspendedSessions.add(sessionId, sessionEffects);
1033 }
1034 } else {
1035 if (index < 0) {
1036 return;
1037 }
1038 sessionEffects = mSuspendedSessions.valueAt(index);
1039 }
1040
1041
1042 int key = EffectChain::kKeyForSuspendAll;
1043 if (type != NULL) {
1044 key = type->timeLow;
1045 }
1046 index = sessionEffects.indexOfKey(key);
1047
1048 sp<SuspendedSessionDesc> desc;
1049 if (suspend) {
1050 if (index >= 0) {
1051 desc = sessionEffects.valueAt(index);
1052 } else {
1053 desc = new SuspendedSessionDesc();
1054 if (type != NULL) {
1055 desc->mType = *type;
1056 }
1057 sessionEffects.add(key, desc);
1058 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1059 }
1060 desc->mRefCount++;
1061 } else {
1062 if (index < 0) {
1063 return;
1064 }
1065 desc = sessionEffects.valueAt(index);
1066 if (--desc->mRefCount == 0) {
1067 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1068 sessionEffects.removeItemsAt(index);
1069 if (sessionEffects.isEmpty()) {
1070 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1071 sessionId);
1072 mSuspendedSessions.removeItem(sessionId);
1073 }
1074 }
1075 }
1076 if (!sessionEffects.isEmpty()) {
1077 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1078 }
1079}
1080
1081void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1082 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001083 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001084{
1085 Mutex::Autolock _l(mLock);
1086 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1087}
1088
1089void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1090 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001091 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001092{
1093 if (mType != RECORD) {
1094 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1095 // another session. This gives the priority to well behaved effect control panels
1096 // and applications not using global effects.
1097 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1098 // global effects
1099 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1100 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1101 }
1102 }
1103
1104 sp<EffectChain> chain = getEffectChain_l(sessionId);
1105 if (chain != 0) {
1106 chain->checkSuspendOnEffectEnabled(effect, enabled);
1107 }
1108}
1109
Eric Laurent4c415062016-06-17 16:14:16 -07001110// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1111status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1112 const effect_descriptor_t *desc, audio_session_t sessionId)
1113{
1114 // No global effect sessions on record threads
1115 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1116 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1117 desc->name, mThreadName);
1118 return BAD_VALUE;
1119 }
1120 // only pre processing effects on record thread
1121 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1122 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1123 desc->name, mThreadName);
1124 return BAD_VALUE;
1125 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001126
1127 // always allow effects without processing load or latency
1128 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1129 return NO_ERROR;
1130 }
1131
Eric Laurent4c415062016-06-17 16:14:16 -07001132 audio_input_flags_t flags = mInput->flags;
1133 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1134 if (flags & AUDIO_INPUT_FLAG_RAW) {
1135 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
1139 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1140 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1141 desc->name, mThreadName);
1142 return BAD_VALUE;
1143 }
1144 }
1145 return NO_ERROR;
1146}
1147
1148// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1149status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1150 const effect_descriptor_t *desc, audio_session_t sessionId)
1151{
1152 // no preprocessing on playback threads
1153 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1154 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1155 " thread %s", desc->name, mThreadName);
1156 return BAD_VALUE;
1157 }
1158
1159 switch (mType) {
1160 case MIXER: {
1161 // Reject any effect on mixer multichannel sinks.
1162 // TODO: fix both format and multichannel issues with effects.
1163 if (mChannelCount != FCC_2) {
1164 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1165 " thread %s", desc->name, mChannelCount, mThreadName);
1166 return BAD_VALUE;
1167 }
1168 audio_output_flags_t flags = mOutput->flags;
1169 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1170 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1171 // global effects are applied only to non fast tracks if they are SW
1172 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1173 break;
1174 }
1175 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1176 // only post processing on output stage session
1177 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1178 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1179 " on output stage session", desc->name);
1180 return BAD_VALUE;
1181 }
1182 } else {
1183 // no restriction on effects applied on non fast tracks
1184 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1185 break;
1186 }
1187 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001188
1189 // always allow effects without processing load or latency
1190 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1191 break;
1192 }
Eric Laurent4c415062016-06-17 16:14:16 -07001193 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1194 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1195 desc->name);
1196 return BAD_VALUE;
1197 }
1198 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1199 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1200 " in fast mode", desc->name);
1201 return BAD_VALUE;
1202 }
1203 }
1204 } break;
1205 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001206 // nothing actionable on offload threads, if the effect:
1207 // - is offloadable: the effect can be created
1208 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1209 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001210 break;
1211 case DIRECT:
1212 // Reject any effect on Direct output threads for now, since the format of
1213 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1214 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1215 desc->name, mThreadName);
1216 return BAD_VALUE;
1217 case DUPLICATING:
1218 // Reject any effect on mixer multichannel sinks.
1219 // TODO: fix both format and multichannel issues with effects.
1220 if (mChannelCount != FCC_2) {
1221 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1222 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1223 return BAD_VALUE;
1224 }
1225 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1226 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1227 " thread %s", desc->name, mThreadName);
1228 return BAD_VALUE;
1229 }
1230 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1231 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1232 " DUPLICATING thread %s", desc->name, mThreadName);
1233 return BAD_VALUE;
1234 }
1235 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1236 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1237 " DUPLICATING thread %s", desc->name, mThreadName);
1238 return BAD_VALUE;
1239 }
1240 break;
1241 default:
1242 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1243 }
1244
1245 return NO_ERROR;
1246}
1247
Eric Laurent81784c32012-11-19 14:55:58 -08001248// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1249sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1250 const sp<AudioFlinger::Client>& client,
1251 const sp<IEffectClient>& effectClient,
1252 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001253 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001254 effect_descriptor_t *desc,
1255 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001256 status_t *status,
1257 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001258{
1259 sp<EffectModule> effect;
1260 sp<EffectHandle> handle;
1261 status_t lStatus;
1262 sp<EffectChain> chain;
1263 bool chainCreated = false;
1264 bool effectCreated = false;
1265 bool effectRegistered = false;
1266
1267 lStatus = initCheck();
1268 if (lStatus != NO_ERROR) {
1269 ALOGW("createEffect_l() Audio driver not initialized.");
1270 goto Exit;
1271 }
1272
Eric Laurent81784c32012-11-19 14:55:58 -08001273 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1274
1275 { // scope for mLock
1276 Mutex::Autolock _l(mLock);
1277
Eric Laurent4c415062016-06-17 16:14:16 -07001278 lStatus = checkEffectCompatibility_l(desc, sessionId);
1279 if (lStatus != NO_ERROR) {
1280 goto Exit;
1281 }
1282
Eric Laurent81784c32012-11-19 14:55:58 -08001283 // check for existing effect chain with the requested audio session
1284 chain = getEffectChain_l(sessionId);
1285 if (chain == 0) {
1286 // create a new chain for this session
1287 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1288 chain = new EffectChain(this, sessionId);
1289 addEffectChain_l(chain);
1290 chain->setStrategy(getStrategyForSession_l(sessionId));
1291 chainCreated = true;
1292 } else {
1293 effect = chain->getEffectFromDesc_l(desc);
1294 }
1295
1296 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1297
1298 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001299 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001300 // Check CPU and memory usage
1301 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1302 if (lStatus != NO_ERROR) {
1303 goto Exit;
1304 }
1305 effectRegistered = true;
1306 // create a new effect module if none present in the chain
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001307 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001308 if (lStatus != NO_ERROR) {
1309 goto Exit;
1310 }
1311 effectCreated = true;
1312
1313 effect->setDevice(mOutDevice);
1314 effect->setDevice(mInDevice);
1315 effect->setMode(mAudioFlinger->getMode());
1316 effect->setAudioSource(mAudioSource);
1317 }
1318 // create effect handle and connect it to effect module
1319 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001320 lStatus = handle->initCheck();
1321 if (lStatus == OK) {
1322 lStatus = effect->addHandle(handle.get());
1323 }
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (enabled != NULL) {
1325 *enabled = (int)effect->isEnabled();
1326 }
1327 }
1328
1329Exit:
1330 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1331 Mutex::Autolock _l(mLock);
1332 if (effectCreated) {
1333 chain->removeEffect_l(effect);
1334 }
1335 if (effectRegistered) {
1336 AudioSystem::unregisterEffect(effect->id());
1337 }
1338 if (chainCreated) {
1339 removeEffectChain_l(chain);
1340 }
1341 handle.clear();
1342 }
1343
Glenn Kasten9156ef32013-08-06 15:39:08 -07001344 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001345 return handle;
1346}
1347
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001348void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1349 bool unpinIfLast)
1350{
1351 bool remove = false;
1352 sp<EffectModule> effect;
1353 {
1354 Mutex::Autolock _l(mLock);
1355
1356 effect = handle->effect().promote();
1357 if (effect == 0) {
1358 return;
1359 }
1360 // restore suspended effects if the disconnected handle was enabled and the last one.
1361 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1362 if (remove) {
1363 removeEffect_l(effect, true);
1364 }
1365 }
1366 if (remove) {
1367 mAudioFlinger->updateOrphanEffectChains(effect);
1368 AudioSystem::unregisterEffect(effect->id());
1369 if (handle->enabled()) {
1370 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1371 }
1372 }
1373}
1374
Glenn Kastend848eb42016-03-08 13:42:11 -08001375sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1376 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001377{
1378 Mutex::Autolock _l(mLock);
1379 return getEffect_l(sessionId, effectId);
1380}
1381
Glenn Kastend848eb42016-03-08 13:42:11 -08001382sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1383 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001384{
1385 sp<EffectChain> chain = getEffectChain_l(sessionId);
1386 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1387}
1388
1389// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1390// PlaybackThread::mLock held
1391status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1392{
1393 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001394 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001395 sp<EffectChain> chain = getEffectChain_l(sessionId);
1396 bool chainCreated = false;
1397
Eric Laurent5baf2af2013-09-12 17:37:00 -07001398 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1399 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1400 this, effect->desc().name, effect->desc().flags);
1401
Eric Laurent81784c32012-11-19 14:55:58 -08001402 if (chain == 0) {
1403 // create a new chain for this session
1404 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1405 chain = new EffectChain(this, sessionId);
1406 addEffectChain_l(chain);
1407 chain->setStrategy(getStrategyForSession_l(sessionId));
1408 chainCreated = true;
1409 }
1410 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1411
1412 if (chain->getEffectFromId_l(effect->id()) != 0) {
1413 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1414 this, effect->desc().name, chain.get());
1415 return BAD_VALUE;
1416 }
1417
Eric Laurent5baf2af2013-09-12 17:37:00 -07001418 effect->setOffloaded(mType == OFFLOAD, mId);
1419
Eric Laurent81784c32012-11-19 14:55:58 -08001420 status_t status = chain->addEffect_l(effect);
1421 if (status != NO_ERROR) {
1422 if (chainCreated) {
1423 removeEffectChain_l(chain);
1424 }
1425 return status;
1426 }
1427
1428 effect->setDevice(mOutDevice);
1429 effect->setDevice(mInDevice);
1430 effect->setMode(mAudioFlinger->getMode());
1431 effect->setAudioSource(mAudioSource);
1432 return NO_ERROR;
1433}
1434
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001435void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001436
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001437 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001438 effect_descriptor_t desc = effect->desc();
1439 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1440 detachAuxEffect_l(effect->id());
1441 }
1442
1443 sp<EffectChain> chain = effect->chain().promote();
1444 if (chain != 0) {
1445 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001446 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001447 removeEffectChain_l(chain);
1448 }
1449 } else {
1450 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1451 }
1452}
1453
1454void AudioFlinger::ThreadBase::lockEffectChains_l(
1455 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1456{
1457 effectChains = mEffectChains;
1458 for (size_t i = 0; i < mEffectChains.size(); i++) {
1459 mEffectChains[i]->lock();
1460 }
1461}
1462
1463void AudioFlinger::ThreadBase::unlockEffectChains(
1464 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1465{
1466 for (size_t i = 0; i < effectChains.size(); i++) {
1467 effectChains[i]->unlock();
1468 }
1469}
1470
Glenn Kastend848eb42016-03-08 13:42:11 -08001471sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001472{
1473 Mutex::Autolock _l(mLock);
1474 return getEffectChain_l(sessionId);
1475}
1476
Glenn Kastend848eb42016-03-08 13:42:11 -08001477sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1478 const
Eric Laurent81784c32012-11-19 14:55:58 -08001479{
1480 size_t size = mEffectChains.size();
1481 for (size_t i = 0; i < size; i++) {
1482 if (mEffectChains[i]->sessionId() == sessionId) {
1483 return mEffectChains[i];
1484 }
1485 }
1486 return 0;
1487}
1488
1489void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1490{
1491 Mutex::Autolock _l(mLock);
1492 size_t size = mEffectChains.size();
1493 for (size_t i = 0; i < size; i++) {
1494 mEffectChains[i]->setMode_l(mode);
1495 }
1496}
1497
Eric Laurent83b88082014-06-20 18:31:16 -07001498void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1499{
1500 config->type = AUDIO_PORT_TYPE_MIX;
1501 config->ext.mix.handle = mId;
1502 config->sample_rate = mSampleRate;
1503 config->format = mFormat;
1504 config->channel_mask = mChannelMask;
1505 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1506 AUDIO_PORT_CONFIG_FORMAT;
1507}
1508
Eric Laurent72e3f392015-05-20 14:43:50 -07001509void AudioFlinger::ThreadBase::systemReady()
1510{
1511 Mutex::Autolock _l(mLock);
1512 if (mSystemReady) {
1513 return;
1514 }
1515 mSystemReady = true;
1516
1517 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1518 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1519 }
1520 mPendingConfigEvents.clear();
1521}
1522
Andy Hungdae27702016-10-31 14:01:16 -07001523template <typename T>
1524ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1525 ssize_t index = mActiveTracks.indexOf(track);
1526 if (index >= 0) {
1527 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1528 return index;
1529 }
1530 mActiveTracksGeneration++;
1531 mLatestActiveTrack = track;
1532 ++mBatteryCounter[track->uid()].second;
1533 return mActiveTracks.add(track);
1534}
1535
1536template <typename T>
1537ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1538 ssize_t index = mActiveTracks.remove(track);
1539 if (index < 0) {
1540 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1541 return index;
1542 }
1543 mActiveTracksGeneration++;
1544 --mBatteryCounter[track->uid()].second;
1545 // mLatestActiveTrack is not cleared even if is the same as track.
1546 return index;
1547}
1548
1549template <typename T>
1550void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1551 for (const sp<T> &track : mActiveTracks) {
1552 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1553 }
1554 mLastActiveTracksGeneration = mActiveTracksGeneration;
1555 mActiveTracks.clear();
1556 mLatestActiveTrack.clear();
1557 mBatteryCounter.clear();
1558}
1559
1560template <typename T>
1561void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1562 sp<ThreadBase> thread, bool force) {
1563 // Updates ActiveTracks client uids to the thread wakelock.
1564 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1565 thread->updateWakeLockUids_l(getWakeLockUids());
1566 mLastActiveTracksGeneration = mActiveTracksGeneration;
1567 }
1568
1569 // Updates BatteryNotifier uids
1570 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1571 const uid_t uid = it->first;
1572 ssize_t &previous = it->second.first;
1573 ssize_t &current = it->second.second;
1574 if (current > 0) {
1575 if (previous == 0) {
1576 BatteryNotifier::getInstance().noteStartAudio(uid);
1577 }
1578 previous = current;
1579 ++it;
1580 } else if (current == 0) {
1581 if (previous > 0) {
1582 BatteryNotifier::getInstance().noteStopAudio(uid);
1583 }
1584 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1585 } else /* (current < 0) */ {
1586 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1587 }
1588 }
1589}
Eric Laurent83b88082014-06-20 18:31:16 -07001590
Eric Laurent81784c32012-11-19 14:55:58 -08001591// ----------------------------------------------------------------------------
1592// Playback
1593// ----------------------------------------------------------------------------
1594
1595AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1596 AudioStreamOut* output,
1597 audio_io_handle_t id,
1598 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001599 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001600 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001601 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001602 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001603 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001604 mMixerBuffer(NULL),
1605 mMixerBufferSize(0),
1606 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1607 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001608 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001609 mEffectBuffer(NULL),
1610 mEffectBufferSize(0),
1611 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1612 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001613 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001614 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001615 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001616 // mStreamTypes[] initialized in constructor body
1617 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001618 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001619 mMixerStatus(MIXER_IDLE),
1620 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001621 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001622 mBytesRemaining(0),
1623 mCurrentWriteLength(0),
1624 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001625 mWriteAckSequence(0),
1626 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001627 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001628 mScreenState(AudioFlinger::mScreenState),
1629 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001630 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001631 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001632{
Glenn Kastend7dca052015-03-05 16:05:54 -08001633 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1634 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001635
1636 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1637 // it would be safer to explicitly pass initial masterVolume/masterMute as
1638 // parameter.
1639 //
1640 // If the HAL we are using has support for master volume or master mute,
1641 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1642 // and the mute set to false).
1643 mMasterVolume = audioFlinger->masterVolume_l();
1644 mMasterMute = audioFlinger->masterMute_l();
1645 if (mOutput && mOutput->audioHwDev) {
1646 if (mOutput->audioHwDev->canSetMasterVolume()) {
1647 mMasterVolume = 1.0;
1648 }
1649
1650 if (mOutput->audioHwDev->canSetMasterMute()) {
1651 mMasterMute = false;
1652 }
1653 }
1654
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001655 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001656
Eric Laurent223fd5c2014-11-11 13:43:36 -08001657 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001658 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001659 stream = (audio_stream_type_t) (stream + 1)) {
1660 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1661 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1662 }
Eric Laurent81784c32012-11-19 14:55:58 -08001663}
1664
1665AudioFlinger::PlaybackThread::~PlaybackThread()
1666{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001667 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001668 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001669 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001670 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001671}
1672
1673void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1674{
1675 dumpInternals(fd, args);
1676 dumpTracks(fd, args);
1677 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001678 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001679}
1680
Glenn Kasten0f11b512014-01-31 16:18:54 -08001681void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001682{
1683 const size_t SIZE = 256;
1684 char buffer[SIZE];
1685 String8 result;
1686
Marco Nelissenb2208842014-02-07 14:00:50 -08001687 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001688 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1689 const stream_type_t *st = &mStreamTypes[i];
1690 if (i > 0) {
1691 result.appendFormat(", ");
1692 }
1693 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1694 if (st->mute) {
1695 result.append("M");
1696 }
1697 }
1698 result.append("\n");
1699 write(fd, result.string(), result.length());
1700 result.clear();
1701
Eric Laurent81784c32012-11-19 14:55:58 -08001702 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1703 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001704 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001705 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001706
1707 size_t numtracks = mTracks.size();
1708 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001709 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001710 size_t numactiveseen = 0;
1711 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001712 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001713 Track::appendDumpHeader(result);
1714 for (size_t i = 0; i < numtracks; ++i) {
1715 sp<Track> track = mTracks[i];
1716 if (track != 0) {
1717 bool active = mActiveTracks.indexOf(track) >= 0;
1718 if (active) {
1719 numactiveseen++;
1720 }
1721 track->dump(buffer, SIZE, active);
1722 result.append(buffer);
1723 }
1724 }
1725 } else {
1726 result.append("\n");
1727 }
1728 if (numactiveseen != numactive) {
1729 // some tracks in the active list were not in the tracks list
1730 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1731 " not in the track list\n");
1732 result.append(buffer);
1733 Track::appendDumpHeader(result);
1734 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001735 sp<Track> track = mActiveTracks[i];
1736 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001737 track->dump(buffer, SIZE, true);
1738 result.append(buffer);
1739 }
1740 }
1741 }
1742
1743 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001744}
1745
1746void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1747{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001748 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001749
1750 dumpBase(fd, args);
1751
Elliott Hughes87cebad2014-05-22 10:14:43 -07001752 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001753 dprintf(fd, " Last write occurred (msecs): %llu\n",
1754 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001755 dprintf(fd, " Total writes: %d\n", mNumWrites);
1756 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1757 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1758 dprintf(fd, " Suspend count: %d\n", mSuspended);
1759 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1760 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1761 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1762 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001763 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001764 AudioStreamOut *output = mOutput;
1765 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001766 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1767 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001768 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1769 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1770 if (mPipeSink.get() != nullptr) {
1771 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1772 }
1773 if (output != nullptr) {
1774 dprintf(fd, " Hal stream dump:\n");
1775 (void)output->stream->dump(fd);
1776 }
Eric Laurent81784c32012-11-19 14:55:58 -08001777}
1778
1779// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001780
1781void AudioFlinger::PlaybackThread::onFirstRef()
1782{
Glenn Kastend7dca052015-03-05 16:05:54 -08001783 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001784}
1785
1786// ThreadBase virtuals
1787void AudioFlinger::PlaybackThread::preExit()
1788{
1789 ALOGV(" preExit()");
1790 // FIXME this is using hard-coded strings but in the future, this functionality will be
1791 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001792 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1793 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001794}
1795
1796// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1797sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1798 const sp<AudioFlinger::Client>& client,
1799 audio_stream_type_t streamType,
1800 uint32_t sampleRate,
1801 audio_format_t format,
1802 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001803 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001804 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001805 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001806 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001807 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001808 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001809 status_t *status,
1810 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001811{
Glenn Kasten74935e42013-12-19 08:56:45 -08001812 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001813 sp<Track> track;
1814 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001815 audio_output_flags_t outputFlags = mOutput->flags;
1816
1817 // special case for FAST flag considered OK if fast mixer is present
1818 if (hasFastMixer()) {
1819 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1820 }
1821
1822 // Check if requested flags are compatible with output stream flags
1823 if ((*flags & outputFlags) != *flags) {
1824 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1825 *flags, outputFlags);
1826 *flags = (audio_output_flags_t)(*flags & outputFlags);
1827 }
Eric Laurent81784c32012-11-19 14:55:58 -08001828
Eric Laurent81784c32012-11-19 14:55:58 -08001829 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001830 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001831 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001832 // PCM data
1833 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001834 // TODO: extract as a data library function that checks that a computationally
1835 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001836 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001837 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1838 (channelMask == AUDIO_CHANNEL_OUT_MONO
1839 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001840 // hardware sample rate
1841 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001842 // normal mixer has an associated fast mixer
1843 hasFastMixer() &&
1844 // there are sufficient fast track slots available
1845 (mFastTrackAvailMask != 0)
1846 // FIXME test that MixerThread for this fast track has a capable output HAL
1847 // FIXME add a permission test also?
1848 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001849 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1850 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001851 // read the fast track multiplier property the first time it is needed
1852 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1853 if (ok != 0) {
1854 ALOGE("%s pthread_once failed: %d", __func__, ok);
1855 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001856 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001857 }
Eric Laurent4c415062016-06-17 16:14:16 -07001858
1859 // check compatibility with audio effects.
1860 { // scope for mLock
1861 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001862 for (audio_session_t session : {
1863 AUDIO_SESSION_OUTPUT_STAGE,
1864 AUDIO_SESSION_OUTPUT_MIX,
1865 sessionId,
1866 }) {
1867 sp<EffectChain> chain = getEffectChain_l(session);
1868 if (chain.get() != nullptr) {
1869 audio_output_flags_t old = *flags;
1870 chain->checkOutputFlagCompatibility(flags);
1871 if (old != *flags) {
1872 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1873 (int)session, (int)old, (int)*flags);
1874 }
Eric Laurent4c415062016-06-17 16:14:16 -07001875 }
1876 }
1877 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001878 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001879 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1880 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001881 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001882 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1883 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001884 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001885 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001886 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001887 audio_is_linear_pcm(format),
1888 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001889 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001890 }
1891 }
1892 // For normal PCM streaming tracks, update minimum frame count.
1893 // For compatibility with AudioTrack calculation, buffer depth is forced
1894 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1895 // This is probably too conservative, but legacy application code may depend on it.
1896 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001897 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001898 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001899 // this must match AudioTrack.cpp calculateMinFrameCount().
1900 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001901 uint32_t latencyMs = 0;
1902 lStatus = mOutput->stream->getLatency(&latencyMs);
1903 if (lStatus != OK) {
1904 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1905 goto Exit;
1906 }
Eric Laurent81784c32012-11-19 14:55:58 -08001907 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1908 if (minBufCount < 2) {
1909 minBufCount = 2;
1910 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001911 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1912 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001913 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001914 minBufCount * sourceFramesNeededWithTimestretch(
1915 sampleRate, mNormalFrameCount,
1916 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001917 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001918 frameCount = minFrameCount;
1919 }
Eric Laurent81784c32012-11-19 14:55:58 -08001920 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001921 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001922
Glenn Kastenc3df8382014-03-13 15:05:25 -07001923 switch (mType) {
1924
1925 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001926 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001927 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001928 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1929 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001930 sampleRate, format, channelMask, mOutput, mFormat);
1931 lStatus = BAD_VALUE;
1932 goto Exit;
1933 }
1934 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001935 break;
1936
1937 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001938 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001939 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1940 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941 sampleRate, format, channelMask, mOutput, mFormat);
1942 lStatus = BAD_VALUE;
1943 goto Exit;
1944 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001945 break;
1946
1947 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001948 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001949 ALOGE("createTrack_l() Bad parameter: format %#x \""
1950 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001951 format, mOutput, mFormat);
1952 lStatus = BAD_VALUE;
1953 goto Exit;
1954 }
Andy Hungcd044842014-08-07 11:04:34 -07001955 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001956 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1957 lStatus = BAD_VALUE;
1958 goto Exit;
1959 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001960 break;
1961
Eric Laurent81784c32012-11-19 14:55:58 -08001962 }
1963
1964 lStatus = initCheck();
1965 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001966 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001967 goto Exit;
1968 }
1969
1970 { // scope for mLock
1971 Mutex::Autolock _l(mLock);
1972
1973 // all tracks in same audio session must share the same routing strategy otherwise
1974 // conflicts will happen when tracks are moved from one output to another by audio policy
1975 // manager
1976 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1977 for (size_t i = 0; i < mTracks.size(); ++i) {
1978 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001979 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001980 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1981 if (sessionId == t->sessionId() && strategy != actual) {
1982 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1983 strategy, actual);
1984 lStatus = BAD_VALUE;
1985 goto Exit;
1986 }
1987 }
1988 }
1989
Glenn Kastend79072e2016-01-06 08:41:20 -08001990 track = new Track(this, client, streamType, sampleRate, format,
1991 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001992 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001993
Glenn Kasten03003332013-08-06 15:40:54 -07001994 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1995 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001996 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001997 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001998 goto Exit;
1999 }
2000 mTracks.add(track);
2001
2002 sp<EffectChain> chain = getEffectChain_l(sessionId);
2003 if (chain != 0) {
2004 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2005 track->setMainBuffer(chain->inBuffer());
2006 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2007 chain->incTrackCnt();
2008 }
2009
Eric Laurent05067782016-06-01 18:27:28 -07002010 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002011 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2012 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2013 // so ask activity manager to do this on our behalf
2014 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2015 }
2016 }
2017
2018 lStatus = NO_ERROR;
2019
2020Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002021 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002022 return track;
2023}
2024
2025uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2026{
2027 return latency;
2028}
2029
2030uint32_t AudioFlinger::PlaybackThread::latency() const
2031{
2032 Mutex::Autolock _l(mLock);
2033 return latency_l();
2034}
2035uint32_t AudioFlinger::PlaybackThread::latency_l() const
2036{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002037 uint32_t latency;
2038 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2039 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002040 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002041 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002042}
2043
2044void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2045{
2046 Mutex::Autolock _l(mLock);
2047 // Don't apply master volume in SW if our HAL can do it for us.
2048 if (mOutput && mOutput->audioHwDev &&
2049 mOutput->audioHwDev->canSetMasterVolume()) {
2050 mMasterVolume = 1.0;
2051 } else {
2052 mMasterVolume = value;
2053 }
2054}
2055
2056void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2057{
2058 Mutex::Autolock _l(mLock);
2059 // Don't apply master mute in SW if our HAL can do it for us.
2060 if (mOutput && mOutput->audioHwDev &&
2061 mOutput->audioHwDev->canSetMasterMute()) {
2062 mMasterMute = false;
2063 } else {
2064 mMasterMute = muted;
2065 }
2066}
2067
2068void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2069{
2070 Mutex::Autolock _l(mLock);
2071 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002072 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002073}
2074
2075void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2076{
2077 Mutex::Autolock _l(mLock);
2078 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002079 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002080}
2081
2082float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2083{
2084 Mutex::Autolock _l(mLock);
2085 return mStreamTypes[stream].volume;
2086}
2087
2088// addTrack_l() must be called with ThreadBase::mLock held
2089status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2090{
2091 status_t status = ALREADY_EXISTS;
2092
Eric Laurent81784c32012-11-19 14:55:58 -08002093 if (mActiveTracks.indexOf(track) < 0) {
2094 // the track is newly added, make sure it fills up all its
2095 // buffers before playing. This is to ensure the client will
2096 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002097 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002098 TrackBase::track_state state = track->mState;
2099 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002100 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002101 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002102 mLock.lock();
2103 // abort track was stopped/paused while we released the lock
2104 if (state != track->mState) {
2105 if (status == NO_ERROR) {
2106 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002107 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002108 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109 mLock.lock();
2110 }
2111 return INVALID_OPERATION;
2112 }
2113 // abort if start is rejected by audio policy manager
2114 if (status != NO_ERROR) {
2115 return PERMISSION_DENIED;
2116 }
2117#ifdef ADD_BATTERY_DATA
2118 // to track the speaker usage
2119 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2120#endif
2121 }
2122
Eric Laurent51716182016-02-29 18:00:56 -08002123 // set retry count for buffer fill
2124 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002125 if (track->isStopping_1()) {
2126 track->mRetryCount = kMaxTrackStopRetriesOffload;
2127 } else {
2128 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2129 }
2130 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002131 } else {
2132 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002133 track->mFillingUpStatus =
2134 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002135 }
2136
Eric Laurent81784c32012-11-19 14:55:58 -08002137 track->mResetDone = false;
2138 track->mPresentationCompleteFrames = 0;
2139 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002140 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2141 if (chain != 0) {
2142 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2143 track->sessionId());
2144 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002145 }
2146
Andy Hung2148bf02016-11-28 19:01:02 -08002147 char buffer[256];
2148 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2149 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2150
Eric Laurent81784c32012-11-19 14:55:58 -08002151 status = NO_ERROR;
2152 }
2153
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002154 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002155 return status;
2156}
2157
Eric Laurentbfb1b832013-01-07 09:53:42 -08002158bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002159{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002160 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002161 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2163 track->mState = TrackBase::STOPPED;
2164 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002165 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002166 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002167 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002168 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169
2170 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002171}
2172
2173void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2174{
2175 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002176
2177 char buffer[256];
2178 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2179 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2180
Eric Laurent81784c32012-11-19 14:55:58 -08002181 mTracks.remove(track);
2182 deleteTrackName_l(track->name());
2183 // redundant as track is about to be destroyed, for dumpsys only
2184 track->mName = -1;
2185 if (track->isFastTrack()) {
2186 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002187 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002188 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2189 mFastTrackAvailMask |= 1 << index;
2190 // redundant as track is about to be destroyed, for dumpsys only
2191 track->mFastIndex = -1;
2192 }
2193 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2194 if (chain != 0) {
2195 chain->decTrackCnt();
2196 }
2197}
2198
Eric Laurentede6c3b2013-09-19 14:37:46 -07002199void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200{
2201 // Thread could be blocked waiting for async
2202 // so signal it to handle state changes immediately
2203 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2204 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2205 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002206 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207}
2208
Eric Laurent81784c32012-11-19 14:55:58 -08002209String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2210{
Eric Laurent81784c32012-11-19 14:55:58 -08002211 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002212 String8 out_s8;
2213 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2214 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002215 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002216 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002217}
2218
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002219void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002220 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2221 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002222
Eric Laurent73e26b62015-04-27 16:55:58 -07002223 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002224
2225 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002226 case AUDIO_OUTPUT_OPENED:
2227 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002228 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002229 desc->mChannelMask = mChannelMask;
2230 desc->mSamplingRate = mSampleRate;
2231 desc->mFormat = mFormat;
2232 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002233 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002234 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002235 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002236 break;
2237
Eric Laurent73e26b62015-04-27 16:55:58 -07002238 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002239 default:
2240 break;
2241 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002242 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002245void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002246{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002247 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002248}
2249
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002250void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002252 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002253}
2254
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002255void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002256{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002257 mCallbackThread->setAsyncError();
2258}
2259
Eric Laurent3b4529e2013-09-05 18:09:19 -07002260void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002261{
2262 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002263 // reject out of sequence requests
2264 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2265 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002266 mWaitWorkCV.signal();
2267 }
2268}
2269
Eric Laurent3b4529e2013-09-05 18:09:19 -07002270void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002271{
2272 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002273 // reject out of sequence requests
2274 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2275 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002276 mWaitWorkCV.signal();
2277 }
2278}
2279
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002280void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002281{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002282 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002283 mSampleRate = mOutput->getSampleRate();
2284 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002285 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002286 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002287 }
Andy Hung9a592762014-07-21 21:56:01 -07002288 if ((mType == MIXER || mType == DUPLICATING)
2289 && !isValidPcmSinkChannelMask(mChannelMask)) {
2290 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2291 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002292 }
Andy Hunge5412692014-05-16 11:25:07 -07002293 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002294
2295 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002296 status_t result = mOutput->stream->getFormat(&mHALFormat);
2297 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002298 // Get format from the shim, which will be different than the HAL format
2299 // if playing compressed audio over HDMI passthrough.
2300 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002301 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002302 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002303 }
Andy Hung6146c082014-03-18 11:56:15 -07002304 if ((mType == MIXER || mType == DUPLICATING)
2305 && !isValidPcmSinkFormat(mFormat)) {
2306 LOG_FATAL("HAL format %#x not supported for mixed output",
2307 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002308 }
Phil Burk062e67a2015-02-11 13:40:50 -08002309 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002310 result = mOutput->stream->getBufferSize(&mBufferSize);
2311 LOG_ALWAYS_FATAL_IF(result != OK,
2312 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002313 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002314 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002315 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002316 mFrameCount);
2317 }
2318
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002319 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2320 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002322 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002323 }
2324 }
2325
Eric Laurentd1f69b02014-12-15 14:33:13 -08002326 mHwSupportsPause = false;
2327 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002328 bool supportsPause = false, supportsResume = false;
2329 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2330 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002331 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002332 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002333 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 } else if (supportsResume) {
2335 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002336 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002337 }
2338 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002339 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2340 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2341 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002342
Andy Hungfbfc3952015-01-15 13:33:51 -08002343 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2344 // For best precision, we use float instead of the associated output
2345 // device format (typically PCM 16 bit).
2346
2347 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2348 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2349 mBufferSize = mFrameSize * mFrameCount;
2350
2351 // TODO: We currently use the associated output device channel mask and sample rate.
2352 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2353 // (if a valid mask) to avoid premature downmix.
2354 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2355 // instead of the output device sample rate to avoid loss of high frequency information.
2356 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2357 }
2358
Andy Hung09a50072014-02-27 14:30:47 -08002359 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002360 double multiplier = 1.0;
2361 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2362 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002363 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2364 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002365
Eric Laurent81784c32012-11-19 14:55:58 -08002366 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2367 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2368 maxNormalFrameCount = maxNormalFrameCount & ~15;
2369 if (maxNormalFrameCount < minNormalFrameCount) {
2370 maxNormalFrameCount = minNormalFrameCount;
2371 }
2372 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2373 if (multiplier <= 1.0) {
2374 multiplier = 1.0;
2375 } else if (multiplier <= 2.0) {
2376 if (2 * mFrameCount <= maxNormalFrameCount) {
2377 multiplier = 2.0;
2378 } else {
2379 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2380 }
2381 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002382 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002383 }
2384 }
2385 mNormalFrameCount = multiplier * mFrameCount;
2386 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002387 if (mType == MIXER || mType == DUPLICATING) {
2388 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2389 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002390 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002391 mNormalFrameCount);
2392
Andy Hung08fb1742015-05-31 23:22:10 -07002393 // Check if we want to throttle the processing to no more than 2x normal rate
2394 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002395 mThreadThrottleTimeMs = 0;
2396 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002397 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2398
Andy Hung010a1a12014-03-13 13:57:33 -07002399 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2400 // Originally this was int16_t[] array, need to remove legacy implications.
2401 free(mSinkBuffer);
2402 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002403 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2404 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2405 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002406 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002407
Andy Hung69aed5f2014-02-25 17:24:40 -08002408 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2409 // drives the output.
2410 free(mMixerBuffer);
2411 mMixerBuffer = NULL;
2412 if (mMixerBufferEnabled) {
2413 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2414 mMixerBufferSize = mNormalFrameCount * mChannelCount
2415 * audio_bytes_per_sample(mMixerBufferFormat);
2416 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2417 }
Andy Hung98ef9782014-03-04 14:46:50 -08002418 free(mEffectBuffer);
2419 mEffectBuffer = NULL;
2420 if (mEffectBufferEnabled) {
2421 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2422 mEffectBufferSize = mNormalFrameCount * mChannelCount
2423 * audio_bytes_per_sample(mEffectBufferFormat);
2424 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2425 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002426
Eric Laurent81784c32012-11-19 14:55:58 -08002427 // force reconfiguration of effect chains and engines to take new buffer size and audio
2428 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002429 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002430 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2431 // matter.
2432 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2433 Vector< sp<EffectChain> > effectChains = mEffectChains;
2434 for (size_t i = 0; i < effectChains.size(); i ++) {
2435 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2436 }
2437}
2438
2439
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002440status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002441{
2442 if (halFrames == NULL || dspFrames == NULL) {
2443 return BAD_VALUE;
2444 }
2445 Mutex::Autolock _l(mLock);
2446 if (initCheck() != NO_ERROR) {
2447 return INVALID_OPERATION;
2448 }
Andy Hung818e7a32016-02-16 18:08:07 -08002449 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002450 *halFrames = framesWritten;
2451
2452 if (isSuspended()) {
2453 // return an estimation of rendered frames when the output is suspended
2454 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002455 *dspFrames = (uint32_t)
2456 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002457 return NO_ERROR;
2458 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002459 status_t status;
2460 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002461 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002462 *dspFrames = (size_t)frames;
2463 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002464 }
2465}
2466
Eric Laurent4c415062016-06-17 16:14:16 -07002467// hasAudioSession_l() must be called with ThreadBase::mLock held
2468uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002469{
Eric Laurent81784c32012-11-19 14:55:58 -08002470 uint32_t result = 0;
2471 if (getEffectChain_l(sessionId) != 0) {
2472 result = EFFECT_SESSION;
2473 }
2474
2475 for (size_t i = 0; i < mTracks.size(); ++i) {
2476 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002477 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002478 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002479 if (track->isFastTrack()) {
2480 result |= FAST_SESSION;
2481 }
Eric Laurent81784c32012-11-19 14:55:58 -08002482 break;
2483 }
2484 }
2485
2486 return result;
2487}
2488
Glenn Kastend848eb42016-03-08 13:42:11 -08002489uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002490{
2491 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2492 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2493 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2494 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2495 }
2496 for (size_t i = 0; i < mTracks.size(); i++) {
2497 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002498 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002499 return AudioSystem::getStrategyForStream(track->streamType());
2500 }
2501 }
2502 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2503}
2504
2505
Phil Burk062e67a2015-02-11 13:40:50 -08002506AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002507{
2508 Mutex::Autolock _l(mLock);
2509 return mOutput;
2510}
2511
Phil Burk062e67a2015-02-11 13:40:50 -08002512AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002513{
2514 Mutex::Autolock _l(mLock);
2515 AudioStreamOut *output = mOutput;
2516 mOutput = NULL;
2517 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2518 // must push a NULL and wait for ack
2519 mOutputSink.clear();
2520 mPipeSink.clear();
2521 mNormalSink.clear();
2522 return output;
2523}
2524
2525// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002526sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002527{
2528 if (mOutput == NULL) {
2529 return NULL;
2530 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002531 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002532}
2533
2534uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2535{
2536 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2537}
2538
2539status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2540{
2541 if (!isValidSyncEvent(event)) {
2542 return BAD_VALUE;
2543 }
2544
2545 Mutex::Autolock _l(mLock);
2546
2547 for (size_t i = 0; i < mTracks.size(); ++i) {
2548 sp<Track> track = mTracks[i];
2549 if (event->triggerSession() == track->sessionId()) {
2550 (void) track->setSyncEvent(event);
2551 return NO_ERROR;
2552 }
2553 }
2554
2555 return NAME_NOT_FOUND;
2556}
2557
2558bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2559{
2560 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2561}
2562
2563void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2564 const Vector< sp<Track> >& tracksToRemove)
2565{
2566 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002567 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002568 for (size_t i = 0 ; i < count ; i++) {
2569 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002570 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002571 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002572 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002573#ifdef ADD_BATTERY_DATA
2574 // to track the speaker usage
2575 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2576#endif
2577 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002578 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002579 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580 }
Eric Laurent81784c32012-11-19 14:55:58 -08002581 }
2582 }
2583 }
Eric Laurent81784c32012-11-19 14:55:58 -08002584}
2585
2586void AudioFlinger::PlaybackThread::checkSilentMode_l()
2587{
2588 if (!mMasterMute) {
2589 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002590 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2591 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2592 return;
2593 }
Eric Laurent81784c32012-11-19 14:55:58 -08002594 if (property_get("ro.audio.silent", value, "0") > 0) {
2595 char *endptr;
2596 unsigned long ul = strtoul(value, &endptr, 0);
2597 if (*endptr == '\0' && ul != 0) {
2598 ALOGD("Silence is golden");
2599 // The setprop command will not allow a property to be changed after
2600 // the first time it is set, so we don't have to worry about un-muting.
2601 setMasterMute_l(true);
2602 }
2603 }
2604 }
2605}
2606
2607// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002609{
Eric Laurent81784c32012-11-19 14:55:58 -08002610 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002611 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002612 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002613
2614 // If an NBAIO sink is present, use it to write the normal mixer's submix
2615 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002616
Andy Hung010a1a12014-03-13 13:57:33 -07002617 const size_t count = mBytesRemaining / mFrameSize;
2618
Simon Wilson2d590962012-11-29 15:18:50 -08002619 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002620 // update the setpoint when AudioFlinger::mScreenState changes
2621 uint32_t screenState = AudioFlinger::mScreenState;
2622 if (screenState != mScreenState) {
2623 mScreenState = screenState;
2624 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2625 if (pipe != NULL) {
2626 pipe->setAvgFrames((mScreenState & 1) ?
2627 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2628 }
2629 }
Andy Hung010a1a12014-03-13 13:57:33 -07002630 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002631 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002632 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002633 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002634 } else {
2635 bytesWritten = framesWritten;
2636 }
2637 // otherwise use the HAL / AudioStreamOut directly
2638 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002640
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002642 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2643 mWriteAckSequence += 2;
2644 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002646 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002647 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002648 // FIXME We should have an implementation of timestamps for direct output threads.
2649 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002650 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002651
Eric Laurentbfb1b832013-01-07 09:53:42 -08002652 if (mUseAsyncWrite &&
2653 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2654 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002655 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002656 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002657 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 }
Eric Laurent81784c32012-11-19 14:55:58 -08002659 }
2660
Eric Laurent81784c32012-11-19 14:55:58 -08002661 mNumWrites++;
2662 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002663 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 return bytesWritten;
2665}
2666
2667void AudioFlinger::PlaybackThread::threadLoop_drain()
2668{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002669 bool supportsDrain = false;
2670 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2672 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002673 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2674 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002676 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002678 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002679 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 }
2681}
2682
2683void AudioFlinger::PlaybackThread::threadLoop_exit()
2684{
Eric Laurent275e8e92014-11-30 15:14:47 -08002685 {
2686 Mutex::Autolock _l(mLock);
2687 for (size_t i = 0; i < mTracks.size(); i++) {
2688 sp<Track> track = mTracks[i];
2689 track->invalidate();
2690 }
Andy Hungdae27702016-10-31 14:01:16 -07002691 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2692 // After we exit there are no more track changes sent to BatteryNotifier
2693 // because that requires an active threadLoop.
2694 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2695 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002696 }
Eric Laurent81784c32012-11-19 14:55:58 -08002697}
2698
2699/*
2700The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002701 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002702 - mActiveSleepTimeUs from activeSleepTimeUs()
2703 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002704 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2705 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002706 - maxPeriod from frame count and sample rate (MIXER only)
2707
2708The parameters that affect these derived values are:
2709 - frame count
2710 - frame size
2711 - sample rate
2712 - device type: A2DP or not
2713 - device latency
2714 - format: PCM or not
2715 - active sleep time
2716 - idle sleep time
2717*/
2718
2719void AudioFlinger::PlaybackThread::cacheParameters_l()
2720{
Andy Hung25c2dac2014-02-27 14:56:00 -08002721 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002722 mActiveSleepTimeUs = activeSleepTimeUs();
2723 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002724
2725 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2726 // truncating audio when going to standby.
2727 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2728 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2729 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2730 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2731 }
2732 }
Eric Laurent81784c32012-11-19 14:55:58 -08002733}
2734
Eric Laurent13084622016-05-17 10:51:49 -07002735bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002736{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002737 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002738 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002739 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002740 size_t size = mTracks.size();
2741 for (size_t i = 0; i < size; i++) {
2742 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002743 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002744 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002745 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002746 }
2747 }
Eric Laurent13084622016-05-17 10:51:49 -07002748 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002749}
2750
Haynes Mathew George05317d22016-05-03 16:34:26 -07002751void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2752{
2753 Mutex::Autolock _l(mLock);
2754 invalidateTracks_l(streamType);
2755}
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2758{
Glenn Kastend848eb42016-03-08 13:42:11 -08002759 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002760 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2761 status_t result = EffectBufferHalInterface::mirror(
2762 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2763 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2764 &halInBuffer);
2765 if (result != OK) return result;
2766 halOutBuffer = halInBuffer;
2767 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002768
2769 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002770 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002771 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002772 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002773 if (mType != DIRECT) {
2774 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002775 status_t result = EffectBufferHalInterface::allocate(
2776 numSamples * sizeof(int16_t),
2777 &halInBuffer);
2778 if (result != OK) return result;
2779 buffer = halInBuffer->audioBuffer()->s16;
2780 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2781 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002782 }
2783
2784 // Attach all tracks with same session ID to this chain.
2785 for (size_t i = 0; i < mTracks.size(); ++i) {
2786 sp<Track> track = mTracks[i];
2787 if (session == track->sessionId()) {
2788 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2789 buffer);
2790 track->setMainBuffer(buffer);
2791 chain->incTrackCnt();
2792 }
2793 }
2794
2795 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002796 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002797 if (session == track->sessionId()) {
2798 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2799 chain->incActiveTrackCnt();
2800 }
2801 }
2802 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002803 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002804 chain->setInBuffer(halInBuffer);
2805 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002807 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002808 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2809 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002810 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002812 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002813 // Effect chain for other sessions are inserted at beginning of effect
2814 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002815 // sessions is not important.
2816 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2817 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2818 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002819 size_t size = mEffectChains.size();
2820 size_t i = 0;
2821 for (i = 0; i < size; i++) {
2822 if (mEffectChains[i]->sessionId() < session) {
2823 break;
2824 }
2825 }
2826 mEffectChains.insertAt(chain, i);
2827 checkSuspendOnAddEffectChain_l(chain);
2828
2829 return NO_ERROR;
2830}
2831
2832size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2833{
Glenn Kastend848eb42016-03-08 13:42:11 -08002834 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002835
2836 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2837
2838 for (size_t i = 0; i < mEffectChains.size(); i++) {
2839 if (chain == mEffectChains[i]) {
2840 mEffectChains.removeAt(i);
2841 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002842 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002843 if (session == track->sessionId()) {
2844 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2845 chain.get(), session);
2846 chain->decActiveTrackCnt();
2847 }
2848 }
2849
2850 // detach all tracks with same session ID from this chain
2851 for (size_t i = 0; i < mTracks.size(); ++i) {
2852 sp<Track> track = mTracks[i];
2853 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002854 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002855 chain->decTrackCnt();
2856 }
2857 }
2858 break;
2859 }
2860 }
2861 return mEffectChains.size();
2862}
2863
2864status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002865 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002866{
2867 Mutex::Autolock _l(mLock);
2868 return attachAuxEffect_l(track, EffectId);
2869}
2870
2871status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002872 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002873{
2874 status_t status = NO_ERROR;
2875
2876 if (EffectId == 0) {
2877 track->setAuxBuffer(0, NULL);
2878 } else {
2879 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2880 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2881 if (effect != 0) {
2882 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2883 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2884 } else {
2885 status = INVALID_OPERATION;
2886 }
2887 } else {
2888 status = BAD_VALUE;
2889 }
2890 }
2891 return status;
2892}
2893
2894void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2895{
2896 for (size_t i = 0; i < mTracks.size(); ++i) {
2897 sp<Track> track = mTracks[i];
2898 if (track->auxEffectId() == effectId) {
2899 attachAuxEffect_l(track, 0);
2900 }
2901 }
2902}
2903
2904bool AudioFlinger::PlaybackThread::threadLoop()
2905{
2906 Vector< sp<Track> > tracksToRemove;
2907
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002908 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002909 nsecs_t lastWriteFinished = -1; // time last server write completed
2910 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002911
2912 // MIXER
2913 nsecs_t lastWarning = 0;
2914
2915 // DUPLICATING
2916 // FIXME could this be made local to while loop?
2917 writeFrames = 0;
2918
2919 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002920 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002921
2922 if (mType == MIXER) {
2923 sleepTimeShift = 0;
2924 }
2925
2926 CpuStats cpuStats;
2927 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2928
2929 acquireWakeLock();
2930
Glenn Kasten9e58b552013-01-18 15:09:48 -08002931 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2932 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2933 // and then that string will be logged at the next convenient opportunity.
2934 const char *logString = NULL;
2935
Eric Laurent664539d2013-09-23 18:24:31 -07002936 checkSilentMode_l();
2937
Eric Laurent81784c32012-11-19 14:55:58 -08002938 while (!exitPending())
2939 {
2940 cpuStats.sample(myName);
2941
2942 Vector< sp<EffectChain> > effectChains;
2943
Eric Laurent81784c32012-11-19 14:55:58 -08002944 { // scope for mLock
2945
2946 Mutex::Autolock _l(mLock);
2947
Eric Laurent021cf962014-05-13 10:18:14 -07002948 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002949
Glenn Kasten9e58b552013-01-18 15:09:48 -08002950 if (logString != NULL) {
2951 mNBLogWriter->logTimestamp();
2952 mNBLogWriter->log(logString);
2953 logString = NULL;
2954 }
2955
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002956 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002957 // and associate with the sink frames written out. We need
2958 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002959 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002960 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002961 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002962 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002963 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002964 ExtendedTimestamp timestamp; // use private copy to fetch
2965 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002966
2967 // We keep track of the last valid kernel position in case we are in underrun
2968 // and the normal mixer period is the same as the fast mixer period, or there
2969 // is some error from the HAL.
2970 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2971 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2972 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2973 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2974 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2975
2976 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2977 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2978 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2979 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002980 }
2981
2982 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2983 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002984 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002985 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002986 }
2987
Andy Hung818e7a32016-02-16 18:08:07 -08002988 // copy over kernel info
2989 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002990 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2991 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002992 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2993 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002994 }
2995 // mFramesWritten for non-offloaded tracks are contiguous
2996 // even after standby() is called. This is useful for the track frame
2997 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002998 bool serverLocationUpdate = false;
2999 if (mFramesWritten != lastFramesWritten) {
3000 serverLocationUpdate = true;
3001 lastFramesWritten = mFramesWritten;
3002 }
3003 // Only update timestamps if there is a meaningful change.
3004 // Either the kernel timestamp must be valid or we have written something.
3005 if (kernelLocationUpdate || serverLocationUpdate) {
3006 if (serverLocationUpdate) {
3007 // use the time before we called the HAL write - it is a bit more accurate
3008 // to when the server last read data than the current time here.
3009 //
3010 // If we haven't written anything, mLastWriteTime will be -1
3011 // and we use systemTime().
3012 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3013 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3014 ? systemTime() : mLastWriteTime;
3015 }
Andy Hungdae27702016-10-31 14:01:16 -07003016
3017 for (const sp<Track> &t : mActiveTracks) {
3018 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003019 t->updateTrackFrameInfo(
3020 t->mAudioTrackServerProxy->framesReleased(),
3021 mFramesWritten,
3022 mTimestamp);
3023 }
Andy Hunge10393e2015-06-12 13:59:33 -07003024 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003025 }
3026
Eric Laurent81784c32012-11-19 14:55:58 -08003027 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003028 if (mSignalPending) {
3029 // A signal was raised while we were unlocked
3030 mSignalPending = false;
3031 } else if (waitingAsyncCallback_l()) {
3032 if (exitPending()) {
3033 break;
3034 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003035 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003036 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003037 releaseWakeLock_l();
3038 released = true;
3039 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040 ALOGV("wait async completion");
3041 mWaitWorkCV.wait(mLock);
3042 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003043 if (released) {
3044 acquireWakeLock_l();
3045 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003046 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3047 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003048
3049 continue;
3050 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003051 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003052 isSuspended()) {
3053 // put audio hardware into standby after short delay
3054 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003055
3056 threadLoop_standby();
3057
3058 mStandby = true;
3059 }
3060
3061 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3062 // we're about to wait, flush the binder command buffer
3063 IPCThreadState::self()->flushCommands();
3064
3065 clearOutputTracks();
3066
3067 if (exitPending()) {
3068 break;
3069 }
3070
3071 releaseWakeLock_l();
3072 // wait until we have something to do...
3073 ALOGV("%s going to sleep", myName.string());
3074 mWaitWorkCV.wait(mLock);
3075 ALOGV("%s waking up", myName.string());
3076 acquireWakeLock_l();
3077
3078 mMixerStatus = MIXER_IDLE;
3079 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3080 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003082 checkSilentMode_l();
3083
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003084 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3085 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003086 if (mType == MIXER) {
3087 sleepTimeShift = 0;
3088 }
3089
3090 continue;
3091 }
3092 }
Eric Laurent81784c32012-11-19 14:55:58 -08003093 // mMixerStatusIgnoringFastTracks is also updated internally
3094 mMixerStatus = prepareTracks_l(&tracksToRemove);
3095
Andy Hungdae27702016-10-31 14:01:16 -07003096 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003097
Eric Laurent81784c32012-11-19 14:55:58 -08003098 // prevent any changes in effect chain list and in each effect chain
3099 // during mixing and effect process as the audio buffers could be deleted
3100 // or modified if an effect is created or deleted
3101 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003102 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003103
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104 if (mBytesRemaining == 0) {
3105 mCurrentWriteLength = 0;
3106 if (mMixerStatus == MIXER_TRACKS_READY) {
3107 // threadLoop_mix() sets mCurrentWriteLength
3108 threadLoop_mix();
3109 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3110 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003111 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 // must be written to HAL
3113 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003115 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 }
3117 }
Andy Hung98ef9782014-03-04 14:46:50 -08003118 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003119 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003120 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3121 // or mSinkBuffer (if there are no effects).
3122 //
3123 // This is done pre-effects computation; if effects change to
3124 // support higher precision, this needs to move.
3125 //
3126 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003127 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003128 if (mMixerBufferValid) {
3129 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3130 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3131
Andy Hung2ddee192015-12-18 17:34:44 -08003132 // mono blend occurs for mixer threads only (not direct or offloaded)
3133 // and is handled here if we're going directly to the sink.
3134 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003135 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3136 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003137 }
3138
Andy Hung98ef9782014-03-04 14:46:50 -08003139 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3140 mNormalFrameCount * mChannelCount);
3141 }
3142
Eric Laurentbfb1b832013-01-07 09:53:42 -08003143 mBytesRemaining = mCurrentWriteLength;
3144 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003145 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3146 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3147 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3148 mBytesWritten += mBytesRemaining;
3149 mFramesWritten += framesRemaining;
3150 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 mBytesRemaining = 0;
3152 }
Eric Laurent81784c32012-11-19 14:55:58 -08003153
Eric Laurentbfb1b832013-01-07 09:53:42 -08003154 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003155 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156 for (size_t i = 0; i < effectChains.size(); i ++) {
3157 effectChains[i]->process_l();
3158 }
Eric Laurent81784c32012-11-19 14:55:58 -08003159 }
3160 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003161 // Process effect chains for offloaded thread even if no audio
3162 // was read from audio track: process only updates effect state
3163 // and thus does have to be synchronized with audio writes but may have
3164 // to be called while waiting for async write callback
3165 if (mType == OFFLOAD) {
3166 for (size_t i = 0; i < effectChains.size(); i ++) {
3167 effectChains[i]->process_l();
3168 }
3169 }
Eric Laurent81784c32012-11-19 14:55:58 -08003170
Andy Hung98ef9782014-03-04 14:46:50 -08003171 // Only if the Effects buffer is enabled and there is data in the
3172 // Effects buffer (buffer valid), we need to
3173 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003174 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003175 if (mEffectBufferValid) {
3176 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003177
3178 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003179 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3180 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003181 }
3182
Andy Hung98ef9782014-03-04 14:46:50 -08003183 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3184 mNormalFrameCount * mChannelCount);
3185 }
3186
Eric Laurent81784c32012-11-19 14:55:58 -08003187 // enable changes in effect chain
3188 unlockEffectChains(effectChains);
3189
Eric Laurentbfb1b832013-01-07 09:53:42 -08003190 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003191 // mSleepTimeUs == 0 means we must write to audio hardware
3192 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003193 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003194 // We save lastWriteFinished here, as previousLastWriteFinished,
3195 // for throttling. On thread start, previousLastWriteFinished will be
3196 // set to -1, which properly results in no throttling after the first write.
3197 nsecs_t previousLastWriteFinished = lastWriteFinished;
3198 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003200 // FIXME rewrite to reduce number of system calls
3201 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003202 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003203 lastWriteFinished = systemTime();
3204 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 if (ret < 0) {
3206 mBytesRemaining = 0;
3207 } else {
3208 mBytesWritten += ret;
3209 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003210 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003211 }
3212 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3213 (mMixerStatus == MIXER_DRAIN_ALL)) {
3214 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003215 }
Andy Hung08fb1742015-05-31 23:22:10 -07003216 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003217 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003218 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003219 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003220 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003221 ATRACE_NAME("underrun");
3222 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003223 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003224 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003225 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003226 }
Andy Hung08fb1742015-05-31 23:22:10 -07003227
3228 if (mThreadThrottle
3229 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3230 && ret > 0) { // we wrote something
3231 // Limit MixerThread data processing to no more than twice the
3232 // expected processing rate.
3233 //
3234 // This helps prevent underruns with NuPlayer and other applications
3235 // which may set up buffers that are close to the minimum size, or use
3236 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3237 //
3238 // The throttle smooths out sudden large data drains from the device,
3239 // e.g. when it comes out of standby, which often causes problems with
3240 // (1) mixer threads without a fast mixer (which has its own warm-up)
3241 // (2) minimum buffer sized tracks (even if the track is full,
3242 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003243 //
3244 // Total time spent in last processing cycle equals time spent in
3245 // 1. threadLoop_write, as well as time spent in
3246 // 2. threadLoop_mix (significant for heavy mixing, especially
3247 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003248
Andy Hung69488c42016-05-16 18:43:33 -07003249 // it's OK if deltaMs is an overestimate.
3250 const int32_t deltaMs =
3251 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003252 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3253 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3254 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003255 // notify of throttle start on verbose log
3256 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3257 "mixer(%p) throttle begin:"
3258 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003259 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003260 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003261 // Throttle must be attributed to the previous mixer loop's write time
3262 // to allow back-to-back throttling.
3263 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003264 } else {
3265 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3266 if (diff > 0) {
3267 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003268 // but prevent spamming for bluetooth
3269 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3270 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003271 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3272 }
Andy Hung08fb1742015-05-31 23:22:10 -07003273 }
3274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 }
Eric Laurent81784c32012-11-19 14:55:58 -08003276
Eric Laurentbfb1b832013-01-07 09:53:42 -08003277 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003278 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003279 Mutex::Autolock _l(mLock);
3280 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3281 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003282 }
Glenn Kastene7754022014-10-31 12:11:26 -07003283 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 }
Eric Laurent81784c32012-11-19 14:55:58 -08003285 }
3286
3287 // Finally let go of removed track(s), without the lock held
3288 // since we can't guarantee the destructors won't acquire that
3289 // same lock. This will also mutate and push a new fast mixer state.
3290 threadLoop_removeTracks(tracksToRemove);
3291 tracksToRemove.clear();
3292
3293 // FIXME I don't understand the need for this here;
3294 // it was in the original code but maybe the
3295 // assignment in saveOutputTracks() makes this unnecessary?
3296 clearOutputTracks();
3297
3298 // Effect chains will be actually deleted here if they were removed from
3299 // mEffectChains list during mixing or effects processing
3300 effectChains.clear();
3301
3302 // FIXME Note that the above .clear() is no longer necessary since effectChains
3303 // is now local to this block, but will keep it for now (at least until merge done).
3304 }
3305
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 threadLoop_exit();
3307
Eric Laurentcf817a22014-08-04 20:36:31 -07003308 if (!mStandby) {
3309 threadLoop_standby();
3310 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003311 }
3312
3313 releaseWakeLock();
3314
3315 ALOGV("Thread %p type %d exiting", this, mType);
3316 return false;
3317}
3318
Eric Laurentbfb1b832013-01-07 09:53:42 -08003319// removeTracks_l() must be called with ThreadBase::mLock held
3320void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3321{
3322 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003323 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003324 for (size_t i=0 ; i<count ; i++) {
3325 const sp<Track>& track = tracksToRemove.itemAt(i);
3326 mActiveTracks.remove(track);
3327 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3328 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3329 if (chain != 0) {
3330 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3331 track->sessionId());
3332 chain->decActiveTrackCnt();
3333 }
3334 if (track->isTerminated()) {
3335 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003336 } else { // inactive but not terminated
3337 char buffer[256];
3338 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3339 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 }
3341 }
3342 }
3343
3344}
Eric Laurent81784c32012-11-19 14:55:58 -08003345
Eric Laurentaccc1472013-09-20 09:36:34 -07003346status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3347{
3348 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003349 ExtendedTimestamp ets;
3350 status_t status = mNormalSink->getTimestamp(ets);
3351 if (status == NO_ERROR) {
3352 status = ets.getBestTimestamp(&timestamp);
3353 }
3354 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003355 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003356 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003357 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003358 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003359 timestamp.mPosition = (uint32_t)position64;
3360 return NO_ERROR;
3361 }
3362 }
3363 return INVALID_OPERATION;
3364}
Eric Laurent1c333e22014-05-20 10:48:17 -07003365
Eric Laurent054d9d32015-04-24 08:48:48 -07003366status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3367 audio_patch_handle_t *handle)
3368{
Andy Hungf60abce2016-08-26 11:37:54 -07003369 status_t status;
3370 if (property_get_bool("af.patch_park", false /* default_value */)) {
3371 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3372 // or if HAL does not properly lock against access.
3373 AutoPark<FastMixer> park(mFastMixer);
3374 status = PlaybackThread::createAudioPatch_l(patch, handle);
3375 } else {
3376 status = PlaybackThread::createAudioPatch_l(patch, handle);
3377 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003378 return status;
3379}
3380
Eric Laurent1c333e22014-05-20 10:48:17 -07003381status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3382 audio_patch_handle_t *handle)
3383{
3384 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003385
3386 // store new device and send to effects
3387 audio_devices_t type = AUDIO_DEVICE_NONE;
3388 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3389 type |= patch->sinks[i].ext.device.type;
3390 }
3391
3392#ifdef ADD_BATTERY_DATA
3393 // when changing the audio output device, call addBatteryData to notify
3394 // the change
3395 if (mOutDevice != type) {
3396 uint32_t params = 0;
3397 // check whether speaker is on
3398 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3399 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003400 }
3401
Eric Laurent054d9d32015-04-24 08:48:48 -07003402 audio_devices_t deviceWithoutSpeaker
3403 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3404 // check if any other device (except speaker) is on
3405 if (type & deviceWithoutSpeaker) {
3406 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3407 }
3408
3409 if (params != 0) {
3410 addBatteryData(params);
3411 }
3412 }
3413#endif
3414
3415 for (size_t i = 0; i < mEffectChains.size(); i++) {
3416 mEffectChains[i]->setDevice_l(type);
3417 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003418
3419 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3420 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3421 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003422 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003423 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003424
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003425 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003426 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3427 status = hwDevice->createAudioPatch(patch->num_sources,
3428 patch->sources,
3429 patch->num_sinks,
3430 patch->sinks,
3431 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003432 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003433 char *address;
3434 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3435 //FIXME: we only support address on first sink with HAL version < 3.0
3436 address = audio_device_address_to_parameter(
3437 patch->sinks[0].ext.device.type,
3438 patch->sinks[0].ext.device.address);
3439 } else {
3440 address = (char *)calloc(1, 1);
3441 }
3442 AudioParameter param = AudioParameter(String8(address));
3443 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003444 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003445 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003446 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003447 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003448 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003449 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003450 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3451 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003452 return status;
3453}
3454
Eric Laurent054d9d32015-04-24 08:48:48 -07003455status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3456{
Andy Hungf60abce2016-08-26 11:37:54 -07003457 status_t status;
3458 if (property_get_bool("af.patch_park", false /* default_value */)) {
3459 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3460 // or if HAL does not properly lock against access.
3461 AutoPark<FastMixer> park(mFastMixer);
3462 status = PlaybackThread::releaseAudioPatch_l(handle);
3463 } else {
3464 status = PlaybackThread::releaseAudioPatch_l(handle);
3465 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003466 return status;
3467}
3468
Eric Laurent1c333e22014-05-20 10:48:17 -07003469status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3470{
3471 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003472
3473 mOutDevice = AUDIO_DEVICE_NONE;
3474
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003475 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003476 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3477 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003478 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003479 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003480 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003481 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003482 }
3483 return status;
3484}
3485
Eric Laurent83b88082014-06-20 18:31:16 -07003486void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3487{
3488 Mutex::Autolock _l(mLock);
3489 mTracks.add(track);
3490}
3491
3492void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3493{
3494 Mutex::Autolock _l(mLock);
3495 destroyTrack_l(track);
3496}
3497
3498void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3499{
3500 ThreadBase::getAudioPortConfig(config);
3501 config->role = AUDIO_PORT_ROLE_SOURCE;
3502 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3503 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3504}
3505
Eric Laurent81784c32012-11-19 14:55:58 -08003506// ----------------------------------------------------------------------------
3507
3508AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003509 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3510 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003511 // mAudioMixer below
3512 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003513 mFastMixerFutex(0),
3514 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003515 // mOutputSink below
3516 // mPipeSink below
3517 // mNormalSink below
3518{
3519 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003520 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3521 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003522 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3523 mNormalFrameCount);
3524 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3525
Andy Hungfbfc3952015-01-15 13:33:51 -08003526 if (type == DUPLICATING) {
3527 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3528 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3529 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3530 return;
3531 }
Eric Laurent81784c32012-11-19 14:55:58 -08003532 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003533 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003534 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003535 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003536#if !LOG_NDEBUG
3537 ssize_t index =
3538#else
3539 (void)
3540#endif
3541 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003542 ALOG_ASSERT(index == 0);
3543
3544 // initialize fast mixer depending on configuration
3545 bool initFastMixer;
3546 switch (kUseFastMixer) {
3547 case FastMixer_Never:
3548 initFastMixer = false;
3549 break;
3550 case FastMixer_Always:
3551 initFastMixer = true;
3552 break;
3553 case FastMixer_Static:
3554 case FastMixer_Dynamic:
3555 initFastMixer = mFrameCount < mNormalFrameCount;
3556 break;
3557 }
3558 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003559 audio_format_t fastMixerFormat;
3560 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3561 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3562 } else {
3563 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3564 }
3565 if (mFormat != fastMixerFormat) {
3566 // change our Sink format to accept our intermediate precision
3567 mFormat = fastMixerFormat;
3568 free(mSinkBuffer);
3569 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3570 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3571 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3572 }
Eric Laurent81784c32012-11-19 14:55:58 -08003573
3574 // create a MonoPipe to connect our submix to FastMixer
3575 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003576#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003577 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003578#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003579 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003580 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003581 format.mFormat = fastMixerFormat;
3582 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3583
Eric Laurent81784c32012-11-19 14:55:58 -08003584 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3585 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3586 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3587 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3588 const NBAIO_Format offers[1] = {format};
3589 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003590#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003591 ssize_t index =
3592#else
3593 (void)
3594#endif
3595 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003596 ALOG_ASSERT(index == 0);
3597 monoPipe->setAvgFrames((mScreenState & 1) ?
3598 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3599 mPipeSink = monoPipe;
3600
Glenn Kasten46909e72013-02-26 09:20:22 -08003601#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003602 if (mTeeSinkOutputEnabled) {
3603 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003604 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3605 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003606 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003607 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003608 ALOG_ASSERT(index == 0);
3609 mTeeSink = teeSink;
3610 PipeReader *teeSource = new PipeReader(*teeSink);
3611 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003612 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003613 ALOG_ASSERT(index == 0);
3614 mTeeSource = teeSource;
3615 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003616#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003617
3618 // create fast mixer and configure it initially with just one fast track for our submix
3619 mFastMixer = new FastMixer();
3620 FastMixerStateQueue *sq = mFastMixer->sq();
3621#ifdef STATE_QUEUE_DUMP
3622 sq->setObserverDump(&mStateQueueObserverDump);
3623 sq->setMutatorDump(&mStateQueueMutatorDump);
3624#endif
3625 FastMixerState *state = sq->begin();
3626 FastTrack *fastTrack = &state->mFastTracks[0];
3627 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3628 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3629 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003630 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3631 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003632 fastTrack->mGeneration++;
3633 state->mFastTracksGen++;
3634 state->mTrackMask = 1;
3635 // fast mixer will use the HAL output sink
3636 state->mOutputSink = mOutputSink.get();
3637 state->mOutputSinkGen++;
3638 state->mFrameCount = mFrameCount;
3639 state->mCommand = FastMixerState::COLD_IDLE;
3640 // already done in constructor initialization list
3641 //mFastMixerFutex = 0;
3642 state->mColdFutexAddr = &mFastMixerFutex;
3643 state->mColdGen++;
3644 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003645#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003646 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003647#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003648 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3649 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003650 sq->end();
3651 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3652
3653 // start the fast mixer
3654 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3655 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003656 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003657 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003658
3659#ifdef AUDIO_WATCHDOG
3660 // create and start the watchdog
3661 mAudioWatchdog = new AudioWatchdog();
3662 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3663 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3664 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003665 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003666#endif
3667
Eric Laurent81784c32012-11-19 14:55:58 -08003668 }
3669
3670 switch (kUseFastMixer) {
3671 case FastMixer_Never:
3672 case FastMixer_Dynamic:
3673 mNormalSink = mOutputSink;
3674 break;
3675 case FastMixer_Always:
3676 mNormalSink = mPipeSink;
3677 break;
3678 case FastMixer_Static:
3679 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3680 break;
3681 }
3682}
3683
3684AudioFlinger::MixerThread::~MixerThread()
3685{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003686 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003687 FastMixerStateQueue *sq = mFastMixer->sq();
3688 FastMixerState *state = sq->begin();
3689 if (state->mCommand == FastMixerState::COLD_IDLE) {
3690 int32_t old = android_atomic_inc(&mFastMixerFutex);
3691 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003692 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003693 }
3694 }
3695 state->mCommand = FastMixerState::EXIT;
3696 sq->end();
3697 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3698 mFastMixer->join();
3699 // Though the fast mixer thread has exited, it's state queue is still valid.
3700 // We'll use that extract the final state which contains one remaining fast track
3701 // corresponding to our sub-mix.
3702 state = sq->begin();
3703 ALOG_ASSERT(state->mTrackMask == 1);
3704 FastTrack *fastTrack = &state->mFastTracks[0];
3705 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3706 delete fastTrack->mBufferProvider;
3707 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003708 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003709#ifdef AUDIO_WATCHDOG
3710 if (mAudioWatchdog != 0) {
3711 mAudioWatchdog->requestExit();
3712 mAudioWatchdog->requestExitAndWait();
3713 mAudioWatchdog.clear();
3714 }
3715#endif
3716 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003717 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003718 delete mAudioMixer;
3719}
3720
3721
3722uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3723{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003724 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003725 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3726 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3727 }
3728 return latency;
3729}
3730
3731
3732void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3733{
3734 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3735}
3736
Eric Laurentbfb1b832013-01-07 09:53:42 -08003737ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003738{
3739 // FIXME we should only do one push per cycle; confirm this is true
3740 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003741 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003742 FastMixerStateQueue *sq = mFastMixer->sq();
3743 FastMixerState *state = sq->begin();
3744 if (state->mCommand != FastMixerState::MIX_WRITE &&
3745 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3746 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003747
3748 // FIXME workaround for first HAL write being CPU bound on some devices
3749 ATRACE_BEGIN("write");
3750 mOutput->write((char *)mSinkBuffer, 0);
3751 ATRACE_END();
3752
Eric Laurent81784c32012-11-19 14:55:58 -08003753 int32_t old = android_atomic_inc(&mFastMixerFutex);
3754 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003755 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003756 }
3757#ifdef AUDIO_WATCHDOG
3758 if (mAudioWatchdog != 0) {
3759 mAudioWatchdog->resume();
3760 }
3761#endif
3762 }
3763 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003764#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003765 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003766 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003767#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003768 sq->end();
3769 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3770 if (kUseFastMixer == FastMixer_Dynamic) {
3771 mNormalSink = mPipeSink;
3772 }
3773 } else {
3774 sq->end(false /*didModify*/);
3775 }
3776 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003777 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003778}
3779
3780void AudioFlinger::MixerThread::threadLoop_standby()
3781{
3782 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003783 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003784 FastMixerStateQueue *sq = mFastMixer->sq();
3785 FastMixerState *state = sq->begin();
3786 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003787 // Report any frames trapped in the Monopipe
3788 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3789 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3790 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3791 "monoPipeWritten:%lld monoPipeLeft:%lld",
3792 (long long)mFramesWritten, (long long)mSuspendedFrames,
3793 (long long)mPipeSink->framesWritten(), pipeFrames);
3794 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3795
Eric Laurent81784c32012-11-19 14:55:58 -08003796 state->mCommand = FastMixerState::COLD_IDLE;
3797 state->mColdFutexAddr = &mFastMixerFutex;
3798 state->mColdGen++;
3799 mFastMixerFutex = 0;
3800 sq->end();
3801 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3802 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3803 if (kUseFastMixer == FastMixer_Dynamic) {
3804 mNormalSink = mOutputSink;
3805 }
3806#ifdef AUDIO_WATCHDOG
3807 if (mAudioWatchdog != 0) {
3808 mAudioWatchdog->pause();
3809 }
3810#endif
3811 } else {
3812 sq->end(false /*didModify*/);
3813 }
3814 }
3815 PlaybackThread::threadLoop_standby();
3816}
3817
Eric Laurentbfb1b832013-01-07 09:53:42 -08003818bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3819{
3820 return false;
3821}
3822
3823bool AudioFlinger::PlaybackThread::shouldStandby_l()
3824{
3825 return !mStandby;
3826}
3827
3828bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3829{
3830 Mutex::Autolock _l(mLock);
3831 return waitingAsyncCallback_l();
3832}
3833
Eric Laurent81784c32012-11-19 14:55:58 -08003834// shared by MIXER and DIRECT, overridden by DUPLICATING
3835void AudioFlinger::PlaybackThread::threadLoop_standby()
3836{
3837 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003838 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003839 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003840 // discard any pending drain or write ack by incrementing sequence
3841 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3842 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003843 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003844 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3845 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003846 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003847 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003848}
3849
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003850void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3851{
3852 ALOGV("signal playback thread");
3853 broadcast_l();
3854}
3855
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003856void AudioFlinger::PlaybackThread::onAsyncError()
3857{
3858 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3859 invalidateTracks((audio_stream_type_t)i);
3860 }
3861}
3862
Eric Laurent81784c32012-11-19 14:55:58 -08003863void AudioFlinger::MixerThread::threadLoop_mix()
3864{
Eric Laurent81784c32012-11-19 14:55:58 -08003865 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003866 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003867 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003868 // increase sleep time progressively when application underrun condition clears.
3869 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3870 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3871 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003872 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003873 sleepTimeShift--;
3874 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003875 mSleepTimeUs = 0;
3876 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003877 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003878
Eric Laurent81784c32012-11-19 14:55:58 -08003879}
3880
3881void AudioFlinger::MixerThread::threadLoop_sleepTime()
3882{
3883 // If no tracks are ready, sleep once for the duration of an output
3884 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003885 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003886 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003887 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3888 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3889 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003890 }
3891 // reduce sleep time in case of consecutive application underruns to avoid
3892 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3893 // duration we would end up writing less data than needed by the audio HAL if
3894 // the condition persists.
3895 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3896 sleepTimeShift++;
3897 }
3898 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003899 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003900 }
3901 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003902 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3903 // before effects processing or output.
3904 if (mMixerBufferValid) {
3905 memset(mMixerBuffer, 0, mMixerBufferSize);
3906 } else {
3907 memset(mSinkBuffer, 0, mSinkBufferSize);
3908 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003909 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003910 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3911 "anticipated start");
3912 }
3913 // TODO add standby time extension fct of effect tail
3914}
3915
3916// prepareTracks_l() must be called with ThreadBase::mLock held
3917AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3918 Vector< sp<Track> > *tracksToRemove)
3919{
3920
3921 mixer_state mixerStatus = MIXER_IDLE;
3922 // find out which tracks need to be processed
3923 size_t count = mActiveTracks.size();
3924 size_t mixedTracks = 0;
3925 size_t tracksWithEffect = 0;
3926 // counts only _active_ fast tracks
3927 size_t fastTracks = 0;
3928 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3929
3930 float masterVolume = mMasterVolume;
3931 bool masterMute = mMasterMute;
3932
3933 if (masterMute) {
3934 masterVolume = 0;
3935 }
3936 // Delegate master volume control to effect in output mix effect chain if needed
3937 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3938 if (chain != 0) {
3939 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3940 chain->setVolume_l(&v, &v);
3941 masterVolume = (float)((v + (1 << 23)) >> 24);
3942 chain.clear();
3943 }
3944
3945 // prepare a new state to push
3946 FastMixerStateQueue *sq = NULL;
3947 FastMixerState *state = NULL;
3948 bool didModify = false;
3949 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003950 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003951 sq = mFastMixer->sq();
3952 state = sq->begin();
3953 }
3954
Andy Hung69aed5f2014-02-25 17:24:40 -08003955 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003956 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003957
Eric Laurent81784c32012-11-19 14:55:58 -08003958 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003959 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003960
3961 // this const just means the local variable doesn't change
3962 Track* const track = t.get();
3963
3964 // process fast tracks
3965 if (track->isFastTrack()) {
3966
3967 // It's theoretically possible (though unlikely) for a fast track to be created
3968 // and then removed within the same normal mix cycle. This is not a problem, as
3969 // the track never becomes active so it's fast mixer slot is never touched.
3970 // The converse, of removing an (active) track and then creating a new track
3971 // at the identical fast mixer slot within the same normal mix cycle,
3972 // is impossible because the slot isn't marked available until the end of each cycle.
3973 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003974 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003975 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3976 FastTrack *fastTrack = &state->mFastTracks[j];
3977
3978 // Determine whether the track is currently in underrun condition,
3979 // and whether it had a recent underrun.
3980 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3981 FastTrackUnderruns underruns = ftDump->mUnderruns;
3982 uint32_t recentFull = (underruns.mBitFields.mFull -
3983 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3984 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3985 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3986 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3987 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3988 uint32_t recentUnderruns = recentPartial + recentEmpty;
3989 track->mObservedUnderruns = underruns;
3990 // don't count underruns that occur while stopping or pausing
3991 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003992 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3993 recentUnderruns > 0) {
3994 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3995 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003996 } else {
3997 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003998 }
3999
4000 // This is similar to the state machine for normal tracks,
4001 // with a few modifications for fast tracks.
4002 bool isActive = true;
4003 switch (track->mState) {
4004 case TrackBase::STOPPING_1:
4005 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004007 track->mState = TrackBase::STOPPING_2;
4008 }
4009 break;
4010 case TrackBase::PAUSING:
4011 // ramp down is not yet implemented
4012 track->setPaused();
4013 break;
4014 case TrackBase::RESUMING:
4015 // ramp up is not yet implemented
4016 track->mState = TrackBase::ACTIVE;
4017 break;
4018 case TrackBase::ACTIVE:
4019 if (recentFull > 0 || recentPartial > 0) {
4020 // track has provided at least some frames recently: reset retry count
4021 track->mRetryCount = kMaxTrackRetries;
4022 }
4023 if (recentUnderruns == 0) {
4024 // no recent underruns: stay active
4025 break;
4026 }
4027 // there has recently been an underrun of some kind
4028 if (track->sharedBuffer() == 0) {
4029 // were any of the recent underruns "empty" (no frames available)?
4030 if (recentEmpty == 0) {
4031 // no, then ignore the partial underruns as they are allowed indefinitely
4032 break;
4033 }
4034 // there has recently been an "empty" underrun: decrement the retry counter
4035 if (--(track->mRetryCount) > 0) {
4036 break;
4037 }
4038 // indicate to client process that the track was disabled because of underrun;
4039 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004040 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004041 // remove from active list, but state remains ACTIVE [confusing but true]
4042 isActive = false;
4043 break;
4044 }
4045 // fall through
4046 case TrackBase::STOPPING_2:
4047 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004048 case TrackBase::STOPPED:
4049 case TrackBase::FLUSHED: // flush() while active
4050 // Check for presentation complete if track is inactive
4051 // We have consumed all the buffers of this track.
4052 // This would be incomplete if we auto-paused on underrun
4053 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004054 uint32_t latency = 0;
4055 status_t result = mOutput->stream->getLatency(&latency);
4056 ALOGE_IF(result != OK,
4057 "Error when retrieving output stream latency: %d", result);
4058 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004059 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004060 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4061 // track stays in active list until presentation is complete
4062 break;
4063 }
4064 }
4065 if (track->isStopping_2()) {
4066 track->mState = TrackBase::STOPPED;
4067 }
4068 if (track->isStopped()) {
4069 // Can't reset directly, as fast mixer is still polling this track
4070 // track->reset();
4071 // So instead mark this track as needing to be reset after push with ack
4072 resetMask |= 1 << i;
4073 }
4074 isActive = false;
4075 break;
4076 case TrackBase::IDLE:
4077 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004078 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
4080
4081 if (isActive) {
4082 // was it previously inactive?
4083 if (!(state->mTrackMask & (1 << j))) {
4084 ExtendedAudioBufferProvider *eabp = track;
4085 VolumeProvider *vp = track;
4086 fastTrack->mBufferProvider = eabp;
4087 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004088 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004089 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004090 fastTrack->mGeneration++;
4091 state->mTrackMask |= 1 << j;
4092 didModify = true;
4093 // no acknowledgement required for newly active tracks
4094 }
4095 // cache the combined master volume and stream type volume for fast mixer; this
4096 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004097 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004098 ++fastTracks;
4099 } else {
4100 // was it previously active?
4101 if (state->mTrackMask & (1 << j)) {
4102 fastTrack->mBufferProvider = NULL;
4103 fastTrack->mGeneration++;
4104 state->mTrackMask &= ~(1 << j);
4105 didModify = true;
4106 // If any fast tracks were removed, we must wait for acknowledgement
4107 // because we're about to decrement the last sp<> on those tracks.
4108 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4109 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004110 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4111 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4112 j, track->mState, state->mTrackMask, recentUnderruns,
4113 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004114 }
4115 tracksToRemove->add(track);
4116 // Avoids a misleading display in dumpsys
4117 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4118 }
4119 continue;
4120 }
4121
4122 { // local variable scope to avoid goto warning
4123
4124 audio_track_cblk_t* cblk = track->cblk();
4125
4126 // The first time a track is added we wait
4127 // for all its buffers to be filled before processing it
4128 int name = track->name();
4129 // make sure that we have enough frames to mix one full buffer.
4130 // enforce this condition only once to enable draining the buffer in case the client
4131 // app does not call stop() and relies on underrun to stop:
4132 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4133 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004134 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004135 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004136 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004137
4138 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004139 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004140 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4141 // add frames already consumed but not yet released by the resampler
4142 // because mAudioTrackServerProxy->framesReady() will include these frames
4143 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4144
Eric Laurent81784c32012-11-19 14:55:58 -08004145 uint32_t minFrames = 1;
4146 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4147 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004148 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004149 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004150
4151 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004152 if (ATRACE_ENABLED()) {
4153 // I wish we had formatted trace names
4154 char traceName[16];
4155 strcpy(traceName, "nRdy");
4156 int name = track->name();
4157 if (AudioMixer::TRACK0 <= name &&
4158 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4159 name -= AudioMixer::TRACK0;
4160 traceName[4] = (name / 10) + '0';
4161 traceName[5] = (name % 10) + '0';
4162 } else {
4163 traceName[4] = '?';
4164 traceName[5] = '?';
4165 }
4166 traceName[6] = '\0';
4167 ATRACE_INT(traceName, framesReady);
4168 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004169 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004170 !track->isPaused() && !track->isTerminated())
4171 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004172 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004173
4174 mixedTracks++;
4175
Andy Hung69aed5f2014-02-25 17:24:40 -08004176 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4177 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004178 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004179 if (track->mainBuffer() != mSinkBuffer &&
4180 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004181 if (mEffectBufferEnabled) {
4182 mEffectBufferValid = true; // Later can set directly.
4183 }
Eric Laurent81784c32012-11-19 14:55:58 -08004184 chain = getEffectChain_l(track->sessionId());
4185 // Delegate volume control to effect in track effect chain if needed
4186 if (chain != 0) {
4187 tracksWithEffect++;
4188 } else {
4189 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4190 "session %d",
4191 name, track->sessionId());
4192 }
4193 }
4194
4195
4196 int param = AudioMixer::VOLUME;
4197 if (track->mFillingUpStatus == Track::FS_FILLED) {
4198 // no ramp for the first volume setting
4199 track->mFillingUpStatus = Track::FS_ACTIVE;
4200 if (track->mState == TrackBase::RESUMING) {
4201 track->mState = TrackBase::ACTIVE;
4202 param = AudioMixer::RAMP_VOLUME;
4203 }
4204 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004205 // FIXME should not make a decision based on mServer
4206 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207 // If the track is stopped before the first frame was mixed,
4208 // do not apply ramp
4209 param = AudioMixer::RAMP_VOLUME;
4210 }
4211
4212 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004213 uint32_t vl, vr; // in U8.24 integer format
4214 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004215 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004216 vl = vr = 0;
4217 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004218 if (track->isPausing()) {
4219 track->setPaused();
4220 }
4221 } else {
4222
4223 // read original volumes with volume control
4224 float typeVolume = mStreamTypes[track->streamType()].volume;
4225 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004226 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004227 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004228 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4229 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004230 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004231 if (vlf > GAIN_FLOAT_UNITY) {
4232 ALOGV("Track left volume out of range: %.3g", vlf);
4233 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004234 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004235 if (vrf > GAIN_FLOAT_UNITY) {
4236 ALOGV("Track right volume out of range: %.3g", vrf);
4237 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004238 }
4239 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004240 vlf *= v;
4241 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004242 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004243 // then derive vl and vr as U8.24 versions for the effect chain
4244 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4245 vl = (uint32_t) (scaleto8_24 * vlf);
4246 vr = (uint32_t) (scaleto8_24 * vrf);
4247 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004248 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004249 // send level comes from shared memory and so may be corrupt
4250 if (sendLevel > MAX_GAIN_INT) {
4251 ALOGV("Track send level out of range: %04X", sendLevel);
4252 sendLevel = MAX_GAIN_INT;
4253 }
Andy Hung6be49402014-05-30 10:42:03 -07004254 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4255 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004256 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004257
Eric Laurent81784c32012-11-19 14:55:58 -08004258 // Delegate volume control to effect in track effect chain if needed
4259 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4260 // Do not ramp volume if volume is controlled by effect
4261 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004262 // Update remaining floating point volume levels
4263 vlf = (float)vl / (1 << 24);
4264 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004265 track->mHasVolumeController = true;
4266 } else {
4267 // force no volume ramp when volume controller was just disabled or removed
4268 // from effect chain to avoid volume spike
4269 if (track->mHasVolumeController) {
4270 param = AudioMixer::VOLUME;
4271 }
4272 track->mHasVolumeController = false;
4273 }
4274
Eric Laurent81784c32012-11-19 14:55:58 -08004275 // XXX: these things DON'T need to be done each time
4276 mAudioMixer->setBufferProvider(name, track);
4277 mAudioMixer->enable(name);
4278
Andy Hung6be49402014-05-30 10:42:03 -07004279 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4280 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4281 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004282 mAudioMixer->setParameter(
4283 name,
4284 AudioMixer::TRACK,
4285 AudioMixer::FORMAT, (void *)track->format());
4286 mAudioMixer->setParameter(
4287 name,
4288 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004289 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004290 mAudioMixer->setParameter(
4291 name,
4292 AudioMixer::TRACK,
4293 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004294 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004295 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004296 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004297 if (reqSampleRate == 0) {
4298 reqSampleRate = mSampleRate;
4299 } else if (reqSampleRate > maxSampleRate) {
4300 reqSampleRate = maxSampleRate;
4301 }
Eric Laurent81784c32012-11-19 14:55:58 -08004302 mAudioMixer->setParameter(
4303 name,
4304 AudioMixer::RESAMPLE,
4305 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004306 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004307
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004308 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004309 mAudioMixer->setParameter(
4310 name,
4311 AudioMixer::TIMESTRETCH,
4312 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004313 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004314
Andy Hung69aed5f2014-02-25 17:24:40 -08004315 /*
4316 * Select the appropriate output buffer for the track.
4317 *
Andy Hung98ef9782014-03-04 14:46:50 -08004318 * Tracks with effects go into their own effects chain buffer
4319 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004320 *
4321 * Other tracks can use mMixerBuffer for higher precision
4322 * channel accumulation. If this buffer is enabled
4323 * (mMixerBufferEnabled true), then selected tracks will accumulate
4324 * into it.
4325 *
4326 */
4327 if (mMixerBufferEnabled
4328 && (track->mainBuffer() == mSinkBuffer
4329 || track->mainBuffer() == mMixerBuffer)) {
4330 mAudioMixer->setParameter(
4331 name,
4332 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004333 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004334 mAudioMixer->setParameter(
4335 name,
4336 AudioMixer::TRACK,
4337 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4338 // TODO: override track->mainBuffer()?
4339 mMixerBufferValid = true;
4340 } else {
4341 mAudioMixer->setParameter(
4342 name,
4343 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004344 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004345 mAudioMixer->setParameter(
4346 name,
4347 AudioMixer::TRACK,
4348 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4349 }
Eric Laurent81784c32012-11-19 14:55:58 -08004350 mAudioMixer->setParameter(
4351 name,
4352 AudioMixer::TRACK,
4353 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4354
4355 // reset retry count
4356 track->mRetryCount = kMaxTrackRetries;
4357
4358 // If one track is ready, set the mixer ready if:
4359 // - the mixer was not ready during previous round OR
4360 // - no other track is not ready
4361 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4362 mixerStatus != MIXER_TRACKS_ENABLED) {
4363 mixerStatus = MIXER_TRACKS_READY;
4364 }
4365 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004366 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004367 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4368 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004369 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004370 } else {
4371 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004372 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004373
Eric Laurent81784c32012-11-19 14:55:58 -08004374 // clear effect chain input buffer if an active track underruns to avoid sending
4375 // previous audio buffer again to effects
4376 chain = getEffectChain_l(track->sessionId());
4377 if (chain != 0) {
4378 chain->clearInputBuffer();
4379 }
4380
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004381 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004382 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4383 track->isStopped() || track->isPaused()) {
4384 // We have consumed all the buffers of this track.
4385 // Remove it from the list of active tracks.
4386 // TODO: use actual buffer filling status instead of latency when available from
4387 // audio HAL
4388 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004389 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004390 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4391 if (track->isStopped()) {
4392 track->reset();
4393 }
4394 tracksToRemove->add(track);
4395 }
4396 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004397 // No buffers for this track. Give it a few chances to
4398 // fill a buffer, then remove it from active list.
4399 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004400 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004401 tracksToRemove->add(track);
4402 // indicate to client process that the track was disabled because of underrun;
4403 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004404 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004405 // If one track is not ready, mark the mixer also not ready if:
4406 // - the mixer was ready during previous round OR
4407 // - no other track is ready
4408 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4409 mixerStatus != MIXER_TRACKS_READY) {
4410 mixerStatus = MIXER_TRACKS_ENABLED;
4411 }
4412 }
4413 mAudioMixer->disable(name);
4414 }
4415
4416 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004417
4418 }
4419
4420 // Push the new FastMixer state if necessary
4421 bool pauseAudioWatchdog = false;
4422 if (didModify) {
4423 state->mFastTracksGen++;
4424 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4425 if (kUseFastMixer == FastMixer_Dynamic &&
4426 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4427 state->mCommand = FastMixerState::COLD_IDLE;
4428 state->mColdFutexAddr = &mFastMixerFutex;
4429 state->mColdGen++;
4430 mFastMixerFutex = 0;
4431 if (kUseFastMixer == FastMixer_Dynamic) {
4432 mNormalSink = mOutputSink;
4433 }
4434 // If we go into cold idle, need to wait for acknowledgement
4435 // so that fast mixer stops doing I/O.
4436 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4437 pauseAudioWatchdog = true;
4438 }
Eric Laurent81784c32012-11-19 14:55:58 -08004439 }
4440 if (sq != NULL) {
4441 sq->end(didModify);
4442 sq->push(block);
4443 }
4444#ifdef AUDIO_WATCHDOG
4445 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4446 mAudioWatchdog->pause();
4447 }
4448#endif
4449
4450 // Now perform the deferred reset on fast tracks that have stopped
4451 while (resetMask != 0) {
4452 size_t i = __builtin_ctz(resetMask);
4453 ALOG_ASSERT(i < count);
4454 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004455 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004456 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4457 track->reset();
4458 }
4459
4460 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004461 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004462
Eric Laurent97d547d2014-09-02 14:45:53 -07004463 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4464 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004465 }
4466
4467 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004468 // as long as there are effects we should clear the effects buffer, to avoid
4469 // passing a non-clean buffer to the effect chain
4470 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004471 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004472 // sink or mix buffer must be cleared if all tracks are connected to an
4473 // effect chain as in this case the mixer will not write to the sink or mix buffer
4474 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4476 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004477 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004478 if (mMixerBufferValid) {
4479 memset(mMixerBuffer, 0, mMixerBufferSize);
4480 // TODO: In testing, mSinkBuffer below need not be cleared because
4481 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4482 // after mixing.
4483 //
4484 // To enforce this guarantee:
4485 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4486 // (mixedTracks == 0 && fastTracks > 0))
4487 // must imply MIXER_TRACKS_READY.
4488 // Later, we may clear buffers regardless, and skip much of this logic.
4489 }
Andy Hung98ef9782014-03-04 14:46:50 -08004490 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004491 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004492 }
4493
4494 // if any fast tracks, then status is ready
4495 mMixerStatusIgnoringFastTracks = mixerStatus;
4496 if (fastTracks > 0) {
4497 mixerStatus = MIXER_TRACKS_READY;
4498 }
4499 return mixerStatus;
4500}
4501
Eric Laurentad7dd962016-09-22 12:38:37 -07004502// trackCountForUid_l() must be called with ThreadBase::mLock held
4503uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4504{
4505 uint32_t trackCount = 0;
4506 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004507 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004508 trackCount++;
4509 }
4510 }
4511 return trackCount;
4512}
4513
Eric Laurent81784c32012-11-19 14:55:58 -08004514// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004515int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004516 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004517{
Eric Laurentad7dd962016-09-22 12:38:37 -07004518 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4519 return -1;
4520 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004521 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004522}
4523
4524// deleteTrackName_l() must be called with ThreadBase::mLock held
4525void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4526{
4527 ALOGV("remove track (%d) and delete from mixer", name);
4528 mAudioMixer->deleteTrackName(name);
4529}
4530
Eric Laurent10351942014-05-08 18:49:52 -07004531// checkForNewParameter_l() must be called with ThreadBase::mLock held
4532bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4533 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004534{
Eric Laurent81784c32012-11-19 14:55:58 -08004535 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004536 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004537
Eric Laurent10351942014-05-08 18:49:52 -07004538 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004539
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004540 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004541
Eric Laurent10351942014-05-08 18:49:52 -07004542 AudioParameter param = AudioParameter(keyValuePair);
4543 int value;
4544 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4545 reconfig = true;
4546 }
4547 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004548 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004549 status = BAD_VALUE;
4550 } else {
4551 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004552 reconfig = true;
4553 }
Eric Laurent10351942014-05-08 18:49:52 -07004554 }
4555 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004556 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004557 status = BAD_VALUE;
4558 } else {
4559 // no need to save value, since it's constant
4560 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004561 }
Eric Laurent10351942014-05-08 18:49:52 -07004562 }
4563 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4564 // do not accept frame count changes if tracks are open as the track buffer
4565 // size depends on frame count and correct behavior would not be guaranteed
4566 // if frame count is changed after track creation
4567 if (!mTracks.isEmpty()) {
4568 status = INVALID_OPERATION;
4569 } else {
4570 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004571 }
Eric Laurent10351942014-05-08 18:49:52 -07004572 }
4573 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004574#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004575 // when changing the audio output device, call addBatteryData to notify
4576 // the change
4577 if (mOutDevice != value) {
4578 uint32_t params = 0;
4579 // check whether speaker is on
4580 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4581 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004582 }
Eric Laurent10351942014-05-08 18:49:52 -07004583
4584 audio_devices_t deviceWithoutSpeaker
4585 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4586 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004587 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004588 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4589 }
4590
4591 if (params != 0) {
4592 addBatteryData(params);
4593 }
4594 }
Eric Laurent81784c32012-11-19 14:55:58 -08004595#endif
4596
Eric Laurent10351942014-05-08 18:49:52 -07004597 // forward device change to effects that have requested to be
4598 // aware of attached audio device.
4599 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004600 a2dpDeviceChanged =
4601 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004602 mOutDevice = value;
4603 for (size_t i = 0; i < mEffectChains.size(); i++) {
4604 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004605 }
4606 }
Eric Laurent10351942014-05-08 18:49:52 -07004607 }
Eric Laurent81784c32012-11-19 14:55:58 -08004608
Eric Laurent10351942014-05-08 18:49:52 -07004609 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004610 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004611 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004612 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004613 mStandby = true;
4614 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004615 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004616 }
Eric Laurent10351942014-05-08 18:49:52 -07004617 if (status == NO_ERROR && reconfig) {
4618 readOutputParameters_l();
4619 delete mAudioMixer;
4620 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4621 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004622 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004623 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004624 if (name < 0) {
4625 break;
4626 }
4627 mTracks[i]->mName = name;
4628 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004629 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004630 }
Eric Laurent81784c32012-11-19 14:55:58 -08004631 }
4632
Eric Laurent42537be2016-01-08 17:16:42 -08004633 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004634}
4635
4636
4637void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4638{
Eric Laurent81784c32012-11-19 14:55:58 -08004639 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004640 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004641 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004642 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004643
4644 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004645 // while we are dumping it. It may be inconsistent, but it won't mutate!
4646 // This is a large object so we place it on the heap.
4647 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4648 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4649 copy->dump(fd);
4650 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004651
4652#ifdef STATE_QUEUE_DUMP
4653 // Similar for state queue
4654 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4655 observerCopy.dump(fd);
4656 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4657 mutatorCopy.dump(fd);
4658#endif
4659
Glenn Kasten46909e72013-02-26 09:20:22 -08004660#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004661 // Write the tee output to a .wav file
4662 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004663#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004664
4665#ifdef AUDIO_WATCHDOG
4666 if (mAudioWatchdog != 0) {
4667 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4668 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4669 wdCopy.dump(fd);
4670 }
4671#endif
4672}
4673
4674uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4675{
4676 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4677}
4678
4679uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4680{
4681 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4682}
4683
4684void AudioFlinger::MixerThread::cacheParameters_l()
4685{
4686 PlaybackThread::cacheParameters_l();
4687
4688 // FIXME: Relaxed timing because of a certain device that can't meet latency
4689 // Should be reduced to 2x after the vendor fixes the driver issue
4690 // increase threshold again due to low power audio mode. The way this warning
4691 // threshold is calculated and its usefulness should be reconsidered anyway.
4692 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4693}
4694
4695// ----------------------------------------------------------------------------
4696
4697AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004698 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4699 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004700 // mLeftVolFloat, mRightVolFloat
4701{
4702}
4703
Eric Laurentbfb1b832013-01-07 09:53:42 -08004704AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4705 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004706 ThreadBase::type_t type, bool systemReady)
4707 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004708 // mLeftVolFloat, mRightVolFloat
4709{
4710}
4711
Eric Laurent81784c32012-11-19 14:55:58 -08004712AudioFlinger::DirectOutputThread::~DirectOutputThread()
4713{
4714}
4715
Eric Laurent5850c4c2016-11-10 13:04:31 -08004716void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004717{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718 float left, right;
4719
4720 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4721 left = right = 0;
4722 } else {
4723 float typeVolume = mStreamTypes[track->streamType()].volume;
4724 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004725 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004726 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4727 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4728 if (left > GAIN_FLOAT_UNITY) {
4729 left = GAIN_FLOAT_UNITY;
4730 }
4731 left *= v;
4732 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4733 if (right > GAIN_FLOAT_UNITY) {
4734 right = GAIN_FLOAT_UNITY;
4735 }
4736 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004737 }
4738
4739 if (lastTrack) {
4740 if (left != mLeftVolFloat || right != mRightVolFloat) {
4741 mLeftVolFloat = left;
4742 mRightVolFloat = right;
4743
4744 // Convert volumes from float to 8.24
4745 uint32_t vl = (uint32_t)(left * (1 << 24));
4746 uint32_t vr = (uint32_t)(right * (1 << 24));
4747
4748 // Delegate volume control to effect in track effect chain if needed
4749 // only one effect chain can be present on DirectOutputThread, so if
4750 // there is one, the track is connected to it
4751 if (!mEffectChains.isEmpty()) {
4752 mEffectChains[0]->setVolume_l(&vl, &vr);
4753 left = (float)vl / (1 << 24);
4754 right = (float)vr / (1 << 24);
4755 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004756 status_t result = mOutput->stream->setVolume(left, right);
4757 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004758 }
4759 }
4760}
4761
Phil Burk43b4dcc2015-06-09 16:53:44 -07004762void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4763{
4764 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004765 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004766
Eric Laurent0f0631e2015-07-06 18:01:25 -07004767 if (previousTrack != 0 && latestTrack != 0) {
4768 if (mType == DIRECT) {
4769 if (previousTrack.get() != latestTrack.get()) {
4770 mFlushPending = true;
4771 }
4772 } else /* mType == OFFLOAD */ {
4773 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4774 mFlushPending = true;
4775 }
4776 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004777 }
4778 PlaybackThread::onAddNewTrack_l();
4779}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004780
Eric Laurent81784c32012-11-19 14:55:58 -08004781AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4782 Vector< sp<Track> > *tracksToRemove
4783)
4784{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004785 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004786 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004787 bool doHwPause = false;
4788 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004789
4790 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004791 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004792 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004793 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004794 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004795 continue;
4796 }
4797
Eric Laurent5850c4c2016-11-10 13:04:31 -08004798 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004799#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004800 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004801#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004802 // Only consider last track started for volume and mixer state control.
4803 // In theory an older track could underrun and restart after the new one starts
4804 // but as we only care about the transition phase between two tracks on a
4805 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004806 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004807 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004808
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004809 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004810 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004811 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004812 doHwPause = true;
4813 mHwPaused = true;
4814 }
4815 tracksToRemove->add(track);
4816 } else if (track->isFlushPending()) {
4817 track->flushAck();
4818 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004819 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004820 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004821 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004822 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004823 if (last) {
4824 mLeftVolFloat = mRightVolFloat = -1.0;
4825 if (mHwPaused) {
4826 doHwResume = true;
4827 mHwPaused = false;
4828 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004829 }
4830 }
4831
Eric Laurent81784c32012-11-19 14:55:58 -08004832 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004833 // for all its buffers to be filled before processing it.
4834 // Allow draining the buffer in case the client
4835 // app does not call stop() and relies on underrun to stop:
4836 // hence the test on (track->mRetryCount > 1).
4837 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004838 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004839 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004840 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004841 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004842 minFrames = mNormalFrameCount;
4843 } else {
4844 minFrames = 1;
4845 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004846
Eric Laurentab5cdba2014-06-09 17:22:27 -07004847 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4848 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004849 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004850 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004851
4852 if (track->mFillingUpStatus == Track::FS_FILLED) {
4853 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004854 if (last) {
4855 // make sure processVolume_l() will apply new volume even if 0
4856 mLeftVolFloat = mRightVolFloat = -1.0;
4857 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004858 if (!mHwSupportsPause) {
4859 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004860 }
4861 }
4862
4863 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004864 processVolume_l(track, last);
4865 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004866 sp<Track> previousTrack = mPreviousTrack.promote();
4867 if (previousTrack != 0) {
4868 if (track != previousTrack.get()) {
4869 // Flush any data still being written from last track
4870 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004871 // Invalidate previous track to force a seek when resuming.
4872 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004873 }
4874 }
4875 mPreviousTrack = track;
4876
Eric Laurentd595b7c2013-04-03 17:27:56 -07004877 // reset retry count
4878 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004879 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004880 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004881 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004882 doHwResume = true;
4883 mHwPaused = false;
4884 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004885 }
Eric Laurent81784c32012-11-19 14:55:58 -08004886 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004887 // clear effect chain input buffer if the last active track started underruns
4888 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004889 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004890 mEffectChains[0]->clearInputBuffer();
4891 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004892 if (track->isStopping_1()) {
4893 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004894 if (last && mHwPaused) {
4895 doHwResume = true;
4896 mHwPaused = false;
4897 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004898 }
4899 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4900 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004901 // We have consumed all the buffers of this track.
4902 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004903 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004904 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004905 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4906 } else {
4907 audioHALFrames = 0;
4908 }
4909
Andy Hung818e7a32016-02-16 18:08:07 -08004910 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004911 if (mStandby || !last ||
4912 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004913 if (track->isStopping_2()) {
4914 track->mState = TrackBase::STOPPED;
4915 }
Eric Laurent81784c32012-11-19 14:55:58 -08004916 if (track->isStopped()) {
4917 track->reset();
4918 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004919 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004920 }
4921 } else {
4922 // No buffers for this track. Give it a few chances to
4923 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004924 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004925 if (--(track->mRetryCount) <= 0) {
4926 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004927 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004928 // indicate to client process that the track was disabled because of underrun;
4929 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004930 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004932 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4933 "minFrames = %u, mFormat = %#x",
4934 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004935 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004936 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004937 doHwPause = true;
4938 mHwPaused = true;
4939 }
Eric Laurent81784c32012-11-19 14:55:58 -08004940 }
4941 }
4942 }
4943 }
4944
Eric Laurentd1f69b02014-12-15 14:33:13 -08004945 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004946 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004947 for (size_t i = 0; i < mTracks.size(); i++) {
4948 if (mTracks[i]->isFlushPending()) {
4949 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004950 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004951 }
4952 }
4953 }
4954
4955 // make sure the pause/flush/resume sequence is executed in the right order.
4956 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4957 // before flush and then resume HW. This can happen in case of pause/flush/resume
4958 // if resume is received before pause is executed.
4959 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004960 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004961 status_t result = mOutput->stream->pause();
4962 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004963 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004964 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004965 flushHw_l();
4966 }
4967 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004968 status_t result = mOutput->stream->resume();
4969 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004970 }
Eric Laurent81784c32012-11-19 14:55:58 -08004971 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004972 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004973
4974 return mixerStatus;
4975}
4976
4977void AudioFlinger::DirectOutputThread::threadLoop_mix()
4978{
Eric Laurent81784c32012-11-19 14:55:58 -08004979 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004980 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004981 // output audio to hardware
4982 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004983 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004984 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004985 status_t status = mActiveTrack->getNextBuffer(&buffer);
4986 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004987 // no need to pad with 0 for compressed audio
4988 if (audio_has_proportional_frames(mFormat)) {
4989 memset(curBuf, 0, frameCount * mFrameSize);
4990 }
Eric Laurent81784c32012-11-19 14:55:58 -08004991 break;
4992 }
4993 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4994 frameCount -= buffer.frameCount;
4995 curBuf += buffer.frameCount * mFrameSize;
4996 mActiveTrack->releaseBuffer(&buffer);
4997 }
Andy Hung2098f272014-02-27 14:00:06 -08004998 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004999 mSleepTimeUs = 0;
5000 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005001 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005002}
5003
5004void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5005{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005006 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005007 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005008 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005009 return;
5010 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005011 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005012 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005013 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005014 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005015 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005016 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005017 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005018 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005019 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005020 }
5021}
5022
Eric Laurentd1f69b02014-12-15 14:33:13 -08005023void AudioFlinger::DirectOutputThread::threadLoop_exit()
5024{
5025 {
5026 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005027 for (size_t i = 0; i < mTracks.size(); i++) {
5028 if (mTracks[i]->isFlushPending()) {
5029 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005030 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005031 }
5032 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005033 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005034 flushHw_l();
5035 }
5036 }
5037 PlaybackThread::threadLoop_exit();
5038}
5039
5040// must be called with thread mutex locked
5041bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5042{
5043 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005044 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005045
vivek mehta9cd7ad12016-03-17 00:18:29 -07005046 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5047 return !mStandby;
5048 }
5049
Eric Laurentd1f69b02014-12-15 14:33:13 -08005050 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5051 // after a timeout and we will enter standby then.
5052 if (mTracks.size() > 0) {
5053 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005054 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5055 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005056 }
5057
Eric Laurent5cff4032015-05-26 13:49:58 -07005058 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059}
5060
Eric Laurent81784c32012-11-19 14:55:58 -08005061// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005062int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005063 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005064{
Eric Laurentad7dd962016-09-22 12:38:37 -07005065 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5066 return -1;
5067 }
Eric Laurent81784c32012-11-19 14:55:58 -08005068 return 0;
5069}
5070
5071// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005072void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005073{
5074}
5075
Eric Laurent10351942014-05-08 18:49:52 -07005076// checkForNewParameter_l() must be called with ThreadBase::mLock held
5077bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5078 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005079{
5080 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005081 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005082
Eric Laurent10351942014-05-08 18:49:52 -07005083 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005084
Eric Laurent10351942014-05-08 18:49:52 -07005085 AudioParameter param = AudioParameter(keyValuePair);
5086 int value;
5087 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5088 // forward device change to effects that have requested to be
5089 // aware of attached audio device.
5090 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005091 a2dpDeviceChanged =
5092 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005093 mOutDevice = value;
5094 for (size_t i = 0; i < mEffectChains.size(); i++) {
5095 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005096 }
5097 }
Eric Laurent81784c32012-11-19 14:55:58 -08005098 }
Eric Laurent10351942014-05-08 18:49:52 -07005099 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5100 // do not accept frame count changes if tracks are open as the track buffer
5101 // size depends on frame count and correct behavior would not be garantied
5102 // if frame count is changed after track creation
5103 if (!mTracks.isEmpty()) {
5104 status = INVALID_OPERATION;
5105 } else {
5106 reconfig = true;
5107 }
5108 }
5109 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005110 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005111 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005112 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005113 mStandby = true;
5114 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005115 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005116 }
5117 if (status == NO_ERROR && reconfig) {
5118 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005119 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005120 }
5121 }
5122
Eric Laurent42537be2016-01-08 17:16:42 -08005123 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005124}
5125
5126uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5127{
5128 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005129 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005130 time = PlaybackThread::activeSleepTimeUs();
5131 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005132 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
5134 return time;
5135}
5136
5137uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5138{
5139 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005140 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005141 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5142 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005143 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005144 }
5145 return time;
5146}
5147
5148uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5149{
5150 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005151 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005152 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5153 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005154 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005155 }
5156 return time;
5157}
5158
5159void AudioFlinger::DirectOutputThread::cacheParameters_l()
5160{
5161 PlaybackThread::cacheParameters_l();
5162
5163 // use shorter standby delay as on normal output to release
5164 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005165 // no delay on outputs with HW A/V sync
5166 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005167 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005168 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005169 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005170 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005171 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005172 }
Eric Laurent81784c32012-11-19 14:55:58 -08005173}
5174
Eric Laurente659ef42014-09-29 13:06:46 -07005175void AudioFlinger::DirectOutputThread::flushHw_l()
5176{
Phil Burk062e67a2015-02-11 13:40:50 -08005177 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005178 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005179 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005180}
5181
Eric Laurent81784c32012-11-19 14:55:58 -08005182// ----------------------------------------------------------------------------
5183
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005185 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005186 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005187 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005188 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005189 mDrainSequence(0),
5190 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005191{
5192}
5193
5194AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5195{
5196}
5197
5198void AudioFlinger::AsyncCallbackThread::onFirstRef()
5199{
5200 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5201}
5202
5203bool AudioFlinger::AsyncCallbackThread::threadLoop()
5204{
5205 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005206 uint32_t writeAckSequence;
5207 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005208 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005209
5210 {
5211 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005212 while (!((mWriteAckSequence & 1) ||
5213 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005214 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005215 exitPending())) {
5216 mWaitWorkCV.wait(mLock);
5217 }
5218
Eric Laurentbfb1b832013-01-07 09:53:42 -08005219 if (exitPending()) {
5220 break;
5221 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005222 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5223 mWriteAckSequence, mDrainSequence);
5224 writeAckSequence = mWriteAckSequence;
5225 mWriteAckSequence &= ~1;
5226 drainSequence = mDrainSequence;
5227 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005228 asyncError = mAsyncError;
5229 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230 }
5231 {
Eric Laurent4de95592013-09-26 15:28:21 -07005232 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5233 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005234 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005235 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005236 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005237 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005238 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005239 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005240 if (asyncError) {
5241 playbackThread->onAsyncError();
5242 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005243 }
5244 }
5245 }
5246 return false;
5247}
5248
5249void AudioFlinger::AsyncCallbackThread::exit()
5250{
5251 ALOGV("AsyncCallbackThread::exit");
5252 Mutex::Autolock _l(mLock);
5253 requestExit();
5254 mWaitWorkCV.broadcast();
5255}
5256
Eric Laurent3b4529e2013-09-05 18:09:19 -07005257void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005258{
5259 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005260 // bit 0 is cleared
5261 mWriteAckSequence = sequence << 1;
5262}
5263
5264void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5265{
5266 Mutex::Autolock _l(mLock);
5267 // ignore unexpected callbacks
5268 if (mWriteAckSequence & 2) {
5269 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270 mWaitWorkCV.signal();
5271 }
5272}
5273
Eric Laurent3b4529e2013-09-05 18:09:19 -07005274void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005275{
5276 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005277 // bit 0 is cleared
5278 mDrainSequence = sequence << 1;
5279}
5280
5281void AudioFlinger::AsyncCallbackThread::resetDraining()
5282{
5283 Mutex::Autolock _l(mLock);
5284 // ignore unexpected callbacks
5285 if (mDrainSequence & 2) {
5286 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287 mWaitWorkCV.signal();
5288 }
5289}
5290
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005291void AudioFlinger::AsyncCallbackThread::setAsyncError()
5292{
5293 Mutex::Autolock _l(mLock);
5294 mAsyncError = true;
5295 mWaitWorkCV.signal();
5296}
5297
Eric Laurentbfb1b832013-01-07 09:53:42 -08005298
5299// ----------------------------------------------------------------------------
5300AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005301 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5302 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005303 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5304 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305{
Eric Laurentfd477972013-10-25 18:10:40 -07005306 //FIXME: mStandby should be set to true by ThreadBase constructor
5307 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005308 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309}
5310
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311void AudioFlinger::OffloadThread::threadLoop_exit()
5312{
5313 if (mFlushPending || mHwPaused) {
5314 // If a flush is pending or track was paused, just discard buffered data
5315 flushHw_l();
5316 } else {
5317 mMixerStatus = MIXER_DRAIN_ALL;
5318 threadLoop_drain();
5319 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005320 if (mUseAsyncWrite) {
5321 ALOG_ASSERT(mCallbackThread != 0);
5322 mCallbackThread->exit();
5323 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005324 PlaybackThread::threadLoop_exit();
5325}
5326
5327AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5328 Vector< sp<Track> > *tracksToRemove
5329)
5330{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331 size_t count = mActiveTracks.size();
5332
5333 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005334 bool doHwPause = false;
5335 bool doHwResume = false;
5336
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005337 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005338
Eric Laurentbfb1b832013-01-07 09:53:42 -08005339 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005340 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005341 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005342#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005344#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005345 // Only consider last track started for volume and mixer state control.
5346 // In theory an older track could underrun and restart after the new one starts
5347 // but as we only care about the transition phase between two tracks on a
5348 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005349 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005350 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005351
Haynes Mathew George7844f672014-01-15 12:32:55 -08005352 if (track->isInvalid()) {
5353 ALOGW("An invalidated track shouldn't be in active list");
5354 tracksToRemove->add(track);
5355 continue;
5356 }
5357
5358 if (track->mState == TrackBase::IDLE) {
5359 ALOGW("An idle track shouldn't be in active list");
5360 continue;
5361 }
5362
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 if (track->isPausing()) {
5364 track->setPaused();
5365 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005366 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005367 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005368 mHwPaused = true;
5369 }
5370 // If we were part way through writing the mixbuffer to
5371 // the HAL we must save this until we resume
5372 // BUG - this will be wrong if a different track is made active,
5373 // in that case we want to discard the pending data in the
5374 // mixbuffer and tell the client to present it again when the
5375 // track is resumed
5376 mPausedWriteLength = mCurrentWriteLength;
5377 mPausedBytesRemaining = mBytesRemaining;
5378 mBytesRemaining = 0; // stop writing
5379 }
5380 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005381 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005382 if (track->isStopping_1()) {
5383 track->mRetryCount = kMaxTrackStopRetriesOffload;
5384 } else {
5385 track->mRetryCount = kMaxTrackRetriesOffload;
5386 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005387 track->flushAck();
5388 if (last) {
5389 mFlushPending = true;
5390 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005391 } else if (track->isResumePending()){
5392 track->resumeAck();
5393 if (last) {
5394 if (mPausedBytesRemaining) {
5395 // Need to continue write that was interrupted
5396 mCurrentWriteLength = mPausedWriteLength;
5397 mBytesRemaining = mPausedBytesRemaining;
5398 mPausedBytesRemaining = 0;
5399 }
5400 if (mHwPaused) {
5401 doHwResume = true;
5402 mHwPaused = false;
5403 // threadLoop_mix() will handle the case that we need to
5404 // resume an interrupted write
5405 }
5406 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005407 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005408
Eric Laurent3df841a2016-07-15 15:15:40 -07005409 mLeftVolFloat = mRightVolFloat = -1.0;
5410
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005411 // Do not handle new data in this iteration even if track->framesReady()
5412 mixerStatus = MIXER_TRACKS_ENABLED;
5413 }
5414 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005415 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005416 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005417 if (track->mFillingUpStatus == Track::FS_FILLED) {
5418 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005419 if (last) {
5420 // make sure processVolume_l() will apply new volume even if 0
5421 mLeftVolFloat = mRightVolFloat = -1.0;
5422 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005423 }
5424
5425 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005426 sp<Track> previousTrack = mPreviousTrack.promote();
5427 if (previousTrack != 0) {
5428 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005429 // Flush any data still being written from last track
5430 mBytesRemaining = 0;
5431 if (mPausedBytesRemaining) {
5432 // Last track was paused so we also need to flush saved
5433 // mixbuffer state and invalidate track so that it will
5434 // re-submit that unwritten data when it is next resumed
5435 mPausedBytesRemaining = 0;
5436 // Invalidate is a bit drastic - would be more efficient
5437 // to have a flag to tell client that some of the
5438 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005439 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005440 }
5441 // flush data already sent to the DSP if changing audio session as audio
5442 // comes from a different source. Also invalidate previous track to force a
5443 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005444 if (previousTrack->sessionId() != track->sessionId()) {
5445 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005446 }
5447 }
5448 }
5449 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005450 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005451 if (track->isStopping_1()) {
5452 track->mRetryCount = kMaxTrackStopRetriesOffload;
5453 } else {
5454 track->mRetryCount = kMaxTrackRetriesOffload;
5455 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005456 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005457 mixerStatus = MIXER_TRACKS_READY;
5458 }
5459 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005460 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005461 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005462 if (--(track->mRetryCount) <= 0) {
5463 // Hardware buffer can hold a large amount of audio so we must
5464 // wait for all current track's data to drain before we say
5465 // that the track is stopped.
5466 if (mBytesRemaining == 0) {
5467 // Only start draining when all data in mixbuffer
5468 // has been written
5469 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5470 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5471 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5472 if (last && !mStandby) {
5473 // do not modify drain sequence if we are already draining. This happens
5474 // when resuming from pause after drain.
5475 if ((mDrainSequence & 1) == 0) {
5476 mSleepTimeUs = 0;
5477 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5478 mixerStatus = MIXER_DRAIN_TRACK;
5479 mDrainSequence += 2;
5480 }
5481 if (mHwPaused) {
5482 // It is possible to move from PAUSED to STOPPING_1 without
5483 // a resume so we must ensure hardware is running
5484 doHwResume = true;
5485 mHwPaused = false;
5486 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 }
5488 }
Eric Laurente93cc032016-05-05 10:15:10 -07005489 } else if (last) {
5490 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5491 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 }
5493 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005494 // Drain has completed or we are in standby, signal presentation complete
5495 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005497 uint32_t latency = 0;
5498 status_t result = mOutput->stream->getLatency(&latency);
5499 ALOGE_IF(result != OK,
5500 "Error when retrieving output stream latency: %d", result);
5501 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005502 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005503 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005504 track->presentationComplete(framesWritten, audioHALFrames);
5505 track->reset();
5506 tracksToRemove->add(track);
5507 }
5508 } else {
5509 // No buffers for this track. Give it a few chances to
5510 // fill a buffer, then remove it from active list.
5511 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005512 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005513 uint64_t position = 0;
5514 struct timespec unused;
5515 // The running check restarts the retry counter at least once.
5516 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5517 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5518 running = true;
5519 mOffloadUnderrunPosition = position;
5520 }
5521 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005522 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5523 (long long)position, (long long)mOffloadUnderrunPosition);
5524 }
5525 if (running) { // still running, give us more time.
5526 track->mRetryCount = kMaxTrackRetriesOffload;
5527 } else {
5528 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5529 track->name());
5530 tracksToRemove->add(track);
5531 // indicate to client process that the track was disabled because of underrun;
5532 // it will then automatically call start() when data is available
5533 track->disable();
5534 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 } else if (last){
5536 mixerStatus = MIXER_TRACKS_ENABLED;
5537 }
5538 }
5539 }
5540 // compute volume for this track
5541 processVolume_l(track, last);
5542 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005543
Eric Laurentea0fade2013-10-04 16:23:48 -07005544 // make sure the pause/flush/resume sequence is executed in the right order.
5545 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5546 // before flush and then resume HW. This can happen in case of pause/flush/resume
5547 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005548 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005549 status_t result = mOutput->stream->pause();
5550 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005551 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005552 if (mFlushPending) {
5553 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005554 }
Eric Laurentfd477972013-10-25 18:10:40 -07005555 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005556 status_t result = mOutput->stream->resume();
5557 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005558 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005559
Eric Laurentbfb1b832013-01-07 09:53:42 -08005560 // remove all the tracks that need to be...
5561 removeTracks_l(*tracksToRemove);
5562
5563 return mixerStatus;
5564}
5565
Eric Laurentbfb1b832013-01-07 09:53:42 -08005566// must be called with thread mutex locked
5567bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5568{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005569 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5570 mWriteAckSequence, mDrainSequence);
5571 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005572 return true;
5573 }
5574 return false;
5575}
5576
Eric Laurentbfb1b832013-01-07 09:53:42 -08005577bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5578{
5579 Mutex::Autolock _l(mLock);
5580 return waitingAsyncCallback_l();
5581}
5582
5583void AudioFlinger::OffloadThread::flushHw_l()
5584{
Eric Laurente659ef42014-09-29 13:06:46 -07005585 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005586 // Flush anything still waiting in the mixbuffer
5587 mCurrentWriteLength = 0;
5588 mBytesRemaining = 0;
5589 mPausedWriteLength = 0;
5590 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005591 // reset bytes written count to reflect that DSP buffers are empty after flush.
5592 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005593 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005594
Eric Laurentbfb1b832013-01-07 09:53:42 -08005595 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005596 // discard any pending drain or write ack by incrementing sequence
5597 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5598 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005599 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005600 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5601 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005602 }
5603}
5604
Haynes Mathew George05317d22016-05-03 16:34:26 -07005605void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5606{
5607 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005608 if (PlaybackThread::invalidateTracks_l(streamType)) {
5609 mFlushPending = true;
5610 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005611}
5612
Eric Laurentbfb1b832013-01-07 09:53:42 -08005613// ----------------------------------------------------------------------------
5614
Eric Laurent81784c32012-11-19 14:55:58 -08005615AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005616 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005617 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005618 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005619 mWaitTimeMs(UINT_MAX)
5620{
5621 addOutputTrack(mainThread);
5622}
5623
5624AudioFlinger::DuplicatingThread::~DuplicatingThread()
5625{
5626 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5627 mOutputTracks[i]->destroy();
5628 }
5629}
5630
5631void AudioFlinger::DuplicatingThread::threadLoop_mix()
5632{
5633 // mix buffers...
5634 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005635 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005636 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005637 if (mMixerBufferValid) {
5638 memset(mMixerBuffer, 0, mMixerBufferSize);
5639 } else {
5640 memset(mSinkBuffer, 0, mSinkBufferSize);
5641 }
Eric Laurent81784c32012-11-19 14:55:58 -08005642 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005643 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005644 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005645 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005646 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005647}
5648
5649void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5650{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005651 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005652 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005653 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005654 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005655 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005656 }
5657 } else if (mBytesWritten != 0) {
5658 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5659 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005660 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005661 } else {
5662 // flush remaining overflow buffers in output tracks
5663 writeFrames = 0;
5664 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005665 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005666 }
5667}
5668
Eric Laurentbfb1b832013-01-07 09:53:42 -08005669ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005670{
5671 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005672 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005673 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005674 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005675 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005676}
5677
5678void AudioFlinger::DuplicatingThread::threadLoop_standby()
5679{
5680 // DuplicatingThread implements standby by stopping all tracks
5681 for (size_t i = 0; i < outputTracks.size(); i++) {
5682 outputTracks[i]->stop();
5683 }
5684}
5685
5686void AudioFlinger::DuplicatingThread::saveOutputTracks()
5687{
5688 outputTracks = mOutputTracks;
5689}
5690
5691void AudioFlinger::DuplicatingThread::clearOutputTracks()
5692{
5693 outputTracks.clear();
5694}
5695
5696void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5697{
5698 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005699 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5700 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5701 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5702 const size_t frameCount =
5703 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5704 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5705 // from different OutputTracks and their associated MixerThreads (e.g. one may
5706 // nearly empty and the other may be dropping data).
5707
5708 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005709 this,
5710 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005711 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005712 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005713 frameCount,
5714 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005715 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5716 if (status != NO_ERROR) {
5717 ALOGE("addOutputTrack() initCheck failed %d", status);
5718 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005719 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005720 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5721 mOutputTracks.add(outputTrack);
5722 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5723 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005724}
5725
5726void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5727{
5728 Mutex::Autolock _l(mLock);
5729 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5730 if (mOutputTracks[i]->thread() == thread) {
5731 mOutputTracks[i]->destroy();
5732 mOutputTracks.removeAt(i);
5733 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005734 if (thread->getOutput() == mOutput) {
5735 mOutput = NULL;
5736 }
Eric Laurent81784c32012-11-19 14:55:58 -08005737 return;
5738 }
5739 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005740 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005741}
5742
5743// caller must hold mLock
5744void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5745{
5746 mWaitTimeMs = UINT_MAX;
5747 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5748 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5749 if (strong != 0) {
5750 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5751 if (waitTimeMs < mWaitTimeMs) {
5752 mWaitTimeMs = waitTimeMs;
5753 }
5754 }
5755 }
5756}
5757
5758
5759bool AudioFlinger::DuplicatingThread::outputsReady(
5760 const SortedVector< sp<OutputTrack> > &outputTracks)
5761{
5762 for (size_t i = 0; i < outputTracks.size(); i++) {
5763 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5764 if (thread == 0) {
5765 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5766 outputTracks[i].get());
5767 return false;
5768 }
5769 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5770 // see note at standby() declaration
5771 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5772 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5773 thread.get());
5774 return false;
5775 }
5776 }
5777 return true;
5778}
5779
5780uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5781{
5782 return (mWaitTimeMs * 1000) / 2;
5783}
5784
5785void AudioFlinger::DuplicatingThread::cacheParameters_l()
5786{
5787 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5788 updateWaitTime_l();
5789
5790 MixerThread::cacheParameters_l();
5791}
5792
5793// ----------------------------------------------------------------------------
5794// Record
5795// ----------------------------------------------------------------------------
5796
5797AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5798 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005799 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005800 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005801 audio_devices_t inDevice,
5802 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005803#ifdef TEE_SINK
5804 , const sp<NBAIO_Sink>& teeSink
5805#endif
5806 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005807 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005808 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005809 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005810 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005811#ifdef TEE_SINK
5812 , mTeeSink(teeSink)
5813#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005814 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5815 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005816 // mFastCapture below
5817 , mFastCaptureFutex(0)
5818 // mInputSource
5819 // mPipeSink
5820 // mPipeSource
5821 , mPipeFramesP2(0)
5822 // mPipeMemory
5823 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005824 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005825{
Glenn Kastend7dca052015-03-05 16:05:54 -08005826 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5827 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005828
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005829 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005830
5831 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005832 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833 size_t numCounterOffers = 0;
5834 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005835#if !LOG_NDEBUG
5836 ssize_t index =
5837#else
5838 (void)
5839#endif
5840 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005841 ALOG_ASSERT(index == 0);
5842
5843 // initialize fast capture depending on configuration
5844 bool initFastCapture;
5845 switch (kUseFastCapture) {
5846 case FastCapture_Never:
5847 initFastCapture = false;
5848 break;
5849 case FastCapture_Always:
5850 initFastCapture = true;
5851 break;
5852 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005853 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005854 break;
5855 // case FastCapture_Dynamic:
5856 }
5857
5858 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005859 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005860 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005861 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5862 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005863 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5864 void *pipeBuffer;
5865 const sp<MemoryDealer> roHeap(readOnlyHeap());
5866 sp<IMemory> pipeMemory;
5867 if ((roHeap == 0) ||
5868 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5869 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5870 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5871 goto failed;
5872 }
5873 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5874 memset(pipeBuffer, 0, pipeSize);
5875 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5876 const NBAIO_Format offers[1] = {format};
5877 size_t numCounterOffers = 0;
5878 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5879 ALOG_ASSERT(index == 0);
5880 mPipeSink = pipe;
5881 PipeReader *pipeReader = new PipeReader(*pipe);
5882 numCounterOffers = 0;
5883 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5884 ALOG_ASSERT(index == 0);
5885 mPipeSource = pipeReader;
5886 mPipeFramesP2 = pipeFramesP2;
5887 mPipeMemory = pipeMemory;
5888
5889 // create fast capture
5890 mFastCapture = new FastCapture();
5891 FastCaptureStateQueue *sq = mFastCapture->sq();
5892#ifdef STATE_QUEUE_DUMP
5893 // FIXME
5894#endif
5895 FastCaptureState *state = sq->begin();
5896 state->mCblk = NULL;
5897 state->mInputSource = mInputSource.get();
5898 state->mInputSourceGen++;
5899 state->mPipeSink = pipe;
5900 state->mPipeSinkGen++;
5901 state->mFrameCount = mFrameCount;
5902 state->mCommand = FastCaptureState::COLD_IDLE;
5903 // already done in constructor initialization list
5904 //mFastCaptureFutex = 0;
5905 state->mColdFutexAddr = &mFastCaptureFutex;
5906 state->mColdGen++;
5907 state->mDumpState = &mFastCaptureDumpState;
5908#ifdef TEE_SINK
5909 // FIXME
5910#endif
5911 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5912 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5913 sq->end();
5914 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5915
5916 // start the fast capture
5917 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5918 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005919 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005920 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005921#ifdef AUDIO_WATCHDOG
5922 // FIXME
5923#endif
5924
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005925 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005926 }
5927failed: ;
5928
5929 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005930}
5931
Eric Laurent81784c32012-11-19 14:55:58 -08005932AudioFlinger::RecordThread::~RecordThread()
5933{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005934 if (mFastCapture != 0) {
5935 FastCaptureStateQueue *sq = mFastCapture->sq();
5936 FastCaptureState *state = sq->begin();
5937 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5938 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5939 if (old == -1) {
5940 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5941 }
5942 }
5943 state->mCommand = FastCaptureState::EXIT;
5944 sq->end();
5945 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5946 mFastCapture->join();
5947 mFastCapture.clear();
5948 }
5949 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005950 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005951 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005952}
5953
5954void AudioFlinger::RecordThread::onFirstRef()
5955{
Glenn Kastend7dca052015-03-05 16:05:54 -08005956 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005957}
5958
Eric Laurent81784c32012-11-19 14:55:58 -08005959bool AudioFlinger::RecordThread::threadLoop()
5960{
Eric Laurent81784c32012-11-19 14:55:58 -08005961 nsecs_t lastWarning = 0;
5962
5963 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005964
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005965reacquire_wakelock:
5966 sp<RecordTrack> activeTrack;
5967 {
5968 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005969 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005970 }
5971
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005972 // used to request a deferred sleep, to be executed later while mutex is unlocked
5973 uint32_t sleepUs = 0;
5974
5975 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005976 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005977 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005978
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005979 // activeTracks accumulates a copy of a subset of mActiveTracks
5980 Vector< sp<RecordTrack> > activeTracks;
5981
Glenn Kasten735f45f2014-08-18 15:51:59 -07005982 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005983 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005984
Glenn Kasten735f45f2014-08-18 15:51:59 -07005985 // reference to a fast track which is about to be removed
5986 sp<RecordTrack> fastTrackToRemove;
5987
Eric Laurent81784c32012-11-19 14:55:58 -08005988 { // scope for mLock
5989 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005990
Eric Laurent021cf962014-05-13 10:18:14 -07005991 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005992
Eric Laurent000a4192014-01-29 15:17:32 -08005993 // check exitPending here because checkForNewParameters_l() and
5994 // checkForNewParameters_l() can temporarily release mLock
5995 if (exitPending()) {
5996 break;
5997 }
5998
Eric Laurent5c25d562016-07-13 17:17:45 -07005999 // sleep with mutex unlocked
6000 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006001 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006002 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6003 ATRACE_END();
6004 sleepUs = 0;
6005 continue;
6006 }
6007
Glenn Kasten2b806402013-11-20 16:37:38 -08006008 // if no active track(s), then standby and release wakelock
6009 size_t size = mActiveTracks.size();
6010 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006011 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006012 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006013 releaseWakeLock_l();
6014 ALOGV("RecordThread: loop stopping");
6015 // go to sleep
6016 mWaitWorkCV.wait(mLock);
6017 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006018 goto reacquire_wakelock;
6019 }
6020
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006021 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006022 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006023 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006024
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006025 activeTrack = mActiveTracks[i];
6026 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006027 if (activeTrack->isFastTrack()) {
6028 ALOG_ASSERT(fastTrackToRemove == 0);
6029 fastTrackToRemove = activeTrack;
6030 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006031 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006032 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006033 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006034 continue;
6035 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006036
6037 TrackBase::track_state activeTrackState = activeTrack->mState;
6038 switch (activeTrackState) {
6039
6040 case TrackBase::PAUSING:
6041 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006042 doBroadcast = true;
6043 size--;
6044 continue;
6045
6046 case TrackBase::STARTING_1:
6047 sleepUs = 10000;
6048 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006049 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006050 continue;
6051
6052 case TrackBase::STARTING_2:
6053 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006054 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006055 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006056 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006057 break;
6058
6059 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006060 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006061 break;
6062
6063 case TrackBase::IDLE:
6064 i++;
6065 continue;
6066
6067 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006068 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006069 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006070
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006071 activeTracks.add(activeTrack);
6072 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006073
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006074 if (activeTrack->isFastTrack()) {
6075 ALOG_ASSERT(!mFastTrackAvail);
6076 ALOG_ASSERT(fastTrack == 0);
6077 fastTrack = activeTrack;
6078 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006079 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006080
Andy Hungdae27702016-10-31 14:01:16 -07006081 mActiveTracks.updatePowerState(this);
6082
Eric Laurent5c25d562016-07-13 17:17:45 -07006083 if (allStopped) {
6084 standbyIfNotAlreadyInStandby();
6085 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006086 if (doBroadcast) {
6087 mStartStopCond.broadcast();
6088 }
6089
6090 // sleep if there are no active tracks to process
6091 if (activeTracks.size() == 0) {
6092 if (sleepUs == 0) {
6093 sleepUs = kRecordThreadSleepUs;
6094 }
6095 continue;
6096 }
6097 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006098
Eric Laurent81784c32012-11-19 14:55:58 -08006099 lockEffectChains_l(effectChains);
6100 }
6101
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006102 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006103
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006104 size_t size = effectChains.size();
6105 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006106 // thread mutex is not locked, but effect chain is locked
6107 effectChains[i]->process_l();
6108 }
6109
Glenn Kasten735f45f2014-08-18 15:51:59 -07006110 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006111 if (mFastCapture != 0) {
6112 FastCaptureStateQueue *sq = mFastCapture->sq();
6113 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006114 bool didModify = false;
6115 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006116 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6117 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6118 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6119 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6120 if (old == -1) {
6121 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6122 }
6123 }
6124 state->mCommand = FastCaptureState::READ_WRITE;
6125#if 0 // FIXME
6126 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006127 FastThreadDumpState::kSamplingNforLowRamDevice :
6128 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006129#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006130 didModify = true;
6131 }
6132 audio_track_cblk_t *cblkOld = state->mCblk;
6133 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6134 if (cblkNew != cblkOld) {
6135 state->mCblk = cblkNew;
6136 // block until acked if removing a fast track
6137 if (cblkOld != NULL) {
6138 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6139 }
6140 didModify = true;
6141 }
6142 sq->end(didModify);
6143 if (didModify) {
6144 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006145#if 0
6146 if (kUseFastCapture == FastCapture_Dynamic) {
6147 mNormalSource = mPipeSource;
6148 }
6149#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006150 }
6151 }
6152
Glenn Kasten735f45f2014-08-18 15:51:59 -07006153 // now run the fast track destructor with thread mutex unlocked
6154 fastTrackToRemove.clear();
6155
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006156 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6157 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6158 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6159 // If destination is non-contiguous, first read past the nominal end of buffer, then
6160 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006161
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006163 ssize_t framesRead;
6164
6165 // If an NBAIO source is present, use it to read the normal capture's data
6166 if (mPipeSource != 0) {
6167 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006168 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006169 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006170 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006171 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6172 // buffer size or at least for 20ms.
6173 size_t sleepFrames = max(
6174 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6175 if (framesRead <= (ssize_t) sleepFrames) {
6176 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6177 }
6178 if (framesRead < 0) {
6179 status_t status = (status_t) framesRead;
6180 switch (status) {
6181 case OVERRUN:
6182 ALOGW("overrun on read from pipe");
6183 framesRead = 0;
6184 break;
6185 case NEGOTIATE:
6186 ALOGE("re-negotiation is needed");
6187 framesRead = -1; // Will cause an attempt to recover.
6188 break;
6189 default:
6190 ALOGE("unknown error %d on read from pipe", status);
6191 break;
6192 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006193 }
6194 // otherwise use the HAL / AudioStreamIn directly
6195 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006196 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006197 size_t bytesRead;
6198 status_t result = mInput->stream->read(
6199 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006200 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006201 if (result < 0) {
6202 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006203 } else {
6204 framesRead = bytesRead / mFrameSize;
6205 }
6206 }
6207
Andy Hung3f0c9022016-01-15 17:49:46 -08006208 // Update server timestamp with server stats
6209 // systemTime() is optional if the hardware supports timestamps.
6210 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6211 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6212
6213 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006214 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006215 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006216 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006217 if (ret == NO_ERROR) {
6218 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6219 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6220 // Note: In general record buffers should tend to be empty in
6221 // a properly running pipeline.
6222 //
6223 // Also, it is not advantageous to call get_presentation_position during the read
6224 // as the read obtains a lock, preventing the timestamp call from executing.
6225 }
6226 }
6227 // Use this to track timestamp information
6228 // ALOGD("%s", mTimestamp.toString().c_str());
6229
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006230 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006231 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006232 // Force input into standby so that it tries to recover at next read attempt
6233 inputStandBy();
6234 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006235 }
6236 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006237 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006238 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006240
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006241 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006242 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 }
6244 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006245 {
6246 size_t part1 = mRsmpInFramesP2 - rear;
6247 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006248 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006249 (framesRead - part1) * mFrameSize);
6250 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 }
6252 rear = mRsmpInRear += framesRead;
6253
6254 size = activeTracks.size();
6255 // loop over each active track
6256 for (size_t i = 0; i < size; i++) {
6257 activeTrack = activeTracks[i];
6258
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006259 // skip fast tracks, as those are handled directly by FastCapture
6260 if (activeTrack->isFastTrack()) {
6261 continue;
6262 }
6263
Andy Hung73c02e42015-03-29 01:13:58 -07006264 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006265 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6266
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006267 enum {
6268 OVERRUN_UNKNOWN,
6269 OVERRUN_TRUE,
6270 OVERRUN_FALSE
6271 } overrun = OVERRUN_UNKNOWN;
6272
6273 // loop over getNextBuffer to handle circular sink
6274 for (;;) {
6275
6276 activeTrack->mSink.frameCount = ~0;
6277 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6278 size_t framesOut = activeTrack->mSink.frameCount;
6279 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6280
Andy Hung73c02e42015-03-29 01:13:58 -07006281 // check available frames and handle overrun conditions
6282 // if the record track isn't draining fast enough.
6283 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006284 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006285 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6286 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006287 overrun = OVERRUN_TRUE;
6288 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006289 if (framesOut == 0 || framesIn == 0) {
6290 break;
6291 }
6292
Andy Hung6770c6f2015-04-07 13:43:36 -07006293 // Don't allow framesOut to be larger than what is possible with resampling
6294 // from framesIn.
6295 // This isn't strictly necessary but helps limit buffer resizing in
6296 // RecordBufferConverter. TODO: remove when no longer needed.
6297 framesOut = min(framesOut,
6298 destinationFramesPossible(
6299 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006300 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6301 framesOut = activeTrack->mRecordBufferConverter->convert(
6302 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303
6304 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6305 overrun = OVERRUN_FALSE;
6306 }
6307
6308 if (activeTrack->mFramesToDrop == 0) {
6309 if (framesOut > 0) {
6310 activeTrack->mSink.frameCount = framesOut;
6311 activeTrack->releaseBuffer(&activeTrack->mSink);
6312 }
6313 } else {
6314 // FIXME could do a partial drop of framesOut
6315 if (activeTrack->mFramesToDrop > 0) {
6316 activeTrack->mFramesToDrop -= framesOut;
6317 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006318 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006319 }
6320 } else {
6321 activeTrack->mFramesToDrop += framesOut;
6322 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6323 activeTrack->mSyncStartEvent->isCancelled()) {
6324 ALOGW("Synced record %s, session %d, trigger session %d",
6325 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6326 activeTrack->sessionId(),
6327 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006328 activeTrack->mSyncStartEvent->triggerSession() :
6329 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006330 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006331 }
6332 }
6333 }
6334
6335 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006336 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006337 }
6338 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339
6340 switch (overrun) {
6341 case OVERRUN_TRUE:
6342 // client isn't retrieving buffers fast enough
6343 if (!activeTrack->setOverflow()) {
6344 nsecs_t now = systemTime();
6345 // FIXME should lastWarning per track?
6346 if ((now - lastWarning) > kWarningThrottleNs) {
6347 ALOGW("RecordThread: buffer overflow");
6348 lastWarning = now;
6349 }
6350 }
6351 break;
6352 case OVERRUN_FALSE:
6353 activeTrack->clearOverflow();
6354 break;
6355 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006356 break;
6357 }
6358
Andy Hung3f0c9022016-01-15 17:49:46 -08006359 // update frame information and push timestamp out
6360 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006361 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006362 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6363 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006364 }
6365
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006366unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006367 // enable changes in effect chain
6368 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006369 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006370 }
6371
Glenn Kasten93e471f2013-08-19 08:40:07 -07006372 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006373
6374 {
6375 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006376 for (size_t i = 0; i < mTracks.size(); i++) {
6377 sp<RecordTrack> track = mTracks[i];
6378 track->invalidate();
6379 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006380 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006381 mStartStopCond.broadcast();
6382 }
6383
6384 releaseWakeLock();
6385
6386 ALOGV("RecordThread %p exiting", this);
6387 return false;
6388}
6389
Glenn Kasten93e471f2013-08-19 08:40:07 -07006390void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006391{
6392 if (!mStandby) {
6393 inputStandBy();
6394 mStandby = true;
6395 }
6396}
6397
6398void AudioFlinger::RecordThread::inputStandBy()
6399{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006400 // Idle the fast capture if it's currently running
6401 if (mFastCapture != 0) {
6402 FastCaptureStateQueue *sq = mFastCapture->sq();
6403 FastCaptureState *state = sq->begin();
6404 if (!(state->mCommand & FastCaptureState::IDLE)) {
6405 state->mCommand = FastCaptureState::COLD_IDLE;
6406 state->mColdFutexAddr = &mFastCaptureFutex;
6407 state->mColdGen++;
6408 mFastCaptureFutex = 0;
6409 sq->end();
6410 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6411 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6412#if 0
6413 if (kUseFastCapture == FastCapture_Dynamic) {
6414 // FIXME
6415 }
6416#endif
6417#ifdef AUDIO_WATCHDOG
6418 // FIXME
6419#endif
6420 } else {
6421 sq->end(false /*didModify*/);
6422 }
6423 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006424 status_t result = mInput->stream->standby();
6425 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006426
6427 // If going into standby, flush the pipe source.
6428 if (mPipeSource.get() != nullptr) {
6429 const ssize_t flushed = mPipeSource->flush();
6430 if (flushed > 0) {
6431 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6432 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6433 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6434 }
6435 }
Eric Laurent81784c32012-11-19 14:55:58 -08006436}
6437
Glenn Kasten05997e22014-03-13 15:08:33 -07006438// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006439sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006440 const sp<AudioFlinger::Client>& client,
6441 uint32_t sampleRate,
6442 audio_format_t format,
6443 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006444 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006445 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006446 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006447 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006448 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006449 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006450 status_t *status,
6451 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006452{
Glenn Kasten74935e42013-12-19 08:56:45 -08006453 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006454 sp<RecordTrack> track;
6455 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006456 audio_input_flags_t inputFlags = mInput->flags;
6457
6458 // special case for FAST flag considered OK if fast capture is present
6459 if (hasFastCapture()) {
6460 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6461 }
6462
6463 // Check if requested flags are compatible with output stream flags
6464 if ((*flags & inputFlags) != *flags) {
6465 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6466 " input flags (%08x)",
6467 *flags, inputFlags);
6468 *flags = (audio_input_flags_t)(*flags & inputFlags);
6469 }
Eric Laurent81784c32012-11-19 14:55:58 -08006470
Glenn Kasten90e58b12013-07-31 16:16:02 -07006471 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006472 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006473 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006474 // we formerly checked for a callback handler (non-0 tid),
6475 // but that is no longer required for TRANSFER_OBTAIN mode
6476 //
Glenn Kasten74105912014-07-03 12:28:53 -07006477 // frame count is not specified, or is exactly the pipe depth
6478 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006479 // PCM data
6480 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006481 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006482 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006483 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006484 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006485 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006486 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006487 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006488 hasFastCapture() &&
6489 // there are sufficient fast track slots available
6490 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006491 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006492 // check compatibility with audio effects.
6493 Mutex::Autolock _l(mLock);
6494 // Do not accept FAST flag if the session has software effects
6495 sp<EffectChain> chain = getEffectChain_l(sessionId);
6496 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006497 audio_input_flags_t old = *flags;
6498 chain->checkInputFlagCompatibility(flags);
6499 if (old != *flags) {
6500 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6501 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006502 }
6503 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006504 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006505 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6506 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006507 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006508 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006509 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006510 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006511 frameCount, mFrameCount, mPipeFramesP2,
6512 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6513 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006514 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006515 }
6516 }
6517
6518 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006519 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006520 // fast track: frame count is exactly the pipe depth
6521 frameCount = mPipeFramesP2;
6522 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6523 *notificationFrames = mFrameCount;
6524 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006525 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6526 // or 20 ms if there is a fast capture
6527 // TODO This could be a roundupRatio inline, and const
6528 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6529 * sampleRate + mSampleRate - 1) / mSampleRate;
6530 // minimum number of notification periods is at least kMinNotifications,
6531 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6532 static const size_t kMinNotifications = 3;
6533 static const uint32_t kMinMs = 30;
6534 // TODO This could be a roundupRatio inline
6535 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6536 // TODO This could be a roundupRatio inline
6537 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6538 maxNotificationFrames;
6539 const size_t minFrameCount = maxNotificationFrames *
6540 max(kMinNotifications, minNotificationsByMs);
6541 frameCount = max(frameCount, minFrameCount);
6542 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6543 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006544 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006545 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006546 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006547
Glenn Kasten15e57982013-09-24 11:52:37 -07006548 lStatus = initCheck();
6549 if (lStatus != NO_ERROR) {
6550 ALOGE("createRecordTrack_l() audio driver not initialized");
6551 goto Exit;
6552 }
Eric Laurent81784c32012-11-19 14:55:58 -08006553
6554 { // scope for mLock
6555 Mutex::Autolock _l(mLock);
6556
6557 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006558 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006559 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006560
Glenn Kasten03003332013-08-06 15:40:54 -07006561 lStatus = track->initCheck();
6562 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006563 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006564 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006565 goto Exit;
6566 }
6567 mTracks.add(track);
6568
6569 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6570 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6571 mAudioFlinger->btNrecIsOff();
6572 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6573 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006574
Eric Laurent05067782016-06-01 18:27:28 -07006575 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006576 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6577 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6578 // so ask activity manager to do this on our behalf
6579 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6580 }
Eric Laurent81784c32012-11-19 14:55:58 -08006581 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006582
Eric Laurent81784c32012-11-19 14:55:58 -08006583 lStatus = NO_ERROR;
6584
6585Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006586 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006587 return track;
6588}
6589
6590status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6591 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006592 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006593{
6594 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6595 sp<ThreadBase> strongMe = this;
6596 status_t status = NO_ERROR;
6597
6598 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006599 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006600 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006601 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006602 triggerSession,
6603 recordTrack->sessionId(),
6604 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006605 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006606 // Sync event can be cancelled by the trigger session if the track is not in a
6607 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006609 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006610 } else {
6611 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006612 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006613 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006614 }
6615 }
6616
6617 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006618 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006619 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006620 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6621 if (recordTrack->mState == TrackBase::PAUSING) {
6622 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006623 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006624 } else {
6625 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006626 }
6627 return status;
6628 }
6629
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006630 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6631 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6632 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006633 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006634 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006635 status_t status = NO_ERROR;
6636 if (recordTrack->isExternalTrack()) {
6637 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006638 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006639 mLock.lock();
6640 // FIXME should verify that recordTrack is still in mActiveTracks
6641 if (status != NO_ERROR) {
6642 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006643 recordTrack->clearSyncStartEvent();
6644 ALOGV("RecordThread::start error %d", status);
6645 return status;
6646 }
Eric Laurent81784c32012-11-19 14:55:58 -08006647 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006648 // Catch up with current buffer indices if thread is already running.
6649 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6650 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6651 // see previously buffered data before it called start(), but with greater risk of overrun.
6652
Andy Hung73c02e42015-03-29 01:13:58 -07006653 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006654 // clear any converter state as new data will be discontinuous
6655 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006656 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006657 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006658 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006659 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006660 ALOGV("Record failed to start");
6661 status = BAD_VALUE;
6662 goto startError;
6663 }
Eric Laurent81784c32012-11-19 14:55:58 -08006664 return status;
6665 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006666
Eric Laurent81784c32012-11-19 14:55:58 -08006667startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006668 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006669 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006670 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006671 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006672 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006673 return status;
6674}
6675
Eric Laurent81784c32012-11-19 14:55:58 -08006676void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6677{
6678 sp<SyncEvent> strongEvent = event.promote();
6679
6680 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006681 sp<RefBase> ptr = strongEvent->cookie().promote();
6682 if (ptr != 0) {
6683 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6684 recordTrack->handleSyncStartEvent(strongEvent);
6685 }
Eric Laurent81784c32012-11-19 14:55:58 -08006686 }
6687}
6688
Glenn Kastena8356f62013-07-25 14:37:52 -07006689bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006690 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006691 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006692 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006693 return false;
6694 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006695 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006696 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006697 // signal thread to stop
6698 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006699 // do not wait for mStartStopCond if exiting
6700 if (exitPending()) {
6701 return true;
6702 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006703 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006704 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006705 // if we have been restarted, recordTrack is in mActiveTracks here
6706 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006707 ALOGV("Record stopped OK");
6708 return true;
6709 }
6710 return false;
6711}
6712
Glenn Kasten0f11b512014-01-31 16:18:54 -08006713bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006714{
6715 return false;
6716}
6717
Glenn Kasten0f11b512014-01-31 16:18:54 -08006718status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006719{
6720#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6721 if (!isValidSyncEvent(event)) {
6722 return BAD_VALUE;
6723 }
6724
Glenn Kastend848eb42016-03-08 13:42:11 -08006725 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006726 status_t ret = NAME_NOT_FOUND;
6727
6728 Mutex::Autolock _l(mLock);
6729
6730 for (size_t i = 0; i < mTracks.size(); i++) {
6731 sp<RecordTrack> track = mTracks[i];
6732 if (eventSession == track->sessionId()) {
6733 (void) track->setSyncEvent(event);
6734 ret = NO_ERROR;
6735 }
6736 }
6737 return ret;
6738#else
6739 return BAD_VALUE;
6740#endif
6741}
6742
6743// destroyTrack_l() must be called with ThreadBase::mLock held
6744void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6745{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006746 track->terminate();
6747 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006748 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006749 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006750 removeTrack_l(track);
6751 }
6752}
6753
6754void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6755{
6756 mTracks.remove(track);
6757 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006758 if (track->isFastTrack()) {
6759 ALOG_ASSERT(!mFastTrackAvail);
6760 mFastTrackAvail = true;
6761 }
Eric Laurent81784c32012-11-19 14:55:58 -08006762}
6763
6764void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6765{
6766 dumpInternals(fd, args);
6767 dumpTracks(fd, args);
6768 dumpEffectChains(fd, args);
6769}
6770
6771void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6772{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006773 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006774
Glenn Kasten44182c22015-03-05 17:12:23 -08006775 dumpBase(fd, args);
6776
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006777 AudioStreamIn *input = mInput;
6778 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6779 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6780 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006781 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006782 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006783 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006784 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006785 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006786
Glenn Kasten2f90c512015-12-02 11:40:09 -08006787 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6788 // while we are dumping it. It may be inconsistent, but it won't mutate!
6789 // This is a large object so we place it on the heap.
6790 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6791 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6792 copy->dump(fd);
6793 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006794}
6795
Glenn Kasten0f11b512014-01-31 16:18:54 -08006796void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006797{
6798 const size_t SIZE = 256;
6799 char buffer[SIZE];
6800 String8 result;
6801
Marco Nelissenb2208842014-02-07 14:00:50 -08006802 size_t numtracks = mTracks.size();
6803 size_t numactive = mActiveTracks.size();
6804 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006805 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006806 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006807 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006808 RecordTrack::appendDumpHeader(result);
6809 for (size_t i = 0; i < numtracks ; ++i) {
6810 sp<RecordTrack> track = mTracks[i];
6811 if (track != 0) {
6812 bool active = mActiveTracks.indexOf(track) >= 0;
6813 if (active) {
6814 numactiveseen++;
6815 }
6816 track->dump(buffer, SIZE, active);
6817 result.append(buffer);
6818 }
Eric Laurent81784c32012-11-19 14:55:58 -08006819 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006820 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006821 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006822 }
6823
Marco Nelissenb2208842014-02-07 14:00:50 -08006824 if (numactiveseen != numactive) {
6825 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6826 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006827 result.append(buffer);
6828 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006829 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006830 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006831 if (mTracks.indexOf(track) < 0) {
6832 track->dump(buffer, SIZE, true);
6833 result.append(buffer);
6834 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006835 }
Eric Laurent81784c32012-11-19 14:55:58 -08006836
6837 }
6838 write(fd, result.string(), result.size());
6839}
6840
Andy Hung73c02e42015-03-29 01:13:58 -07006841
6842void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6843{
6844 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6845 RecordThread *recordThread = (RecordThread *) threadBase.get();
6846 mRsmpInFront = recordThread->mRsmpInRear;
6847 mRsmpInUnrel = 0;
6848}
6849
6850void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6851 size_t *framesAvailable, bool *hasOverrun)
6852{
6853 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6854 RecordThread *recordThread = (RecordThread *) threadBase.get();
6855 const int32_t rear = recordThread->mRsmpInRear;
6856 const int32_t front = mRsmpInFront;
6857 const ssize_t filled = rear - front;
6858
6859 size_t framesIn;
6860 bool overrun = false;
6861 if (filled < 0) {
6862 // should not happen, but treat like a massive overrun and re-sync
6863 framesIn = 0;
6864 mRsmpInFront = rear;
6865 overrun = true;
6866 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6867 framesIn = (size_t) filled;
6868 } else {
6869 // client is not keeping up with server, but give it latest data
6870 framesIn = recordThread->mRsmpInFrames;
6871 mRsmpInFront = /* front = */ rear - framesIn;
6872 overrun = true;
6873 }
6874 if (framesAvailable != NULL) {
6875 *framesAvailable = framesIn;
6876 }
6877 if (hasOverrun != NULL) {
6878 *hasOverrun = overrun;
6879 }
6880}
6881
Eric Laurent81784c32012-11-19 14:55:58 -08006882// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006883status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006884 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006885{
Andy Hung73c02e42015-03-29 01:13:58 -07006886 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006887 if (threadBase == 0) {
6888 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006889 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006890 return NOT_ENOUGH_DATA;
6891 }
6892 RecordThread *recordThread = (RecordThread *) threadBase.get();
6893 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006894 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006895 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006896 // FIXME should not be P2 (don't want to increase latency)
6897 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006898 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006899 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006900 front &= recordThread->mRsmpInFramesP2 - 1;
6901 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006902 if (part1 > (size_t) filled) {
6903 part1 = filled;
6904 }
6905 size_t ask = buffer->frameCount;
6906 ALOG_ASSERT(ask > 0);
6907 if (part1 > ask) {
6908 part1 = ask;
6909 }
6910 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006911 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006912 buffer->raw = NULL;
6913 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006914 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006915 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
6917
Andy Hung57446612015-04-19 23:56:46 -07006918 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006919 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006920 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006921 return NO_ERROR;
6922}
6923
6924// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006925void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6926 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006927{
Glenn Kasten85948432013-08-19 12:09:05 -07006928 size_t stepCount = buffer->frameCount;
6929 if (stepCount == 0) {
6930 return;
6931 }
Andy Hung73c02e42015-03-29 01:13:58 -07006932 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6933 mRsmpInUnrel -= stepCount;
6934 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006935 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006936 buffer->frameCount = 0;
6937}
6938
Andy Hung97a893e2015-03-29 01:03:07 -07006939AudioFlinger::RecordThread::RecordBufferConverter::RecordBufferConverter(
6940 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
6941 uint32_t srcSampleRate,
6942 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
6943 uint32_t dstSampleRate) :
6944 mSrcChannelMask(AUDIO_CHANNEL_INVALID), // updateParameters will set following vars
6945 // mSrcFormat
6946 // mSrcSampleRate
6947 // mDstChannelMask
6948 // mDstFormat
6949 // mDstSampleRate
6950 // mSrcChannelCount
6951 // mDstChannelCount
6952 // mDstFrameSize
6953 mBuf(NULL), mBufFrames(0), mBufFrameSize(0),
Andy Hungd330ee42015-04-20 13:23:41 -07006954 mResampler(NULL),
6955 mIsLegacyDownmix(false),
6956 mIsLegacyUpmix(false),
6957 mRequiresFloat(false),
6958 mInputConverterProvider(NULL)
Andy Hung97a893e2015-03-29 01:03:07 -07006959{
6960 (void)updateParameters(srcChannelMask, srcFormat, srcSampleRate,
6961 dstChannelMask, dstFormat, dstSampleRate);
6962}
6963
6964AudioFlinger::RecordThread::RecordBufferConverter::~RecordBufferConverter() {
6965 free(mBuf);
6966 delete mResampler;
Andy Hungd330ee42015-04-20 13:23:41 -07006967 delete mInputConverterProvider;
Andy Hung97a893e2015-03-29 01:03:07 -07006968}
6969
6970size_t AudioFlinger::RecordThread::RecordBufferConverter::convert(void *dst,
6971 AudioBufferProvider *provider, size_t frames)
6972{
Andy Hungd330ee42015-04-20 13:23:41 -07006973 if (mInputConverterProvider != NULL) {
6974 mInputConverterProvider->setBufferProvider(provider);
6975 provider = mInputConverterProvider;
6976 }
6977
6978 if (mResampler == NULL) {
Andy Hung97a893e2015-03-29 01:03:07 -07006979 ALOGVV("NO RESAMPLING sampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6980 mSrcSampleRate, mSrcFormat, mDstFormat);
6981
6982 AudioBufferProvider::Buffer buffer;
6983 for (size_t i = frames; i > 0; ) {
6984 buffer.frameCount = i;
Glenn Kastend79072e2016-01-06 08:41:20 -08006985 status_t status = provider->getNextBuffer(&buffer);
Andy Hung97a893e2015-03-29 01:03:07 -07006986 if (status != OK || buffer.frameCount == 0) {
6987 frames -= i; // cannot fill request.
6988 break;
6989 }
Andy Hungd330ee42015-04-20 13:23:41 -07006990 // format convert to destination buffer
6991 convertNoResampler(dst, buffer.raw, buffer.frameCount);
Andy Hung97a893e2015-03-29 01:03:07 -07006992
6993 dst = (int8_t*)dst + buffer.frameCount * mDstFrameSize;
6994 i -= buffer.frameCount;
6995 provider->releaseBuffer(&buffer);
6996 }
6997 } else {
6998 ALOGVV("RESAMPLING mSrcSampleRate:%u mDstSampleRate:%u mSrcFormat:%#x mDstFormat:%#x",
6999 mSrcSampleRate, mDstSampleRate, mSrcFormat, mDstFormat);
7000
Andy Hungd330ee42015-04-20 13:23:41 -07007001 // reallocate buffer if needed
7002 if (mBufFrameSize != 0 && mBufFrames < frames) {
7003 free(mBuf);
7004 mBufFrames = frames;
7005 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7006 }
Andy Hung97a893e2015-03-29 01:03:07 -07007007 // resampler accumulates, but we only have one source track
Andy Hungd330ee42015-04-20 13:23:41 -07007008 memset(mBuf, 0, frames * mBufFrameSize);
7009 frames = mResampler->resample((int32_t*)mBuf, frames, provider);
7010 // format convert to destination buffer
7011 convertResampler(dst, mBuf, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007012 }
7013 return frames;
7014}
7015
7016status_t AudioFlinger::RecordThread::RecordBufferConverter::updateParameters(
7017 audio_channel_mask_t srcChannelMask, audio_format_t srcFormat,
7018 uint32_t srcSampleRate,
7019 audio_channel_mask_t dstChannelMask, audio_format_t dstFormat,
7020 uint32_t dstSampleRate)
7021{
7022 // quick evaluation if there is any change.
7023 if (mSrcFormat == srcFormat
7024 && mSrcChannelMask == srcChannelMask
7025 && mSrcSampleRate == srcSampleRate
7026 && mDstFormat == dstFormat
7027 && mDstChannelMask == dstChannelMask
7028 && mDstSampleRate == dstSampleRate) {
7029 return NO_ERROR;
7030 }
7031
Andy Hungdb4c0312015-05-06 08:46:52 -07007032 ALOGV("RecordBufferConverter updateParameters srcMask:%#x dstMask:%#x"
7033 " srcFormat:%#x dstFormat:%#x srcRate:%u dstRate:%u",
7034 srcChannelMask, dstChannelMask, srcFormat, dstFormat, srcSampleRate, dstSampleRate);
Andy Hung97a893e2015-03-29 01:03:07 -07007035 const bool valid =
7036 audio_is_input_channel(srcChannelMask)
7037 && audio_is_input_channel(dstChannelMask)
7038 && audio_is_valid_format(srcFormat) && audio_is_linear_pcm(srcFormat)
7039 && audio_is_valid_format(dstFormat) && audio_is_linear_pcm(dstFormat)
7040 && (srcSampleRate <= dstSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX)
7041 ; // no upsampling checks for now
7042 if (!valid) {
7043 return BAD_VALUE;
7044 }
7045
7046 mSrcFormat = srcFormat;
7047 mSrcChannelMask = srcChannelMask;
7048 mSrcSampleRate = srcSampleRate;
7049 mDstFormat = dstFormat;
7050 mDstChannelMask = dstChannelMask;
7051 mDstSampleRate = dstSampleRate;
7052
7053 // compute derived parameters
7054 mSrcChannelCount = audio_channel_count_from_in_mask(srcChannelMask);
7055 mDstChannelCount = audio_channel_count_from_in_mask(dstChannelMask);
7056 mDstFrameSize = mDstChannelCount * audio_bytes_per_sample(mDstFormat);
7057
Andy Hungd330ee42015-04-20 13:23:41 -07007058 // do we need to resample?
7059 delete mResampler;
7060 mResampler = NULL;
7061 if (mSrcSampleRate != mDstSampleRate) {
7062 mResampler = AudioResampler::create(AUDIO_FORMAT_PCM_FLOAT,
7063 mSrcChannelCount, mDstSampleRate);
7064 mResampler->setSampleRate(mSrcSampleRate);
7065 mResampler->setVolume(AudioMixer::UNITY_GAIN_FLOAT, AudioMixer::UNITY_GAIN_FLOAT);
7066 }
7067
7068 // are we running legacy channel conversion modes?
7069 mIsLegacyDownmix = (mSrcChannelMask == AUDIO_CHANNEL_IN_STEREO
7070 || mSrcChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK)
7071 && mDstChannelMask == AUDIO_CHANNEL_IN_MONO;
7072 mIsLegacyUpmix = mSrcChannelMask == AUDIO_CHANNEL_IN_MONO
7073 && (mDstChannelMask == AUDIO_CHANNEL_IN_STEREO
7074 || mDstChannelMask == AUDIO_CHANNEL_IN_FRONT_BACK);
7075
7076 // do we need to process in float?
7077 mRequiresFloat = mResampler != NULL || mIsLegacyDownmix || mIsLegacyUpmix;
7078
7079 // do we need a staging buffer to convert for destination (we can still optimize this)?
7080 // we use mBufFrameSize > 0 to indicate both frame size as well as buffer necessity
7081 if (mResampler != NULL) {
7082 mBufFrameSize = max(mSrcChannelCount, FCC_2)
7083 * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
Andy Hunga97630b2015-07-22 23:27:24 -07007084 } else if (mIsLegacyUpmix || mIsLegacyDownmix) { // legacy modes always float
Andy Hungd330ee42015-04-20 13:23:41 -07007085 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(AUDIO_FORMAT_PCM_FLOAT);
7086 } else if (mSrcChannelMask != mDstChannelMask && mDstFormat != mSrcFormat) {
Andy Hung97a893e2015-03-29 01:03:07 -07007087 mBufFrameSize = mDstChannelCount * audio_bytes_per_sample(mSrcFormat);
7088 } else {
7089 mBufFrameSize = 0;
7090 }
7091 mBufFrames = 0; // force the buffer to be resized.
7092
Andy Hungd330ee42015-04-20 13:23:41 -07007093 // do we need an input converter buffer provider to give us float?
7094 delete mInputConverterProvider;
7095 mInputConverterProvider = NULL;
7096 if (mRequiresFloat && mSrcFormat != AUDIO_FORMAT_PCM_FLOAT) {
7097 mInputConverterProvider = new ReformatBufferProvider(
7098 audio_channel_count_from_in_mask(mSrcChannelMask),
7099 mSrcFormat,
7100 AUDIO_FORMAT_PCM_FLOAT,
7101 256 /* provider buffer frame count */);
7102 }
7103
7104 // do we need a remixer to do channel mask conversion
7105 if (!mIsLegacyDownmix && !mIsLegacyUpmix && mSrcChannelMask != mDstChannelMask) {
7106 (void) memcpy_by_index_array_initialization_from_channel_mask(
7107 mIdxAry, ARRAY_SIZE(mIdxAry), mDstChannelMask, mSrcChannelMask);
Andy Hung97a893e2015-03-29 01:03:07 -07007108 }
7109 return NO_ERROR;
7110}
7111
Andy Hungd330ee42015-04-20 13:23:41 -07007112void AudioFlinger::RecordThread::RecordBufferConverter::convertNoResampler(
7113 void *dst, const void *src, size_t frames)
Andy Hung97a893e2015-03-29 01:03:07 -07007114{
Andy Hungd330ee42015-04-20 13:23:41 -07007115 // src is native type unless there is legacy upmix or downmix, whereupon it is float.
Andy Hung97a893e2015-03-29 01:03:07 -07007116 if (mBufFrameSize != 0 && mBufFrames < frames) {
7117 free(mBuf);
7118 mBufFrames = frames;
7119 (void)posix_memalign(&mBuf, 32, mBufFrames * mBufFrameSize);
7120 }
Andy Hungd330ee42015-04-20 13:23:41 -07007121 // do we need to do legacy upmix and downmix?
7122 if (mIsLegacyUpmix || mIsLegacyDownmix) {
Andy Hung97a893e2015-03-29 01:03:07 -07007123 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007124 if (mIsLegacyUpmix) {
7125 upmix_to_stereo_float_from_mono_float((float *)dstBuf,
7126 (const float *)src, frames);
7127 } else /*mIsLegacyDownmix */ {
7128 downmix_to_mono_float_from_stereo_float((float *)dstBuf,
7129 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007130 }
Andy Hungd330ee42015-04-20 13:23:41 -07007131 if (mBuf != NULL) {
7132 memcpy_by_audio_format(dst, mDstFormat, mBuf, AUDIO_FORMAT_PCM_FLOAT,
7133 frames * mDstChannelCount);
7134 }
7135 return;
7136 }
7137 // do we need to do channel mask conversion?
7138 if (mSrcChannelMask != mDstChannelMask) {
Andy Hung97a893e2015-03-29 01:03:07 -07007139 void *dstBuf = mBuf != NULL ? mBuf : dst;
Andy Hungd330ee42015-04-20 13:23:41 -07007140 memcpy_by_index_array(dstBuf, mDstChannelCount,
7141 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mSrcFormat), frames);
7142 if (dstBuf == dst) {
7143 return; // format is the same
7144 }
7145 }
7146 // convert to destination buffer
7147 const void *convertBuf = mBuf != NULL ? mBuf : src;
7148 memcpy_by_audio_format(dst, mDstFormat, convertBuf, mSrcFormat,
7149 frames * mDstChannelCount);
7150}
7151
7152void AudioFlinger::RecordThread::RecordBufferConverter::convertResampler(
7153 void *dst, /*not-a-const*/ void *src, size_t frames)
7154{
7155 // src buffer format is ALWAYS float when entering this routine
7156 if (mIsLegacyUpmix) {
7157 ; // mono to stereo already handled by resampler
7158 } else if (mIsLegacyDownmix
7159 || (mSrcChannelMask == mDstChannelMask && mSrcChannelCount == 1)) {
7160 // the resampler outputs stereo for mono input channel (a feature?)
7161 // must convert to mono
7162 downmix_to_mono_float_from_stereo_float((float *)src,
7163 (const float *)src, frames);
7164 } else if (mSrcChannelMask != mDstChannelMask) {
7165 // convert to mono channel again for channel mask conversion (could be skipped
7166 // with further optimization).
Andy Hung97a893e2015-03-29 01:03:07 -07007167 if (mSrcChannelCount == 1) {
Andy Hungd330ee42015-04-20 13:23:41 -07007168 downmix_to_mono_float_from_stereo_float((float *)src,
7169 (const float *)src, frames);
Andy Hung97a893e2015-03-29 01:03:07 -07007170 }
Andy Hungd330ee42015-04-20 13:23:41 -07007171 // convert to destination format (in place, OK as float is larger than other types)
7172 if (mDstFormat != AUDIO_FORMAT_PCM_FLOAT) {
7173 memcpy_by_audio_format(src, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7174 frames * mSrcChannelCount);
7175 }
7176 // channel convert and save to dst
7177 memcpy_by_index_array(dst, mDstChannelCount,
7178 src, mSrcChannelCount, mIdxAry, audio_bytes_per_sample(mDstFormat), frames);
7179 return;
Andy Hung97a893e2015-03-29 01:03:07 -07007180 }
Andy Hungd330ee42015-04-20 13:23:41 -07007181 // convert to destination format and save to dst
7182 memcpy_by_audio_format(dst, mDstFormat, src, AUDIO_FORMAT_PCM_FLOAT,
7183 frames * mDstChannelCount);
Andy Hung97a893e2015-03-29 01:03:07 -07007184}
7185
Eric Laurent10351942014-05-08 18:49:52 -07007186bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7187 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007188{
7189 bool reconfig = false;
7190
Eric Laurent10351942014-05-08 18:49:52 -07007191 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007192
Eric Laurent10351942014-05-08 18:49:52 -07007193 audio_format_t reqFormat = mFormat;
7194 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007195 // 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 -07007196 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7197
7198 AudioParameter param = AudioParameter(keyValuePair);
7199 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007200
7201 // scope for AutoPark extends to end of method
7202 AutoPark<FastCapture> park(mFastCapture);
7203
Eric Laurent10351942014-05-08 18:49:52 -07007204 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7205 // channel count change can be requested. Do we mandate the first client defines the
7206 // HAL sampling rate and channel count or do we allow changes on the fly?
7207 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7208 samplingRate = value;
7209 reconfig = true;
7210 }
7211 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007212 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007213 status = BAD_VALUE;
7214 } else {
7215 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007216 reconfig = true;
7217 }
Eric Laurent10351942014-05-08 18:49:52 -07007218 }
7219 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7220 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007221 if (!audio_is_input_channel(mask) ||
7222 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007223 status = BAD_VALUE;
7224 } else {
7225 channelMask = mask;
7226 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007227 }
Eric Laurent10351942014-05-08 18:49:52 -07007228 }
7229 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7230 // do not accept frame count changes if tracks are open as the track buffer
7231 // size depends on frame count and correct behavior would not be guaranteed
7232 // if frame count is changed after track creation
7233 if (mActiveTracks.size() > 0) {
7234 status = INVALID_OPERATION;
7235 } else {
7236 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007237 }
Eric Laurent10351942014-05-08 18:49:52 -07007238 }
7239 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7240 // forward device change to effects that have requested to be
7241 // aware of attached audio device.
7242 for (size_t i = 0; i < mEffectChains.size(); i++) {
7243 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007244 }
Eric Laurent81784c32012-11-19 14:55:58 -08007245
Eric Laurent10351942014-05-08 18:49:52 -07007246 // store input device and output device but do not forward output device to audio HAL.
7247 // Note that status is ignored by the caller for output device
7248 // (see AudioFlinger::setParameters()
7249 if (audio_is_output_devices(value)) {
7250 mOutDevice = value;
7251 status = BAD_VALUE;
7252 } else {
7253 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007254 if (value != AUDIO_DEVICE_NONE) {
7255 mPrevInDevice = value;
7256 }
Eric Laurent10351942014-05-08 18:49:52 -07007257 // disable AEC and NS if the device is a BT SCO headset supporting those
7258 // pre processings
7259 if (mTracks.size() > 0) {
7260 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7261 mAudioFlinger->btNrecIsOff();
7262 for (size_t i = 0; i < mTracks.size(); i++) {
7263 sp<RecordTrack> track = mTracks[i];
7264 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7265 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007266 }
7267 }
7268 }
Eric Laurent10351942014-05-08 18:49:52 -07007269 }
7270 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7271 mAudioSource != (audio_source_t)value) {
7272 // forward device change to effects that have requested to be
7273 // aware of attached audio device.
7274 for (size_t i = 0; i < mEffectChains.size(); i++) {
7275 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007276 }
Eric Laurent10351942014-05-08 18:49:52 -07007277 mAudioSource = (audio_source_t)value;
7278 }
Glenn Kastene198c362013-08-13 09:13:36 -07007279
Eric Laurent10351942014-05-08 18:49:52 -07007280 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007281 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007282 if (status == INVALID_OPERATION) {
7283 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007284 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007285 }
7286 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007287 if (status == BAD_VALUE) {
7288 uint32_t sRate;
7289 audio_channel_mask_t channelMask;
7290 audio_format_t format;
7291 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7292 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7293 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7294 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7295 status = NO_ERROR;
7296 }
Eric Laurent81784c32012-11-19 14:55:58 -08007297 }
Eric Laurent10351942014-05-08 18:49:52 -07007298 if (status == NO_ERROR) {
7299 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007300 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007301 }
7302 }
Eric Laurent81784c32012-11-19 14:55:58 -08007303 }
Eric Laurent10351942014-05-08 18:49:52 -07007304
Eric Laurent81784c32012-11-19 14:55:58 -08007305 return reconfig;
7306}
7307
7308String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7309{
Eric Laurent81784c32012-11-19 14:55:58 -08007310 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007311 if (initCheck() == NO_ERROR) {
7312 String8 out_s8;
7313 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7314 return out_s8;
7315 }
Eric Laurent81784c32012-11-19 14:55:58 -08007316 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007317 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007318}
7319
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007320void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007321 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7322
7323 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007324
7325 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007326 case AUDIO_INPUT_OPENED:
7327 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007328 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007329 desc->mChannelMask = mChannelMask;
7330 desc->mSamplingRate = mSampleRate;
7331 desc->mFormat = mFormat;
7332 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007333 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007334 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007335 break;
7336
Eric Laurent73e26b62015-04-27 16:55:58 -07007337 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007338 default:
7339 break;
7340 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007341 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007342}
7343
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007344void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007345{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007346 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7347 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007348 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007349 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007350 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007351 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7352 result = mInput->stream->getFrameSize(&mFrameSize);
7353 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7354 result = mInput->stream->getBufferSize(&mBufferSize);
7355 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007356 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007357 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007358 // 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 -07007359 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007360 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007361 // A larger value should allow more old data to be read after a track calls start(),
7362 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007363 //
7364 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007365 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007366 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007367 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007368 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007369
7370 // TODO optimize audio capture buffer sizes ...
7371 // Here we calculate the size of the sliding buffer used as a source
7372 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7373 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7374 // be better to have it derived from the pipe depth in the long term.
7375 // The current value is higher than necessary. However it should not add to latency.
7376
Glenn Kasten85948432013-08-19 12:09:05 -07007377 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007378 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7379 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7380 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007381
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007382 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7383 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007384}
7385
Glenn Kasten5f972c02014-01-13 09:59:31 -08007386uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007387{
7388 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007389 uint32_t result;
7390 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7391 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007392 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007393 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007394}
7395
Eric Laurent4c415062016-06-17 16:14:16 -07007396// hasAudioSession_l() must be called with ThreadBase::mLock held
7397uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007398{
Eric Laurent81784c32012-11-19 14:55:58 -08007399 uint32_t result = 0;
7400 if (getEffectChain_l(sessionId) != 0) {
7401 result = EFFECT_SESSION;
7402 }
7403
7404 for (size_t i = 0; i < mTracks.size(); ++i) {
7405 if (sessionId == mTracks[i]->sessionId()) {
7406 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007407 if (mTracks[i]->isFastTrack()) {
7408 result |= FAST_SESSION;
7409 }
Eric Laurent81784c32012-11-19 14:55:58 -08007410 break;
7411 }
7412 }
7413
7414 return result;
7415}
7416
Glenn Kastend848eb42016-03-08 13:42:11 -08007417KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007418{
Glenn Kastend848eb42016-03-08 13:42:11 -08007419 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007420 Mutex::Autolock _l(mLock);
7421 for (size_t j = 0; j < mTracks.size(); ++j) {
7422 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007423 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007424 if (ids.indexOfKey(sessionId) < 0) {
7425 ids.add(sessionId, true);
7426 }
7427 }
7428 return ids;
7429}
7430
7431AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7432{
7433 Mutex::Autolock _l(mLock);
7434 AudioStreamIn *input = mInput;
7435 mInput = NULL;
7436 return input;
7437}
7438
7439// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007440sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007441{
7442 if (mInput == NULL) {
7443 return NULL;
7444 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007445 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007446}
7447
7448status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7449{
7450 // only one chain per input thread
7451 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007452 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007453 return INVALID_OPERATION;
7454 }
7455 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007456 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007457 chain->setInBuffer(NULL);
7458 chain->setOutBuffer(NULL);
7459
7460 checkSuspendOnAddEffectChain_l(chain);
7461
Eric Laurent1b928682014-10-02 19:41:47 -07007462 // make sure enabled pre processing effects state is communicated to the HAL as we
7463 // just moved them to a new input stream.
7464 chain->syncHalEffectsState();
7465
Eric Laurent81784c32012-11-19 14:55:58 -08007466 mEffectChains.add(chain);
7467
7468 return NO_ERROR;
7469}
7470
7471size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7472{
7473 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7474 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007475 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007476 chain.get(), mEffectChains.size(), this);
7477 if (mEffectChains.size() == 1) {
7478 mEffectChains.removeAt(0);
7479 }
7480 return 0;
7481}
7482
Eric Laurent1c333e22014-05-20 10:48:17 -07007483status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7484 audio_patch_handle_t *handle)
7485{
7486 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007487
7488 // store new device and send to effects
7489 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007490 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007491 for (size_t i = 0; i < mEffectChains.size(); i++) {
7492 mEffectChains[i]->setDevice_l(mInDevice);
7493 }
7494
7495 // disable AEC and NS if the device is a BT SCO headset supporting those
7496 // pre processings
7497 if (mTracks.size() > 0) {
7498 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7499 mAudioFlinger->btNrecIsOff();
7500 for (size_t i = 0; i < mTracks.size(); i++) {
7501 sp<RecordTrack> track = mTracks[i];
7502 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7503 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7504 }
7505 }
7506
7507 // store new source and send to effects
7508 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7509 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007510 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007511 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007512 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007513 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007514
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007515 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007516 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7517 status = hwDevice->createAudioPatch(patch->num_sources,
7518 patch->sources,
7519 patch->num_sinks,
7520 patch->sinks,
7521 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007522 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007523 char *address;
7524 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7525 address = audio_device_address_to_parameter(
7526 patch->sources[0].ext.device.type,
7527 patch->sources[0].ext.device.address);
7528 } else {
7529 address = (char *)calloc(1, 1);
7530 }
7531 AudioParameter param = AudioParameter(String8(address));
7532 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007533 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007534 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007535 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007536 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007537 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007538 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007539 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007540
Eric Laurente8726fe2015-06-26 09:39:24 -07007541 if (mInDevice != mPrevInDevice) {
7542 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7543 mPrevInDevice = mInDevice;
7544 }
Eric Laurent296fb132015-05-01 11:38:42 -07007545
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 return status;
7547}
7548
7549status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7550{
7551 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007552
7553 mInDevice = AUDIO_DEVICE_NONE;
7554
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007555 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007556 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7557 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007558 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007559 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007560 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007561 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007562 }
7563 return status;
7564}
7565
Eric Laurent83b88082014-06-20 18:31:16 -07007566void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7567{
7568 Mutex::Autolock _l(mLock);
7569 mTracks.add(record);
7570}
7571
7572void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7573{
7574 Mutex::Autolock _l(mLock);
7575 destroyTrack_l(record);
7576}
7577
7578void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7579{
7580 ThreadBase::getAudioPortConfig(config);
7581 config->role = AUDIO_PORT_ROLE_SINK;
7582 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7583 config->ext.mix.usecase.source = mAudioSource;
7584}
Eric Laurent1c333e22014-05-20 10:48:17 -07007585
Glenn Kasten63238ef2015-03-02 15:50:29 -08007586} // namespace android