blob: a8c761fbdd2578de9348f294843efa4dbffe277a [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>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Andy Hung2ddee192015-12-18 17:34:44 -080039#include <audio_utils/conversion.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Eric Laurent81784c32012-11-19 14:55:58 -080077// ----------------------------------------------------------------------------
78
79// Note: the following macro is used for extremely verbose logging message. In
80// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
81// 0; but one side effect of this is to turn all LOGV's as well. Some messages
82// are so verbose that we want to suppress them even when we have ALOG_ASSERT
83// turned on. Do not uncomment the #def below unless you really know what you
84// are doing and want to see all of the extremely verbose messages.
85//#define VERY_VERY_VERBOSE_LOGGING
86#ifdef VERY_VERY_VERBOSE_LOGGING
87#define ALOGVV ALOGV
88#else
89#define ALOGVV(a...) do { } while(0)
90#endif
91
Andy Hung6770c6f2015-04-07 13:43:36 -070092// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070093#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070094template <typename T>
95static inline T min(const T& a, const T& b)
96{
97 return a < b ? a : b;
98}
Glenn Kasten49d00ad2014-07-21 11:22:03 -070099
Andy Hungd330ee42015-04-20 13:23:41 -0700100#ifndef ARRAY_SIZE
Chih-Hung Hsiehbf291732016-05-17 15:16:07 -0700101#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
Andy Hungd330ee42015-04-20 13:23:41 -0700102#endif
103
Eric Laurent81784c32012-11-19 14:55:58 -0800104namespace android {
105
106// retry counts for buffer fill timeout
107// 50 * ~20msecs = 1 second
108static const int8_t kMaxTrackRetries = 50;
109static const int8_t kMaxTrackStartupRetries = 50;
110// allow less retry attempts on direct output thread.
111// direct outputs can be a scarce resource in audio hardware and should
112// be released as quickly as possible.
113static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700114
Eric Laurent51716182016-02-29 18:00:56 -0800115
Eric Laurent81784c32012-11-19 14:55:58 -0800116
117// don't warn about blocked writes or record buffer overflows more often than this
118static const nsecs_t kWarningThrottleNs = seconds(5);
119
120// RecordThread loop sleep time upon application overrun or audio HAL read error
121static const int kRecordThreadSleepUs = 5000;
122
Eric Laurent10351942014-05-08 18:49:52 -0700123// maximum time to wait in sendConfigEvent_l() for a status to be received
124static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800125
126// minimum sleep time for the mixer thread loop when tracks are active but in underrun
127static const uint32_t kMinThreadSleepTimeUs = 5000;
128// maximum divider applied to the active sleep time in the mixer thread loop
129static const uint32_t kMaxThreadSleepTimeShift = 2;
130
Andy Hung09a50072014-02-27 14:30:47 -0800131// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700132// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800133static const uint32_t kMinNormalSinkBufferSizeMs = 20;
134// maximum normal sink buffer size
135static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800136
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700137// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
138// FIXME This should be based on experimentally observed scheduling jitter
139static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
140
Eric Laurent972a1732013-09-04 09:42:59 -0700141// Offloaded output thread standby delay: allows track transition without going to standby
142static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
143
Eric Laurent51716182016-02-29 18:00:56 -0800144// Direct output thread minimum sleep time in idle or active(underrun) state
145static const nsecs_t kDirectMinSleepTimeUs = 10000;
146
Glenn Kasten1b291842016-07-18 14:55:21 -0700147// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
148// balance between power consumption and latency, and allows threads to be scheduled reliably
149// by the CFS scheduler.
150// FIXME Express other hardcoded references to 20ms with references to this constant and move
151// it appropriately.
152#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800153
Eric Laurent81784c32012-11-19 14:55:58 -0800154// Whether to use fast mixer
155static const enum {
156 FastMixer_Never, // never initialize or use: for debugging only
157 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
158 // normal mixer multiplier is 1
159 FastMixer_Static, // initialize if needed, then use all the time if initialized,
160 // multiplier is calculated based on min & max normal mixer buffer size
161 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 // FIXME for FastMixer_Dynamic:
164 // Supporting this option will require fixing HALs that can't handle large writes.
165 // For example, one HAL implementation returns an error from a large write,
166 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
167 // We could either fix the HAL implementations, or provide a wrapper that breaks
168 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
169} kUseFastMixer = FastMixer_Static;
170
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700171// Whether to use fast capture
172static const enum {
173 FastCapture_Never, // never initialize or use: for debugging only
174 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
175 FastCapture_Static, // initialize if needed, then use all the time if initialized
176} kUseFastCapture = FastCapture_Static;
177
Eric Laurent81784c32012-11-19 14:55:58 -0800178// Priorities for requestPriority
179static const int kPriorityAudioApp = 2;
180static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
Glenn Kastenea38ee72016-04-18 11:08:01 -0700183// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
184// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
185// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700186
187// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800188static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800189
Glenn Kasten03490092014-05-27 12:30:54 -0700190// The minimum and maximum allowed values
191static const int kFastTrackMultiplierMin = 1;
192static const int kFastTrackMultiplierMax = 2;
193
194// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
195static int sFastTrackMultiplier = kFastTrackMultiplier;
196
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700197// See Thread::readOnlyHeap().
198// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
199// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
200// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700201static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700202
Eric Laurent81784c32012-11-19 14:55:58 -0800203// ----------------------------------------------------------------------------
204
Glenn Kasten03490092014-05-27 12:30:54 -0700205static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
206
207static void sFastTrackMultiplierInit()
208{
209 char value[PROPERTY_VALUE_MAX];
210 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
211 char *endptr;
212 unsigned long ul = strtoul(value, &endptr, 0);
213 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
214 sFastTrackMultiplier = (int) ul;
215 }
216 }
217}
218
219// ----------------------------------------------------------------------------
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221#ifdef ADD_BATTERY_DATA
222// To collect the amplifier usage
223static void addBatteryData(uint32_t params) {
224 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
225 if (service == NULL) {
226 // it already logged
227 return;
228 }
229
230 service->addBatteryData(params);
231}
232#endif
233
Andy Hung3f0c9022016-01-15 17:49:46 -0800234// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
235struct {
236 // call when you acquire a partial wakelock
237 void acquire(const sp<IBinder> &wakeLockToken) {
238 pthread_mutex_lock(&mLock);
239 if (wakeLockToken.get() == nullptr) {
240 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
241 } else {
242 if (mCount == 0) {
243 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
244 }
245 ++mCount;
246 }
247 pthread_mutex_unlock(&mLock);
248 }
249
250 // call when you release a partial wakelock.
251 void release(const sp<IBinder> &wakeLockToken) {
252 if (wakeLockToken.get() == nullptr) {
253 return;
254 }
255 pthread_mutex_lock(&mLock);
256 if (--mCount < 0) {
257 ALOGE("negative wakelock count");
258 mCount = 0;
259 }
260 pthread_mutex_unlock(&mLock);
261 }
262
263 // retrieves the boottime timebase offset from monotonic.
264 int64_t getBoottimeOffset() {
265 pthread_mutex_lock(&mLock);
266 int64_t boottimeOffset = mBoottimeOffset;
267 pthread_mutex_unlock(&mLock);
268 return boottimeOffset;
269 }
270
271 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
272 // and the selected timebase.
273 // Currently only TIMEBASE_BOOTTIME is allowed.
274 //
275 // This only needs to be called upon acquiring the first partial wakelock
276 // after all other partial wakelocks are released.
277 //
278 // We do an empirical measurement of the offset rather than parsing
279 // /proc/timer_list since the latter is not a formal kernel ABI.
280 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
281 int clockbase;
282 switch (timebase) {
283 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
284 clockbase = SYSTEM_TIME_BOOTTIME;
285 break;
286 default:
287 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
288 break;
289 }
290 // try three times to get the clock offset, choose the one
291 // with the minimum gap in measurements.
292 const int tries = 3;
293 nsecs_t bestGap, measured;
294 for (int i = 0; i < tries; ++i) {
295 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
296 const nsecs_t tbase = systemTime(clockbase);
297 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
298 const nsecs_t gap = tmono2 - tmono;
299 if (i == 0 || gap < bestGap) {
300 bestGap = gap;
301 measured = tbase - ((tmono + tmono2) >> 1);
302 }
303 }
304
305 // to avoid micro-adjusting, we don't change the timebase
306 // unless it is significantly different.
307 //
308 // Assumption: It probably takes more than toleranceNs to
309 // suspend and resume the device.
310 static int64_t toleranceNs = 10000; // 10 us
311 if (llabs(*offset - measured) > toleranceNs) {
312 ALOGV("Adjusting timebase offset old: %lld new: %lld",
313 (long long)*offset, (long long)measured);
314 *offset = measured;
315 }
316 }
317
318 pthread_mutex_t mLock;
319 int32_t mCount;
320 int64_t mBoottimeOffset;
321} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800322
323// ----------------------------------------------------------------------------
324// CPU Stats
325// ----------------------------------------------------------------------------
326
327class CpuStats {
328public:
329 CpuStats();
330 void sample(const String8 &title);
331#ifdef DEBUG_CPU_USAGE
332private:
333 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
334 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
335
336 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
337
338 int mCpuNum; // thread's current CPU number
339 int mCpukHz; // frequency of thread's current CPU in kHz
340#endif
341};
342
343CpuStats::CpuStats()
344#ifdef DEBUG_CPU_USAGE
345 : mCpuNum(-1), mCpukHz(-1)
346#endif
347{
348}
349
Glenn Kasten0f11b512014-01-31 16:18:54 -0800350void CpuStats::sample(const String8 &title
351#ifndef DEBUG_CPU_USAGE
352 __unused
353#endif
354 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800355#ifdef DEBUG_CPU_USAGE
356 // get current thread's delta CPU time in wall clock ns
357 double wcNs;
358 bool valid = mCpuUsage.sampleAndEnable(wcNs);
359
360 // record sample for wall clock statistics
361 if (valid) {
362 mWcStats.sample(wcNs);
363 }
364
365 // get the current CPU number
366 int cpuNum = sched_getcpu();
367
368 // get the current CPU frequency in kHz
369 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
370
371 // check if either CPU number or frequency changed
372 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
373 mCpuNum = cpuNum;
374 mCpukHz = cpukHz;
375 // ignore sample for purposes of cycles
376 valid = false;
377 }
378
379 // if no change in CPU number or frequency, then record sample for cycle statistics
380 if (valid && mCpukHz > 0) {
381 double cycles = wcNs * cpukHz * 0.000001;
382 mHzStats.sample(cycles);
383 }
384
385 unsigned n = mWcStats.n();
386 // mCpuUsage.elapsed() is expensive, so don't call it every loop
387 if ((n & 127) == 1) {
388 long long elapsed = mCpuUsage.elapsed();
389 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
390 double perLoop = elapsed / (double) n;
391 double perLoop100 = perLoop * 0.01;
392 double perLoop1k = perLoop * 0.001;
393 double mean = mWcStats.mean();
394 double stddev = mWcStats.stddev();
395 double minimum = mWcStats.minimum();
396 double maximum = mWcStats.maximum();
397 double meanCycles = mHzStats.mean();
398 double stddevCycles = mHzStats.stddev();
399 double minCycles = mHzStats.minimum();
400 double maxCycles = mHzStats.maximum();
401 mCpuUsage.resetElapsed();
402 mWcStats.reset();
403 mHzStats.reset();
404 ALOGD("CPU usage for %s over past %.1f secs\n"
405 " (%u mixer loops at %.1f mean ms per loop):\n"
406 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
407 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
408 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
409 title.string(),
410 elapsed * .000000001, n, perLoop * .000001,
411 mean * .001,
412 stddev * .001,
413 minimum * .001,
414 maximum * .001,
415 mean / perLoop100,
416 stddev / perLoop100,
417 minimum / perLoop100,
418 maximum / perLoop100,
419 meanCycles / perLoop1k,
420 stddevCycles / perLoop1k,
421 minCycles / perLoop1k,
422 maxCycles / perLoop1k);
423
424 }
425 }
426#endif
427};
428
429// ----------------------------------------------------------------------------
430// ThreadBase
431// ----------------------------------------------------------------------------
432
Glenn Kasten97b7b752014-09-28 13:04:24 -0700433// static
434const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
435{
436 switch (type) {
437 case MIXER:
438 return "MIXER";
439 case DIRECT:
440 return "DIRECT";
441 case DUPLICATING:
442 return "DUPLICATING";
443 case RECORD:
444 return "RECORD";
445 case OFFLOAD:
446 return "OFFLOAD";
447 default:
448 return "unknown";
449 }
450}
451
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700452std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800453{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700454 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800455 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700456 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800457 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700458 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800459 }
460 return result;
461}
462
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700463std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800464{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700465 std::string result;
466 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467 return result;
468}
469
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700470std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700471{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700472 std::string result;
473 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700474 return result;
475}
476
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800477const char *sourceToString(audio_source_t source)
478{
479 switch (source) {
480 case AUDIO_SOURCE_DEFAULT: return "default";
481 case AUDIO_SOURCE_MIC: return "mic";
482 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
483 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
484 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
485 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
486 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
487 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
488 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800489 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800490 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
491 case AUDIO_SOURCE_HOTWORD: return "hotword";
492 default: return "unknown";
493 }
494}
495
Eric Laurent81784c32012-11-19 14:55:58 -0800496AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700497 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800498 : Thread(false /*canCallJava*/),
499 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700500 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700501 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800502 // are set by PlaybackThread::readOutputParameters_l() or
503 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700504 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800505 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700506 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
507 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800508 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700509 mDeathRecipient(new PMDeathRecipient(this)),
Andy Hungdae27702016-10-31 14:01:16 -0700510 mSystemReady(systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800511{
Eric Laurent296fb132015-05-01 11:38:42 -0700512 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800513}
514
515AudioFlinger::ThreadBase::~ThreadBase()
516{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700517 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700518 mConfigEvents.clear();
519
Eric Laurent81784c32012-11-19 14:55:58 -0800520 // do not lock the mutex in destructor
521 releaseWakeLock_l();
522 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800523 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800524 binder->unlinkToDeath(mDeathRecipient);
525 }
526}
527
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700528status_t AudioFlinger::ThreadBase::readyToRun()
529{
530 status_t status = initCheck();
531 if (status == NO_ERROR) {
532 ALOGI("AudioFlinger's thread %p ready to run", this);
533 } else {
534 ALOGE("No working audio driver found.");
535 }
536 return status;
537}
538
Eric Laurent81784c32012-11-19 14:55:58 -0800539void AudioFlinger::ThreadBase::exit()
540{
541 ALOGV("ThreadBase::exit");
542 // do any cleanup required for exit to succeed
543 preExit();
544 {
545 // This lock prevents the following race in thread (uniprocessor for illustration):
546 // if (!exitPending()) {
547 // // context switch from here to exit()
548 // // exit() calls requestExit(), what exitPending() observes
549 // // exit() calls signal(), which is dropped since no waiters
550 // // context switch back from exit() to here
551 // mWaitWorkCV.wait(...);
552 // // now thread is hung
553 // }
554 AutoMutex lock(mLock);
555 requestExit();
556 mWaitWorkCV.broadcast();
557 }
558 // When Thread::requestExitAndWait is made virtual and this method is renamed to
559 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
560 requestExitAndWait();
561}
562
563status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
564{
Eric Laurent81784c32012-11-19 14:55:58 -0800565 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
566 Mutex::Autolock _l(mLock);
567
Eric Laurent10351942014-05-08 18:49:52 -0700568 return sendSetParameterConfigEvent_l(keyValuePairs);
569}
570
571// sendConfigEvent_l() must be called with ThreadBase::mLock held
572// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
573status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
574{
575 status_t status = NO_ERROR;
576
Eric Laurent72e3f392015-05-20 14:43:50 -0700577 if (event->mRequiresSystemReady && !mSystemReady) {
578 event->mWaitStatus = false;
579 mPendingConfigEvents.add(event);
580 return status;
581 }
Eric Laurent10351942014-05-08 18:49:52 -0700582 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700583 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800584 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700585 mLock.unlock();
586 {
587 Mutex::Autolock _l(event->mLock);
588 while (event->mWaitStatus) {
589 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
590 event->mStatus = TIMED_OUT;
591 event->mWaitStatus = false;
592 }
593 }
594 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800595 }
Eric Laurent10351942014-05-08 18:49:52 -0700596 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800597 return status;
598}
599
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700600void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800601{
602 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700603 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800604}
605
606// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700607void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800608{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700610 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800611}
612
Eric Laurent72e3f392015-05-20 14:43:50 -0700613void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio)
614{
615 Mutex::Autolock _l(mLock);
616 sendPrioConfigEvent_l(pid, tid, prio);
617}
618
Eric Laurent81784c32012-11-19 14:55:58 -0800619// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
620void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio)
621{
Eric Laurent10351942014-05-08 18:49:52 -0700622 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio);
623 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800624}
625
Eric Laurent10351942014-05-08 18:49:52 -0700626// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
627status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800628{
Andy Hung2ddee192015-12-18 17:34:44 -0800629 sp<ConfigEvent> configEvent;
630 AudioParameter param(keyValuePair);
631 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700632 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800633 setMasterMono_l(value != 0);
634 if (param.size() == 1) {
635 return NO_ERROR; // should be a solo parameter - we don't pass down
636 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700637 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800638 configEvent = new SetParameterConfigEvent(param.toString());
639 } else {
640 configEvent = new SetParameterConfigEvent(keyValuePair);
641 }
Eric Laurent10351942014-05-08 18:49:52 -0700642 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700643}
644
Eric Laurent1c333e22014-05-20 10:48:17 -0700645status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
646 const struct audio_patch *patch,
647 audio_patch_handle_t *handle)
648{
649 Mutex::Autolock _l(mLock);
650 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
651 status_t status = sendConfigEvent_l(configEvent);
652 if (status == NO_ERROR) {
653 CreateAudioPatchConfigEventData *data =
654 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
655 *handle = data->mHandle;
656 }
657 return status;
658}
659
660status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
661 const audio_patch_handle_t handle)
662{
663 Mutex::Autolock _l(mLock);
664 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
665 return sendConfigEvent_l(configEvent);
666}
667
668
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700669// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700670void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700671{
Eric Laurent10351942014-05-08 18:49:52 -0700672 bool configChanged = false;
673
Eric Laurent81784c32012-11-19 14:55:58 -0800674 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700675 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700676 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800677 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700678 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700679 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700680 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
681 // FIXME Need to understand why this has to be done asynchronously
682 int err = requestPriority(data->mPid, data->mTid, data->mPrio,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700683 true /*asynchronous*/);
684 if (err != 0) {
685 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700686 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700687 }
688 } break;
689 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700690 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700691 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700692 } break;
693 case CFG_EVENT_SET_PARAMETER: {
694 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
695 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
696 configChanged = true;
Glenn Kastend5418eb2013-08-14 13:11:06 -0700697 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700698 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700699 case CFG_EVENT_CREATE_AUDIO_PATCH: {
700 CreateAudioPatchConfigEventData *data =
701 (CreateAudioPatchConfigEventData *)event->mData.get();
702 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
703 } break;
704 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
705 ReleaseAudioPatchConfigEventData *data =
706 (ReleaseAudioPatchConfigEventData *)event->mData.get();
707 event->mStatus = releaseAudioPatch_l(data->mHandle);
708 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700709 default:
Eric Laurent10351942014-05-08 18:49:52 -0700710 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700711 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800712 }
Eric Laurent10351942014-05-08 18:49:52 -0700713 {
714 Mutex::Autolock _l(event->mLock);
715 if (event->mWaitStatus) {
716 event->mWaitStatus = false;
717 event->mCond.signal();
718 }
719 }
720 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
721 }
722
723 if (configChanged) {
724 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800725 }
Eric Laurent81784c32012-11-19 14:55:58 -0800726}
727
Marco Nelissenb2208842014-02-07 14:00:50 -0800728String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
729 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700730 const audio_channel_representation_t representation =
731 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700732
733 switch (representation) {
734 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
735 if (output) {
736 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
737 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
738 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
739 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
740 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
741 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
742 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
743 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
744 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
745 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
746 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
747 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
748 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
749 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
750 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
751 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
753 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
754 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
755 } else {
756 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
757 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
758 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
759 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
760 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
761 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
762 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
763 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
764 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
765 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
766 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
767 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
768 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
769 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
770 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
771 }
772 const int len = s.length();
773 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700774 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700775 s.unlockBuffer(len - 2); // remove trailing ", "
776 }
777 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800778 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700779 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
780 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
781 return s;
782 default:
783 s.appendFormat("unknown mask, representation:%d bits:%#x",
784 representation, audio_channel_mask_get_bits(mask));
785 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800786 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800787}
788
Glenn Kasten0f11b512014-01-31 16:18:54 -0800789void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800790{
791 const size_t SIZE = 256;
792 char buffer[SIZE];
793 String8 result;
794
795 bool locked = AudioFlinger::dumpTryLock(mLock);
796 if (!locked) {
Glenn Kasten97b7b752014-09-28 13:04:24 -0700797 dprintf(fd, "thread %p may be deadlocked\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -0800798 }
799
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800800 dprintf(fd, " Thread name: %s\n", mThreadName);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700801 dprintf(fd, " I/O handle: %d\n", mId);
802 dprintf(fd, " TID: %d\n", getTid());
803 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700804 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700805 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700806 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700807 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700808 dprintf(fd, " Channel count: %u\n", mChannelCount);
809 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800810 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700811 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700812 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700813 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800814 size_t numConfig = mConfigEvents.size();
815 if (numConfig) {
816 for (size_t i = 0; i < numConfig; i++) {
817 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800819 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700820 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800821 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800823 }
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700824 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
825 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800826 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800827
828 if (locked) {
829 mLock.unlock();
830 }
831}
832
833void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
834{
835 const size_t SIZE = 256;
836 char buffer[SIZE];
837 String8 result;
838
Marco Nelissenb2208842014-02-07 14:00:50 -0800839 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000840 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800841 write(fd, buffer, strlen(buffer));
842
Marco Nelissenb2208842014-02-07 14:00:50 -0800843 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800844 sp<EffectChain> chain = mEffectChains[i];
845 if (chain != 0) {
846 chain->dump(fd, args);
847 }
848 }
849}
850
Andy Hungdae27702016-10-31 14:01:16 -0700851void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800852{
853 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700854 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800855}
856
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100857String16 AudioFlinger::ThreadBase::getWakeLockTag()
858{
859 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800860 case MIXER:
861 return String16("AudioMix");
862 case DIRECT:
863 return String16("AudioDirectOut");
864 case DUPLICATING:
865 return String16("AudioDup");
866 case RECORD:
867 return String16("AudioIn");
868 case OFFLOAD:
869 return String16("AudioOffload");
870 default:
871 ALOG_ASSERT(false);
872 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100873 }
874}
875
Andy Hungdae27702016-10-31 14:01:16 -0700876void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800877{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800878 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800879 if (mPowerManager != 0) {
880 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700881 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
882 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700883 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100884 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700885 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700886 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800887 if (status == NO_ERROR) {
888 mWakeLockToken = binder;
889 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800890 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800891 }
Wei Jia3f273d12015-11-24 09:06:49 -0800892
Andy Hung3f0c9022016-01-15 17:49:46 -0800893 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800894 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
895 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800896}
897
898void AudioFlinger::ThreadBase::releaseWakeLock()
899{
900 Mutex::Autolock _l(mLock);
901 releaseWakeLock_l();
902}
903
904void AudioFlinger::ThreadBase::releaseWakeLock_l()
905{
Andy Hung3f0c9022016-01-15 17:49:46 -0800906 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800907 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800908 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800909 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700910 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
911 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800912 }
913 mWakeLockToken.clear();
914 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800915}
916
917void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700918 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800919 // use checkService() to avoid blocking if power service is not up yet
920 sp<IBinder> binder =
921 defaultServiceManager()->checkService(String16("power"));
922 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800923 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800924 } else {
925 mPowerManager = interface_cast<IPowerManager>(binder);
926 binder->linkToDeath(mDeathRecipient);
927 }
928 }
929}
930
Andy Hungd01b0f12016-11-07 16:10:30 -0800931void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800932 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700933
934#if !LOG_NDEBUG
935 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800936 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700937 s << uid << " ";
938 }
939 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
940#endif
941
Andy Hung438e7572015-12-14 15:51:17 -0800942 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
943 if (mSystemReady) {
944 ALOGE("no wake lock to update, but system ready!");
945 } else {
946 ALOGW("no wake lock to update, system not ready yet");
947 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800948 return;
949 }
950 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800951 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
952 status_t status = mPowerManager->updateWakeLockUids(
953 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
954 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800955 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800956 }
957}
958
Eric Laurent81784c32012-11-19 14:55:58 -0800959void AudioFlinger::ThreadBase::clearPowerManager()
960{
961 Mutex::Autolock _l(mLock);
962 releaseWakeLock_l();
963 mPowerManager.clear();
964}
965
Glenn Kasten0f11b512014-01-31 16:18:54 -0800966void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800967{
968 sp<ThreadBase> thread = mThread.promote();
969 if (thread != 0) {
970 thread->clearPowerManager();
971 }
972 ALOGW("power manager service died !!!");
973}
974
975void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800976 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800977{
978 Mutex::Autolock _l(mLock);
979 setEffectSuspended_l(type, suspend, sessionId);
980}
981
982void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800983 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800984{
985 sp<EffectChain> chain = getEffectChain_l(sessionId);
986 if (chain != 0) {
987 if (type != NULL) {
988 chain->setEffectSuspended_l(type, suspend);
989 } else {
990 chain->setEffectSuspendedAll_l(suspend);
991 }
992 }
993
994 updateSuspendedSessions_l(type, suspend, sessionId);
995}
996
997void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
998{
999 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1000 if (index < 0) {
1001 return;
1002 }
1003
1004 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1005 mSuspendedSessions.valueAt(index);
1006
1007 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001008 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001009 for (int j = 0; j < desc->mRefCount; j++) {
1010 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1011 chain->setEffectSuspendedAll_l(true);
1012 } else {
1013 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1014 desc->mType.timeLow);
1015 chain->setEffectSuspended_l(&desc->mType, true);
1016 }
1017 }
1018 }
1019}
1020
1021void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1022 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001023 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001024{
1025 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1026
1027 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1028
1029 if (suspend) {
1030 if (index >= 0) {
1031 sessionEffects = mSuspendedSessions.valueAt(index);
1032 } else {
1033 mSuspendedSessions.add(sessionId, sessionEffects);
1034 }
1035 } else {
1036 if (index < 0) {
1037 return;
1038 }
1039 sessionEffects = mSuspendedSessions.valueAt(index);
1040 }
1041
1042
1043 int key = EffectChain::kKeyForSuspendAll;
1044 if (type != NULL) {
1045 key = type->timeLow;
1046 }
1047 index = sessionEffects.indexOfKey(key);
1048
1049 sp<SuspendedSessionDesc> desc;
1050 if (suspend) {
1051 if (index >= 0) {
1052 desc = sessionEffects.valueAt(index);
1053 } else {
1054 desc = new SuspendedSessionDesc();
1055 if (type != NULL) {
1056 desc->mType = *type;
1057 }
1058 sessionEffects.add(key, desc);
1059 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1060 }
1061 desc->mRefCount++;
1062 } else {
1063 if (index < 0) {
1064 return;
1065 }
1066 desc = sessionEffects.valueAt(index);
1067 if (--desc->mRefCount == 0) {
1068 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1069 sessionEffects.removeItemsAt(index);
1070 if (sessionEffects.isEmpty()) {
1071 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1072 sessionId);
1073 mSuspendedSessions.removeItem(sessionId);
1074 }
1075 }
1076 }
1077 if (!sessionEffects.isEmpty()) {
1078 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1079 }
1080}
1081
1082void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1083 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001084 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001085{
1086 Mutex::Autolock _l(mLock);
1087 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1088}
1089
1090void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1091 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001092 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001093{
1094 if (mType != RECORD) {
1095 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1096 // another session. This gives the priority to well behaved effect control panels
1097 // and applications not using global effects.
1098 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1099 // global effects
1100 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1101 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1102 }
1103 }
1104
1105 sp<EffectChain> chain = getEffectChain_l(sessionId);
1106 if (chain != 0) {
1107 chain->checkSuspendOnEffectEnabled(effect, enabled);
1108 }
1109}
1110
Eric Laurent4c415062016-06-17 16:14:16 -07001111// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1112status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1113 const effect_descriptor_t *desc, audio_session_t sessionId)
1114{
1115 // No global effect sessions on record threads
1116 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1117 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1118 desc->name, mThreadName);
1119 return BAD_VALUE;
1120 }
1121 // only pre processing effects on record thread
1122 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1123 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1124 desc->name, mThreadName);
1125 return BAD_VALUE;
1126 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001127
1128 // always allow effects without processing load or latency
1129 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1130 return NO_ERROR;
1131 }
1132
Eric Laurent4c415062016-06-17 16:14:16 -07001133 audio_input_flags_t flags = mInput->flags;
1134 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1135 if (flags & AUDIO_INPUT_FLAG_RAW) {
1136 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1137 desc->name, mThreadName);
1138 return BAD_VALUE;
1139 }
1140 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1141 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1142 desc->name, mThreadName);
1143 return BAD_VALUE;
1144 }
1145 }
1146 return NO_ERROR;
1147}
1148
1149// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1150status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1151 const effect_descriptor_t *desc, audio_session_t sessionId)
1152{
1153 // no preprocessing on playback threads
1154 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1155 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1156 " thread %s", desc->name, mThreadName);
1157 return BAD_VALUE;
1158 }
1159
1160 switch (mType) {
1161 case MIXER: {
1162 // Reject any effect on mixer multichannel sinks.
1163 // TODO: fix both format and multichannel issues with effects.
1164 if (mChannelCount != FCC_2) {
1165 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1166 " thread %s", desc->name, mChannelCount, mThreadName);
1167 return BAD_VALUE;
1168 }
1169 audio_output_flags_t flags = mOutput->flags;
1170 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1171 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1172 // global effects are applied only to non fast tracks if they are SW
1173 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1174 break;
1175 }
1176 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1177 // only post processing on output stage session
1178 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1179 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1180 " on output stage session", desc->name);
1181 return BAD_VALUE;
1182 }
1183 } else {
1184 // no restriction on effects applied on non fast tracks
1185 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1186 break;
1187 }
1188 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001189
1190 // always allow effects without processing load or latency
1191 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1192 break;
1193 }
Eric Laurent4c415062016-06-17 16:14:16 -07001194 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1195 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1196 desc->name);
1197 return BAD_VALUE;
1198 }
1199 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1200 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1201 " in fast mode", desc->name);
1202 return BAD_VALUE;
1203 }
1204 }
1205 } break;
1206 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001207 // nothing actionable on offload threads, if the effect:
1208 // - is offloadable: the effect can be created
1209 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1210 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001211 break;
1212 case DIRECT:
1213 // Reject any effect on Direct output threads for now, since the format of
1214 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1215 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1216 desc->name, mThreadName);
1217 return BAD_VALUE;
1218 case DUPLICATING:
1219 // Reject any effect on mixer multichannel sinks.
1220 // TODO: fix both format and multichannel issues with effects.
1221 if (mChannelCount != FCC_2) {
1222 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1223 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1224 return BAD_VALUE;
1225 }
1226 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1227 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1228 " thread %s", desc->name, mThreadName);
1229 return BAD_VALUE;
1230 }
1231 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1232 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1233 " DUPLICATING thread %s", desc->name, mThreadName);
1234 return BAD_VALUE;
1235 }
1236 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1237 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1238 " DUPLICATING thread %s", desc->name, mThreadName);
1239 return BAD_VALUE;
1240 }
1241 break;
1242 default:
1243 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1244 }
1245
1246 return NO_ERROR;
1247}
1248
Eric Laurent81784c32012-11-19 14:55:58 -08001249// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1250sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1251 const sp<AudioFlinger::Client>& client,
1252 const sp<IEffectClient>& effectClient,
1253 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001254 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001255 effect_descriptor_t *desc,
1256 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001257 status_t *status,
1258 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001259{
1260 sp<EffectModule> effect;
1261 sp<EffectHandle> handle;
1262 status_t lStatus;
1263 sp<EffectChain> chain;
1264 bool chainCreated = false;
1265 bool effectCreated = false;
1266 bool effectRegistered = false;
1267
1268 lStatus = initCheck();
1269 if (lStatus != NO_ERROR) {
1270 ALOGW("createEffect_l() Audio driver not initialized.");
1271 goto Exit;
1272 }
1273
Eric Laurent81784c32012-11-19 14:55:58 -08001274 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1275
1276 { // scope for mLock
1277 Mutex::Autolock _l(mLock);
1278
Eric Laurent4c415062016-06-17 16:14:16 -07001279 lStatus = checkEffectCompatibility_l(desc, sessionId);
1280 if (lStatus != NO_ERROR) {
1281 goto Exit;
1282 }
1283
Eric Laurent81784c32012-11-19 14:55:58 -08001284 // check for existing effect chain with the requested audio session
1285 chain = getEffectChain_l(sessionId);
1286 if (chain == 0) {
1287 // create a new chain for this session
1288 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1289 chain = new EffectChain(this, sessionId);
1290 addEffectChain_l(chain);
1291 chain->setStrategy(getStrategyForSession_l(sessionId));
1292 chainCreated = true;
1293 } else {
1294 effect = chain->getEffectFromDesc_l(desc);
1295 }
1296
1297 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1298
1299 if (effect == 0) {
Glenn Kasteneeecb982016-02-26 10:44:04 -08001300 audio_unique_id_t id = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001301 // Check CPU and memory usage
1302 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
1303 if (lStatus != NO_ERROR) {
1304 goto Exit;
1305 }
1306 effectRegistered = true;
1307 // create a new effect module if none present in the chain
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001308 lStatus = chain->createEffect_l(effect, this, desc, id, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001309 if (lStatus != NO_ERROR) {
1310 goto Exit;
1311 }
1312 effectCreated = true;
1313
1314 effect->setDevice(mOutDevice);
1315 effect->setDevice(mInDevice);
1316 effect->setMode(mAudioFlinger->getMode());
1317 effect->setAudioSource(mAudioSource);
1318 }
1319 // create effect handle and connect it to effect module
1320 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001321 lStatus = handle->initCheck();
1322 if (lStatus == OK) {
1323 lStatus = effect->addHandle(handle.get());
1324 }
Eric Laurent81784c32012-11-19 14:55:58 -08001325 if (enabled != NULL) {
1326 *enabled = (int)effect->isEnabled();
1327 }
1328 }
1329
1330Exit:
1331 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1332 Mutex::Autolock _l(mLock);
1333 if (effectCreated) {
1334 chain->removeEffect_l(effect);
1335 }
1336 if (effectRegistered) {
1337 AudioSystem::unregisterEffect(effect->id());
1338 }
1339 if (chainCreated) {
1340 removeEffectChain_l(chain);
1341 }
1342 handle.clear();
1343 }
1344
Glenn Kasten9156ef32013-08-06 15:39:08 -07001345 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001346 return handle;
1347}
1348
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001349void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1350 bool unpinIfLast)
1351{
1352 bool remove = false;
1353 sp<EffectModule> effect;
1354 {
1355 Mutex::Autolock _l(mLock);
1356
1357 effect = handle->effect().promote();
1358 if (effect == 0) {
1359 return;
1360 }
1361 // restore suspended effects if the disconnected handle was enabled and the last one.
1362 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1363 if (remove) {
1364 removeEffect_l(effect, true);
1365 }
1366 }
1367 if (remove) {
1368 mAudioFlinger->updateOrphanEffectChains(effect);
1369 AudioSystem::unregisterEffect(effect->id());
1370 if (handle->enabled()) {
1371 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1372 }
1373 }
1374}
1375
Glenn Kastend848eb42016-03-08 13:42:11 -08001376sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1377 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001378{
1379 Mutex::Autolock _l(mLock);
1380 return getEffect_l(sessionId, effectId);
1381}
1382
Glenn Kastend848eb42016-03-08 13:42:11 -08001383sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1384 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001385{
1386 sp<EffectChain> chain = getEffectChain_l(sessionId);
1387 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1388}
1389
1390// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1391// PlaybackThread::mLock held
1392status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1393{
1394 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001395 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001396 sp<EffectChain> chain = getEffectChain_l(sessionId);
1397 bool chainCreated = false;
1398
Eric Laurent5baf2af2013-09-12 17:37:00 -07001399 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1400 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1401 this, effect->desc().name, effect->desc().flags);
1402
Eric Laurent81784c32012-11-19 14:55:58 -08001403 if (chain == 0) {
1404 // create a new chain for this session
1405 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1406 chain = new EffectChain(this, sessionId);
1407 addEffectChain_l(chain);
1408 chain->setStrategy(getStrategyForSession_l(sessionId));
1409 chainCreated = true;
1410 }
1411 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1412
1413 if (chain->getEffectFromId_l(effect->id()) != 0) {
1414 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1415 this, effect->desc().name, chain.get());
1416 return BAD_VALUE;
1417 }
1418
Eric Laurent5baf2af2013-09-12 17:37:00 -07001419 effect->setOffloaded(mType == OFFLOAD, mId);
1420
Eric Laurent81784c32012-11-19 14:55:58 -08001421 status_t status = chain->addEffect_l(effect);
1422 if (status != NO_ERROR) {
1423 if (chainCreated) {
1424 removeEffectChain_l(chain);
1425 }
1426 return status;
1427 }
1428
1429 effect->setDevice(mOutDevice);
1430 effect->setDevice(mInDevice);
1431 effect->setMode(mAudioFlinger->getMode());
1432 effect->setAudioSource(mAudioSource);
1433 return NO_ERROR;
1434}
1435
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001436void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001437
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001438 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001439 effect_descriptor_t desc = effect->desc();
1440 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1441 detachAuxEffect_l(effect->id());
1442 }
1443
1444 sp<EffectChain> chain = effect->chain().promote();
1445 if (chain != 0) {
1446 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001447 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001448 removeEffectChain_l(chain);
1449 }
1450 } else {
1451 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1452 }
1453}
1454
1455void AudioFlinger::ThreadBase::lockEffectChains_l(
1456 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1457{
1458 effectChains = mEffectChains;
1459 for (size_t i = 0; i < mEffectChains.size(); i++) {
1460 mEffectChains[i]->lock();
1461 }
1462}
1463
1464void AudioFlinger::ThreadBase::unlockEffectChains(
1465 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1466{
1467 for (size_t i = 0; i < effectChains.size(); i++) {
1468 effectChains[i]->unlock();
1469 }
1470}
1471
Glenn Kastend848eb42016-03-08 13:42:11 -08001472sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001473{
1474 Mutex::Autolock _l(mLock);
1475 return getEffectChain_l(sessionId);
1476}
1477
Glenn Kastend848eb42016-03-08 13:42:11 -08001478sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1479 const
Eric Laurent81784c32012-11-19 14:55:58 -08001480{
1481 size_t size = mEffectChains.size();
1482 for (size_t i = 0; i < size; i++) {
1483 if (mEffectChains[i]->sessionId() == sessionId) {
1484 return mEffectChains[i];
1485 }
1486 }
1487 return 0;
1488}
1489
1490void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1491{
1492 Mutex::Autolock _l(mLock);
1493 size_t size = mEffectChains.size();
1494 for (size_t i = 0; i < size; i++) {
1495 mEffectChains[i]->setMode_l(mode);
1496 }
1497}
1498
Eric Laurent83b88082014-06-20 18:31:16 -07001499void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1500{
1501 config->type = AUDIO_PORT_TYPE_MIX;
1502 config->ext.mix.handle = mId;
1503 config->sample_rate = mSampleRate;
1504 config->format = mFormat;
1505 config->channel_mask = mChannelMask;
1506 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1507 AUDIO_PORT_CONFIG_FORMAT;
1508}
1509
Eric Laurent72e3f392015-05-20 14:43:50 -07001510void AudioFlinger::ThreadBase::systemReady()
1511{
1512 Mutex::Autolock _l(mLock);
1513 if (mSystemReady) {
1514 return;
1515 }
1516 mSystemReady = true;
1517
1518 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1519 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1520 }
1521 mPendingConfigEvents.clear();
1522}
1523
Andy Hungdae27702016-10-31 14:01:16 -07001524template <typename T>
1525ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1526 ssize_t index = mActiveTracks.indexOf(track);
1527 if (index >= 0) {
1528 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1529 return index;
1530 }
1531 mActiveTracksGeneration++;
1532 mLatestActiveTrack = track;
1533 ++mBatteryCounter[track->uid()].second;
1534 return mActiveTracks.add(track);
1535}
1536
1537template <typename T>
1538ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1539 ssize_t index = mActiveTracks.remove(track);
1540 if (index < 0) {
1541 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1542 return index;
1543 }
1544 mActiveTracksGeneration++;
1545 --mBatteryCounter[track->uid()].second;
1546 // mLatestActiveTrack is not cleared even if is the same as track.
1547 return index;
1548}
1549
1550template <typename T>
1551void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1552 for (const sp<T> &track : mActiveTracks) {
1553 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1554 }
1555 mLastActiveTracksGeneration = mActiveTracksGeneration;
1556 mActiveTracks.clear();
1557 mLatestActiveTrack.clear();
1558 mBatteryCounter.clear();
1559}
1560
1561template <typename T>
1562void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1563 sp<ThreadBase> thread, bool force) {
1564 // Updates ActiveTracks client uids to the thread wakelock.
1565 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1566 thread->updateWakeLockUids_l(getWakeLockUids());
1567 mLastActiveTracksGeneration = mActiveTracksGeneration;
1568 }
1569
1570 // Updates BatteryNotifier uids
1571 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1572 const uid_t uid = it->first;
1573 ssize_t &previous = it->second.first;
1574 ssize_t &current = it->second.second;
1575 if (current > 0) {
1576 if (previous == 0) {
1577 BatteryNotifier::getInstance().noteStartAudio(uid);
1578 }
1579 previous = current;
1580 ++it;
1581 } else if (current == 0) {
1582 if (previous > 0) {
1583 BatteryNotifier::getInstance().noteStopAudio(uid);
1584 }
1585 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1586 } else /* (current < 0) */ {
1587 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1588 }
1589 }
1590}
Eric Laurent83b88082014-06-20 18:31:16 -07001591
Eric Laurent81784c32012-11-19 14:55:58 -08001592// ----------------------------------------------------------------------------
1593// Playback
1594// ----------------------------------------------------------------------------
1595
1596AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1597 AudioStreamOut* output,
1598 audio_io_handle_t id,
1599 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001600 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001601 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001602 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001603 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001604 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001605 mMixerBuffer(NULL),
1606 mMixerBufferSize(0),
1607 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1608 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001609 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001610 mEffectBuffer(NULL),
1611 mEffectBufferSize(0),
1612 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1613 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001614 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001615 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001616 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001617 // mStreamTypes[] initialized in constructor body
1618 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001619 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001620 mMixerStatus(MIXER_IDLE),
1621 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001622 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001623 mBytesRemaining(0),
1624 mCurrentWriteLength(0),
1625 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001626 mWriteAckSequence(0),
1627 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001628 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001629 mScreenState(AudioFlinger::mScreenState),
1630 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001631 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001632 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001633{
Glenn Kastend7dca052015-03-05 16:05:54 -08001634 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1635 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001636
1637 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1638 // it would be safer to explicitly pass initial masterVolume/masterMute as
1639 // parameter.
1640 //
1641 // If the HAL we are using has support for master volume or master mute,
1642 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1643 // and the mute set to false).
1644 mMasterVolume = audioFlinger->masterVolume_l();
1645 mMasterMute = audioFlinger->masterMute_l();
1646 if (mOutput && mOutput->audioHwDev) {
1647 if (mOutput->audioHwDev->canSetMasterVolume()) {
1648 mMasterVolume = 1.0;
1649 }
1650
1651 if (mOutput->audioHwDev->canSetMasterMute()) {
1652 mMasterMute = false;
1653 }
1654 }
1655
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001656 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001657
Eric Laurent223fd5c2014-11-11 13:43:36 -08001658 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001659 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001660 stream = (audio_stream_type_t) (stream + 1)) {
1661 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1662 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1663 }
Eric Laurent81784c32012-11-19 14:55:58 -08001664}
1665
1666AudioFlinger::PlaybackThread::~PlaybackThread()
1667{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001668 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001669 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001670 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001671 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001672}
1673
1674void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1675{
1676 dumpInternals(fd, args);
1677 dumpTracks(fd, args);
1678 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001679 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001680}
1681
Glenn Kasten0f11b512014-01-31 16:18:54 -08001682void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001683{
1684 const size_t SIZE = 256;
1685 char buffer[SIZE];
1686 String8 result;
1687
Marco Nelissenb2208842014-02-07 14:00:50 -08001688 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001689 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1690 const stream_type_t *st = &mStreamTypes[i];
1691 if (i > 0) {
1692 result.appendFormat(", ");
1693 }
1694 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1695 if (st->mute) {
1696 result.append("M");
1697 }
1698 }
1699 result.append("\n");
1700 write(fd, result.string(), result.length());
1701 result.clear();
1702
Eric Laurent81784c32012-11-19 14:55:58 -08001703 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1704 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001705 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001706 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001707
1708 size_t numtracks = mTracks.size();
1709 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001710 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001711 size_t numactiveseen = 0;
1712 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001713 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001714 Track::appendDumpHeader(result);
1715 for (size_t i = 0; i < numtracks; ++i) {
1716 sp<Track> track = mTracks[i];
1717 if (track != 0) {
1718 bool active = mActiveTracks.indexOf(track) >= 0;
1719 if (active) {
1720 numactiveseen++;
1721 }
1722 track->dump(buffer, SIZE, active);
1723 result.append(buffer);
1724 }
1725 }
1726 } else {
1727 result.append("\n");
1728 }
1729 if (numactiveseen != numactive) {
1730 // some tracks in the active list were not in the tracks list
1731 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1732 " not in the track list\n");
1733 result.append(buffer);
1734 Track::appendDumpHeader(result);
1735 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001736 sp<Track> track = mActiveTracks[i];
1737 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001738 track->dump(buffer, SIZE, true);
1739 result.append(buffer);
1740 }
1741 }
1742 }
1743
1744 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001745}
1746
1747void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1748{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001749 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001750
1751 dumpBase(fd, args);
1752
Elliott Hughes87cebad2014-05-22 10:14:43 -07001753 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001754 dprintf(fd, " Last write occurred (msecs): %llu\n",
1755 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001756 dprintf(fd, " Total writes: %d\n", mNumWrites);
1757 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1758 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1759 dprintf(fd, " Suspend count: %d\n", mSuspended);
1760 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1761 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1762 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1763 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001764 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001765 AudioStreamOut *output = mOutput;
1766 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001767 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1768 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001769 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1770 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1771 if (mPipeSink.get() != nullptr) {
1772 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1773 }
1774 if (output != nullptr) {
1775 dprintf(fd, " Hal stream dump:\n");
1776 (void)output->stream->dump(fd);
1777 }
Eric Laurent81784c32012-11-19 14:55:58 -08001778}
1779
1780// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001781
1782void AudioFlinger::PlaybackThread::onFirstRef()
1783{
Glenn Kastend7dca052015-03-05 16:05:54 -08001784 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001785}
1786
1787// ThreadBase virtuals
1788void AudioFlinger::PlaybackThread::preExit()
1789{
1790 ALOGV(" preExit()");
1791 // FIXME this is using hard-coded strings but in the future, this functionality will be
1792 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001793 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1794 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001795}
1796
1797// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1798sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1799 const sp<AudioFlinger::Client>& client,
1800 audio_stream_type_t streamType,
1801 uint32_t sampleRate,
1802 audio_format_t format,
1803 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001804 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001805 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001806 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001807 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001808 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001809 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001810 status_t *status,
1811 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001812{
Glenn Kasten74935e42013-12-19 08:56:45 -08001813 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001814 sp<Track> track;
1815 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001816 audio_output_flags_t outputFlags = mOutput->flags;
1817
1818 // special case for FAST flag considered OK if fast mixer is present
1819 if (hasFastMixer()) {
1820 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1821 }
1822
1823 // Check if requested flags are compatible with output stream flags
1824 if ((*flags & outputFlags) != *flags) {
1825 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1826 *flags, outputFlags);
1827 *flags = (audio_output_flags_t)(*flags & outputFlags);
1828 }
Eric Laurent81784c32012-11-19 14:55:58 -08001829
Eric Laurent81784c32012-11-19 14:55:58 -08001830 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001831 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001832 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001833 // PCM data
1834 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001835 // TODO: extract as a data library function that checks that a computationally
1836 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001837 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001838 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1839 (channelMask == AUDIO_CHANNEL_OUT_MONO
1840 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001841 // hardware sample rate
1842 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001843 // normal mixer has an associated fast mixer
1844 hasFastMixer() &&
1845 // there are sufficient fast track slots available
1846 (mFastTrackAvailMask != 0)
1847 // FIXME test that MixerThread for this fast track has a capable output HAL
1848 // FIXME add a permission test also?
1849 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001850 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1851 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001852 // read the fast track multiplier property the first time it is needed
1853 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1854 if (ok != 0) {
1855 ALOGE("%s pthread_once failed: %d", __func__, ok);
1856 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001857 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001858 }
Eric Laurent4c415062016-06-17 16:14:16 -07001859
1860 // check compatibility with audio effects.
1861 { // scope for mLock
1862 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001863 for (audio_session_t session : {
1864 AUDIO_SESSION_OUTPUT_STAGE,
1865 AUDIO_SESSION_OUTPUT_MIX,
1866 sessionId,
1867 }) {
1868 sp<EffectChain> chain = getEffectChain_l(session);
1869 if (chain.get() != nullptr) {
1870 audio_output_flags_t old = *flags;
1871 chain->checkOutputFlagCompatibility(flags);
1872 if (old != *flags) {
1873 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1874 (int)session, (int)old, (int)*flags);
1875 }
Eric Laurent4c415062016-06-17 16:14:16 -07001876 }
1877 }
1878 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001879 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001880 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1881 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001882 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001883 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1884 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001885 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001886 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001887 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001888 audio_is_linear_pcm(format),
1889 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001890 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001891 }
1892 }
1893 // For normal PCM streaming tracks, update minimum frame count.
1894 // For compatibility with AudioTrack calculation, buffer depth is forced
1895 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1896 // This is probably too conservative, but legacy application code may depend on it.
1897 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001898 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001899 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001900 // this must match AudioTrack.cpp calculateMinFrameCount().
1901 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001902 uint32_t latencyMs = 0;
1903 lStatus = mOutput->stream->getLatency(&latencyMs);
1904 if (lStatus != OK) {
1905 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1906 goto Exit;
1907 }
Eric Laurent81784c32012-11-19 14:55:58 -08001908 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1909 if (minBufCount < 2) {
1910 minBufCount = 2;
1911 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001912 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1913 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001914 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001915 minBufCount * sourceFramesNeededWithTimestretch(
1916 sampleRate, mNormalFrameCount,
1917 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001918 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001919 frameCount = minFrameCount;
1920 }
Eric Laurent81784c32012-11-19 14:55:58 -08001921 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001922 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001923
Glenn Kastenc3df8382014-03-13 15:05:25 -07001924 switch (mType) {
1925
1926 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001927 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001928 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001929 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1930 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001931 sampleRate, format, channelMask, mOutput, mFormat);
1932 lStatus = BAD_VALUE;
1933 goto Exit;
1934 }
1935 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001936 break;
1937
1938 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001939 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001940 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1941 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001942 sampleRate, format, channelMask, mOutput, mFormat);
1943 lStatus = BAD_VALUE;
1944 goto Exit;
1945 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001946 break;
1947
1948 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001949 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001950 ALOGE("createTrack_l() Bad parameter: format %#x \""
1951 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001952 format, mOutput, mFormat);
1953 lStatus = BAD_VALUE;
1954 goto Exit;
1955 }
Andy Hungcd044842014-08-07 11:04:34 -07001956 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001957 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1958 lStatus = BAD_VALUE;
1959 goto Exit;
1960 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001961 break;
1962
Eric Laurent81784c32012-11-19 14:55:58 -08001963 }
1964
1965 lStatus = initCheck();
1966 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001967 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001968 goto Exit;
1969 }
1970
1971 { // scope for mLock
1972 Mutex::Autolock _l(mLock);
1973
1974 // all tracks in same audio session must share the same routing strategy otherwise
1975 // conflicts will happen when tracks are moved from one output to another by audio policy
1976 // manager
1977 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1978 for (size_t i = 0; i < mTracks.size(); ++i) {
1979 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001980 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001981 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1982 if (sessionId == t->sessionId() && strategy != actual) {
1983 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1984 strategy, actual);
1985 lStatus = BAD_VALUE;
1986 goto Exit;
1987 }
1988 }
1989 }
1990
Glenn Kastend79072e2016-01-06 08:41:20 -08001991 track = new Track(this, client, streamType, sampleRate, format,
1992 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001993 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001994
Glenn Kasten03003332013-08-06 15:40:54 -07001995 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1996 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001997 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08001998 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08001999 goto Exit;
2000 }
2001 mTracks.add(track);
2002
2003 sp<EffectChain> chain = getEffectChain_l(sessionId);
2004 if (chain != 0) {
2005 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2006 track->setMainBuffer(chain->inBuffer());
2007 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2008 chain->incTrackCnt();
2009 }
2010
Eric Laurent05067782016-06-01 18:27:28 -07002011 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002012 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2013 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2014 // so ask activity manager to do this on our behalf
2015 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2016 }
2017 }
2018
2019 lStatus = NO_ERROR;
2020
2021Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002022 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002023 return track;
2024}
2025
2026uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2027{
2028 return latency;
2029}
2030
2031uint32_t AudioFlinger::PlaybackThread::latency() const
2032{
2033 Mutex::Autolock _l(mLock);
2034 return latency_l();
2035}
2036uint32_t AudioFlinger::PlaybackThread::latency_l() const
2037{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002038 uint32_t latency;
2039 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2040 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002041 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002042 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002043}
2044
2045void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2046{
2047 Mutex::Autolock _l(mLock);
2048 // Don't apply master volume in SW if our HAL can do it for us.
2049 if (mOutput && mOutput->audioHwDev &&
2050 mOutput->audioHwDev->canSetMasterVolume()) {
2051 mMasterVolume = 1.0;
2052 } else {
2053 mMasterVolume = value;
2054 }
2055}
2056
2057void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2058{
2059 Mutex::Autolock _l(mLock);
2060 // Don't apply master mute in SW if our HAL can do it for us.
2061 if (mOutput && mOutput->audioHwDev &&
2062 mOutput->audioHwDev->canSetMasterMute()) {
2063 mMasterMute = false;
2064 } else {
2065 mMasterMute = muted;
2066 }
2067}
2068
2069void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2070{
2071 Mutex::Autolock _l(mLock);
2072 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002073 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002074}
2075
2076void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2077{
2078 Mutex::Autolock _l(mLock);
2079 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002080 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002081}
2082
2083float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2084{
2085 Mutex::Autolock _l(mLock);
2086 return mStreamTypes[stream].volume;
2087}
2088
2089// addTrack_l() must be called with ThreadBase::mLock held
2090status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2091{
2092 status_t status = ALREADY_EXISTS;
2093
Eric Laurent81784c32012-11-19 14:55:58 -08002094 if (mActiveTracks.indexOf(track) < 0) {
2095 // the track is newly added, make sure it fills up all its
2096 // buffers before playing. This is to ensure the client will
2097 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002098 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099 TrackBase::track_state state = track->mState;
2100 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002101 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002102 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002103 mLock.lock();
2104 // abort track was stopped/paused while we released the lock
2105 if (state != track->mState) {
2106 if (status == NO_ERROR) {
2107 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002108 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002109 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002110 mLock.lock();
2111 }
2112 return INVALID_OPERATION;
2113 }
2114 // abort if start is rejected by audio policy manager
2115 if (status != NO_ERROR) {
2116 return PERMISSION_DENIED;
2117 }
2118#ifdef ADD_BATTERY_DATA
2119 // to track the speaker usage
2120 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2121#endif
2122 }
2123
Eric Laurent51716182016-02-29 18:00:56 -08002124 // set retry count for buffer fill
2125 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002126 if (track->isStopping_1()) {
2127 track->mRetryCount = kMaxTrackStopRetriesOffload;
2128 } else {
2129 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2130 }
2131 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002132 } else {
2133 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002134 track->mFillingUpStatus =
2135 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002136 }
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138 track->mResetDone = false;
2139 track->mPresentationCompleteFrames = 0;
2140 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002141 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2142 if (chain != 0) {
2143 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2144 track->sessionId());
2145 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002146 }
2147
Andy Hung2148bf02016-11-28 19:01:02 -08002148 char buffer[256];
2149 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2150 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2151
Eric Laurent81784c32012-11-19 14:55:58 -08002152 status = NO_ERROR;
2153 }
2154
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002155 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002156 return status;
2157}
2158
Eric Laurentbfb1b832013-01-07 09:53:42 -08002159bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002160{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002161 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002162 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002163 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2164 track->mState = TrackBase::STOPPED;
2165 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002166 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002167 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002168 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002169 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170
2171 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002172}
2173
2174void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2175{
2176 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002177
2178 char buffer[256];
2179 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2180 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2181
Eric Laurent81784c32012-11-19 14:55:58 -08002182 mTracks.remove(track);
2183 deleteTrackName_l(track->name());
2184 // redundant as track is about to be destroyed, for dumpsys only
2185 track->mName = -1;
2186 if (track->isFastTrack()) {
2187 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002188 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002189 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2190 mFastTrackAvailMask |= 1 << index;
2191 // redundant as track is about to be destroyed, for dumpsys only
2192 track->mFastIndex = -1;
2193 }
2194 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2195 if (chain != 0) {
2196 chain->decTrackCnt();
2197 }
2198}
2199
Eric Laurentede6c3b2013-09-19 14:37:46 -07002200void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002201{
2202 // Thread could be blocked waiting for async
2203 // so signal it to handle state changes immediately
2204 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2205 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2206 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002207 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002208}
2209
Eric Laurent81784c32012-11-19 14:55:58 -08002210String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2211{
Eric Laurent81784c32012-11-19 14:55:58 -08002212 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002213 String8 out_s8;
2214 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2215 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002216 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002217 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002218}
2219
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002220void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002221 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2222 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002223
Eric Laurent73e26b62015-04-27 16:55:58 -07002224 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002225
2226 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002227 case AUDIO_OUTPUT_OPENED:
2228 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002229 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002230 desc->mChannelMask = mChannelMask;
2231 desc->mSamplingRate = mSampleRate;
2232 desc->mFormat = mFormat;
2233 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002234 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002235 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002236 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002237 break;
2238
Eric Laurent73e26b62015-04-27 16:55:58 -07002239 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002240 default:
2241 break;
2242 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002243 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002244}
2245
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002246void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002247{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002248 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249}
2250
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002251void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002252{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002253 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254}
2255
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002257{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002258 mCallbackThread->setAsyncError();
2259}
2260
Eric Laurent3b4529e2013-09-05 18:09:19 -07002261void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002262{
2263 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002264 // reject out of sequence requests
2265 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2266 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002267 mWaitWorkCV.signal();
2268 }
2269}
2270
Eric Laurent3b4529e2013-09-05 18:09:19 -07002271void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002272{
2273 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002274 // reject out of sequence requests
2275 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2276 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277 mWaitWorkCV.signal();
2278 }
2279}
2280
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002281void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002282{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002283 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002284 mSampleRate = mOutput->getSampleRate();
2285 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002286 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002287 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002288 }
Andy Hung9a592762014-07-21 21:56:01 -07002289 if ((mType == MIXER || mType == DUPLICATING)
2290 && !isValidPcmSinkChannelMask(mChannelMask)) {
2291 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2292 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002293 }
Andy Hunge5412692014-05-16 11:25:07 -07002294 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002295
2296 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002297 status_t result = mOutput->stream->getFormat(&mHALFormat);
2298 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002299 // Get format from the shim, which will be different than the HAL format
2300 // if playing compressed audio over HDMI passthrough.
2301 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002302 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002303 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002304 }
Andy Hung6146c082014-03-18 11:56:15 -07002305 if ((mType == MIXER || mType == DUPLICATING)
2306 && !isValidPcmSinkFormat(mFormat)) {
2307 LOG_FATAL("HAL format %#x not supported for mixed output",
2308 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002309 }
Phil Burk062e67a2015-02-11 13:40:50 -08002310 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002311 result = mOutput->stream->getBufferSize(&mBufferSize);
2312 LOG_ALWAYS_FATAL_IF(result != OK,
2313 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002314 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002315 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002316 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002317 mFrameCount);
2318 }
2319
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002320 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2321 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002322 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002323 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 }
2325 }
2326
Eric Laurentd1f69b02014-12-15 14:33:13 -08002327 mHwSupportsPause = false;
2328 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002329 bool supportsPause = false, supportsResume = false;
2330 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2331 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002332 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002333 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002334 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002335 } else if (supportsResume) {
2336 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002337 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002338 }
2339 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002340 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2341 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2342 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343
Andy Hungfbfc3952015-01-15 13:33:51 -08002344 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2345 // For best precision, we use float instead of the associated output
2346 // device format (typically PCM 16 bit).
2347
2348 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2349 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2350 mBufferSize = mFrameSize * mFrameCount;
2351
2352 // TODO: We currently use the associated output device channel mask and sample rate.
2353 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2354 // (if a valid mask) to avoid premature downmix.
2355 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2356 // instead of the output device sample rate to avoid loss of high frequency information.
2357 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2358 }
2359
Andy Hung09a50072014-02-27 14:30:47 -08002360 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002361 double multiplier = 1.0;
2362 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2363 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002364 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2365 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002366
Eric Laurent81784c32012-11-19 14:55:58 -08002367 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2368 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2369 maxNormalFrameCount = maxNormalFrameCount & ~15;
2370 if (maxNormalFrameCount < minNormalFrameCount) {
2371 maxNormalFrameCount = minNormalFrameCount;
2372 }
2373 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2374 if (multiplier <= 1.0) {
2375 multiplier = 1.0;
2376 } else if (multiplier <= 2.0) {
2377 if (2 * mFrameCount <= maxNormalFrameCount) {
2378 multiplier = 2.0;
2379 } else {
2380 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2381 }
2382 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002383 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002384 }
2385 }
2386 mNormalFrameCount = multiplier * mFrameCount;
2387 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002388 if (mType == MIXER || mType == DUPLICATING) {
2389 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2390 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002391 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002392 mNormalFrameCount);
2393
Andy Hung08fb1742015-05-31 23:22:10 -07002394 // Check if we want to throttle the processing to no more than 2x normal rate
2395 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002396 mThreadThrottleTimeMs = 0;
2397 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002398 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2399
Andy Hung010a1a12014-03-13 13:57:33 -07002400 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2401 // Originally this was int16_t[] array, need to remove legacy implications.
2402 free(mSinkBuffer);
2403 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002404 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2405 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2406 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002407 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002408
Andy Hung69aed5f2014-02-25 17:24:40 -08002409 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2410 // drives the output.
2411 free(mMixerBuffer);
2412 mMixerBuffer = NULL;
2413 if (mMixerBufferEnabled) {
2414 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2415 mMixerBufferSize = mNormalFrameCount * mChannelCount
2416 * audio_bytes_per_sample(mMixerBufferFormat);
2417 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2418 }
Andy Hung98ef9782014-03-04 14:46:50 -08002419 free(mEffectBuffer);
2420 mEffectBuffer = NULL;
2421 if (mEffectBufferEnabled) {
2422 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2423 mEffectBufferSize = mNormalFrameCount * mChannelCount
2424 * audio_bytes_per_sample(mEffectBufferFormat);
2425 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2426 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002427
Eric Laurent81784c32012-11-19 14:55:58 -08002428 // force reconfiguration of effect chains and engines to take new buffer size and audio
2429 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002430 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002431 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2432 // matter.
2433 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2434 Vector< sp<EffectChain> > effectChains = mEffectChains;
2435 for (size_t i = 0; i < effectChains.size(); i ++) {
2436 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2437 }
2438}
2439
2440
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002441status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002442{
2443 if (halFrames == NULL || dspFrames == NULL) {
2444 return BAD_VALUE;
2445 }
2446 Mutex::Autolock _l(mLock);
2447 if (initCheck() != NO_ERROR) {
2448 return INVALID_OPERATION;
2449 }
Andy Hung818e7a32016-02-16 18:08:07 -08002450 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002451 *halFrames = framesWritten;
2452
2453 if (isSuspended()) {
2454 // return an estimation of rendered frames when the output is suspended
2455 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002456 *dspFrames = (uint32_t)
2457 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002458 return NO_ERROR;
2459 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002460 status_t status;
2461 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002462 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002463 *dspFrames = (size_t)frames;
2464 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002465 }
2466}
2467
Eric Laurent4c415062016-06-17 16:14:16 -07002468// hasAudioSession_l() must be called with ThreadBase::mLock held
2469uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002470{
Eric Laurent81784c32012-11-19 14:55:58 -08002471 uint32_t result = 0;
2472 if (getEffectChain_l(sessionId) != 0) {
2473 result = EFFECT_SESSION;
2474 }
2475
2476 for (size_t i = 0; i < mTracks.size(); ++i) {
2477 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002478 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002479 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002480 if (track->isFastTrack()) {
2481 result |= FAST_SESSION;
2482 }
Eric Laurent81784c32012-11-19 14:55:58 -08002483 break;
2484 }
2485 }
2486
2487 return result;
2488}
2489
Glenn Kastend848eb42016-03-08 13:42:11 -08002490uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002491{
2492 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2493 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2494 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2495 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2496 }
2497 for (size_t i = 0; i < mTracks.size(); i++) {
2498 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002499 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002500 return AudioSystem::getStrategyForStream(track->streamType());
2501 }
2502 }
2503 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2504}
2505
2506
Phil Burk062e67a2015-02-11 13:40:50 -08002507AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002508{
2509 Mutex::Autolock _l(mLock);
2510 return mOutput;
2511}
2512
Phil Burk062e67a2015-02-11 13:40:50 -08002513AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002514{
2515 Mutex::Autolock _l(mLock);
2516 AudioStreamOut *output = mOutput;
2517 mOutput = NULL;
2518 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2519 // must push a NULL and wait for ack
2520 mOutputSink.clear();
2521 mPipeSink.clear();
2522 mNormalSink.clear();
2523 return output;
2524}
2525
2526// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002528{
2529 if (mOutput == NULL) {
2530 return NULL;
2531 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002532 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002533}
2534
2535uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2536{
2537 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2538}
2539
2540status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2541{
2542 if (!isValidSyncEvent(event)) {
2543 return BAD_VALUE;
2544 }
2545
2546 Mutex::Autolock _l(mLock);
2547
2548 for (size_t i = 0; i < mTracks.size(); ++i) {
2549 sp<Track> track = mTracks[i];
2550 if (event->triggerSession() == track->sessionId()) {
2551 (void) track->setSyncEvent(event);
2552 return NO_ERROR;
2553 }
2554 }
2555
2556 return NAME_NOT_FOUND;
2557}
2558
2559bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2560{
2561 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2562}
2563
2564void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2565 const Vector< sp<Track> >& tracksToRemove)
2566{
2567 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002568 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002569 for (size_t i = 0 ; i < count ; i++) {
2570 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002571 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002572 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002573 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002574#ifdef ADD_BATTERY_DATA
2575 // to track the speaker usage
2576 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2577#endif
2578 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002579 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002580 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002581 }
Eric Laurent81784c32012-11-19 14:55:58 -08002582 }
2583 }
2584 }
Eric Laurent81784c32012-11-19 14:55:58 -08002585}
2586
2587void AudioFlinger::PlaybackThread::checkSilentMode_l()
2588{
2589 if (!mMasterMute) {
2590 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002591 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2592 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2593 return;
2594 }
Eric Laurent81784c32012-11-19 14:55:58 -08002595 if (property_get("ro.audio.silent", value, "0") > 0) {
2596 char *endptr;
2597 unsigned long ul = strtoul(value, &endptr, 0);
2598 if (*endptr == '\0' && ul != 0) {
2599 ALOGD("Silence is golden");
2600 // The setprop command will not allow a property to be changed after
2601 // the first time it is set, so we don't have to worry about un-muting.
2602 setMasterMute_l(true);
2603 }
2604 }
2605 }
2606}
2607
2608// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002609ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002610{
Eric Laurent81784c32012-11-19 14:55:58 -08002611 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002612 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002613 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002614
2615 // If an NBAIO sink is present, use it to write the normal mixer's submix
2616 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002617
Andy Hung010a1a12014-03-13 13:57:33 -07002618 const size_t count = mBytesRemaining / mFrameSize;
2619
Simon Wilson2d590962012-11-29 15:18:50 -08002620 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002621 // update the setpoint when AudioFlinger::mScreenState changes
2622 uint32_t screenState = AudioFlinger::mScreenState;
2623 if (screenState != mScreenState) {
2624 mScreenState = screenState;
2625 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2626 if (pipe != NULL) {
2627 pipe->setAvgFrames((mScreenState & 1) ?
2628 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2629 }
2630 }
Andy Hung010a1a12014-03-13 13:57:33 -07002631 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002632 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002633 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002634 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002635 } else {
2636 bytesWritten = framesWritten;
2637 }
2638 // otherwise use the HAL / AudioStreamOut directly
2639 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002640 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002641
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002643 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2644 mWriteAckSequence += 2;
2645 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002647 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002649 // FIXME We should have an implementation of timestamps for direct output threads.
2650 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002651 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002652
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 if (mUseAsyncWrite &&
2654 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2655 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002656 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002658 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 }
Eric Laurent81784c32012-11-19 14:55:58 -08002660 }
2661
Eric Laurent81784c32012-11-19 14:55:58 -08002662 mNumWrites++;
2663 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002664 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002665 return bytesWritten;
2666}
2667
2668void AudioFlinger::PlaybackThread::threadLoop_drain()
2669{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002670 bool supportsDrain = false;
2671 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002672 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2673 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002674 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2675 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002677 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002679 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002680 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 }
2682}
2683
2684void AudioFlinger::PlaybackThread::threadLoop_exit()
2685{
Eric Laurent275e8e92014-11-30 15:14:47 -08002686 {
2687 Mutex::Autolock _l(mLock);
2688 for (size_t i = 0; i < mTracks.size(); i++) {
2689 sp<Track> track = mTracks[i];
2690 track->invalidate();
2691 }
Andy Hungdae27702016-10-31 14:01:16 -07002692 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2693 // After we exit there are no more track changes sent to BatteryNotifier
2694 // because that requires an active threadLoop.
2695 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2696 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002697 }
Eric Laurent81784c32012-11-19 14:55:58 -08002698}
2699
2700/*
2701The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002702 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002703 - mActiveSleepTimeUs from activeSleepTimeUs()
2704 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002705 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2706 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002707 - maxPeriod from frame count and sample rate (MIXER only)
2708
2709The parameters that affect these derived values are:
2710 - frame count
2711 - frame size
2712 - sample rate
2713 - device type: A2DP or not
2714 - device latency
2715 - format: PCM or not
2716 - active sleep time
2717 - idle sleep time
2718*/
2719
2720void AudioFlinger::PlaybackThread::cacheParameters_l()
2721{
Andy Hung25c2dac2014-02-27 14:56:00 -08002722 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002723 mActiveSleepTimeUs = activeSleepTimeUs();
2724 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002725
2726 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2727 // truncating audio when going to standby.
2728 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2729 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2730 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2731 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2732 }
2733 }
Eric Laurent81784c32012-11-19 14:55:58 -08002734}
2735
Eric Laurent13084622016-05-17 10:51:49 -07002736bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002737{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002738 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002739 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002740 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002741 size_t size = mTracks.size();
2742 for (size_t i = 0; i < size; i++) {
2743 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002744 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002745 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002746 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002747 }
2748 }
Eric Laurent13084622016-05-17 10:51:49 -07002749 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002750}
2751
Haynes Mathew George05317d22016-05-03 16:34:26 -07002752void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2753{
2754 Mutex::Autolock _l(mLock);
2755 invalidateTracks_l(streamType);
2756}
2757
Eric Laurent81784c32012-11-19 14:55:58 -08002758status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2759{
Glenn Kastend848eb42016-03-08 13:42:11 -08002760 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002761 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2762 status_t result = EffectBufferHalInterface::mirror(
2763 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2764 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2765 &halInBuffer);
2766 if (result != OK) return result;
2767 halOutBuffer = halInBuffer;
2768 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002769
2770 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002771 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002772 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002773 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002774 if (mType != DIRECT) {
2775 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002776 status_t result = EffectBufferHalInterface::allocate(
2777 numSamples * sizeof(int16_t),
2778 &halInBuffer);
2779 if (result != OK) return result;
2780 buffer = halInBuffer->audioBuffer()->s16;
2781 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2782 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002783 }
2784
2785 // Attach all tracks with same session ID to this chain.
2786 for (size_t i = 0; i < mTracks.size(); ++i) {
2787 sp<Track> track = mTracks[i];
2788 if (session == track->sessionId()) {
2789 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2790 buffer);
2791 track->setMainBuffer(buffer);
2792 chain->incTrackCnt();
2793 }
2794 }
2795
2796 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002797 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002798 if (session == track->sessionId()) {
2799 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2800 chain->incActiveTrackCnt();
2801 }
2802 }
2803 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002804 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002805 chain->setInBuffer(halInBuffer);
2806 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002807 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002808 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002809 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2810 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002811 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002812 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002813 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002814 // Effect chain for other sessions are inserted at beginning of effect
2815 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002816 // sessions is not important.
2817 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2818 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2819 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002820 size_t size = mEffectChains.size();
2821 size_t i = 0;
2822 for (i = 0; i < size; i++) {
2823 if (mEffectChains[i]->sessionId() < session) {
2824 break;
2825 }
2826 }
2827 mEffectChains.insertAt(chain, i);
2828 checkSuspendOnAddEffectChain_l(chain);
2829
2830 return NO_ERROR;
2831}
2832
2833size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2834{
Glenn Kastend848eb42016-03-08 13:42:11 -08002835 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002836
2837 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2838
2839 for (size_t i = 0; i < mEffectChains.size(); i++) {
2840 if (chain == mEffectChains[i]) {
2841 mEffectChains.removeAt(i);
2842 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002843 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002844 if (session == track->sessionId()) {
2845 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2846 chain.get(), session);
2847 chain->decActiveTrackCnt();
2848 }
2849 }
2850
2851 // detach all tracks with same session ID from this chain
2852 for (size_t i = 0; i < mTracks.size(); ++i) {
2853 sp<Track> track = mTracks[i];
2854 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002855 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002856 chain->decTrackCnt();
2857 }
2858 }
2859 break;
2860 }
2861 }
2862 return mEffectChains.size();
2863}
2864
2865status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002866 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002867{
2868 Mutex::Autolock _l(mLock);
2869 return attachAuxEffect_l(track, EffectId);
2870}
2871
2872status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002873 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002874{
2875 status_t status = NO_ERROR;
2876
2877 if (EffectId == 0) {
2878 track->setAuxBuffer(0, NULL);
2879 } else {
2880 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2881 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2882 if (effect != 0) {
2883 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2884 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2885 } else {
2886 status = INVALID_OPERATION;
2887 }
2888 } else {
2889 status = BAD_VALUE;
2890 }
2891 }
2892 return status;
2893}
2894
2895void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2896{
2897 for (size_t i = 0; i < mTracks.size(); ++i) {
2898 sp<Track> track = mTracks[i];
2899 if (track->auxEffectId() == effectId) {
2900 attachAuxEffect_l(track, 0);
2901 }
2902 }
2903}
2904
2905bool AudioFlinger::PlaybackThread::threadLoop()
2906{
2907 Vector< sp<Track> > tracksToRemove;
2908
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002909 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002910 nsecs_t lastWriteFinished = -1; // time last server write completed
2911 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002912
2913 // MIXER
2914 nsecs_t lastWarning = 0;
2915
2916 // DUPLICATING
2917 // FIXME could this be made local to while loop?
2918 writeFrames = 0;
2919
2920 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002921 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002922
2923 if (mType == MIXER) {
2924 sleepTimeShift = 0;
2925 }
2926
2927 CpuStats cpuStats;
2928 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2929
2930 acquireWakeLock();
2931
Glenn Kasten9e58b552013-01-18 15:09:48 -08002932 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2933 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2934 // and then that string will be logged at the next convenient opportunity.
2935 const char *logString = NULL;
2936
Eric Laurent664539d2013-09-23 18:24:31 -07002937 checkSilentMode_l();
2938
Eric Laurent81784c32012-11-19 14:55:58 -08002939 while (!exitPending())
2940 {
2941 cpuStats.sample(myName);
2942
2943 Vector< sp<EffectChain> > effectChains;
2944
Eric Laurent81784c32012-11-19 14:55:58 -08002945 { // scope for mLock
2946
2947 Mutex::Autolock _l(mLock);
2948
Eric Laurent021cf962014-05-13 10:18:14 -07002949 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002950
Glenn Kasten9e58b552013-01-18 15:09:48 -08002951 if (logString != NULL) {
2952 mNBLogWriter->logTimestamp();
2953 mNBLogWriter->log(logString);
2954 logString = NULL;
2955 }
2956
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002957 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002958 // and associate with the sink frames written out. We need
2959 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002960 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002961 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002962 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002963 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002964 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002965 ExtendedTimestamp timestamp; // use private copy to fetch
2966 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002967
2968 // We keep track of the last valid kernel position in case we are in underrun
2969 // and the normal mixer period is the same as the fast mixer period, or there
2970 // is some error from the HAL.
2971 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2972 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2973 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2974 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2975 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2976
2977 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2978 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2979 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2980 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002981 }
2982
2983 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2984 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002985 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002986 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002987 }
2988
Andy Hung818e7a32016-02-16 18:08:07 -08002989 // copy over kernel info
2990 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002991 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2992 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002993 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2994 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002995 }
2996 // mFramesWritten for non-offloaded tracks are contiguous
2997 // even after standby() is called. This is useful for the track frame
2998 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07002999 bool serverLocationUpdate = false;
3000 if (mFramesWritten != lastFramesWritten) {
3001 serverLocationUpdate = true;
3002 lastFramesWritten = mFramesWritten;
3003 }
3004 // Only update timestamps if there is a meaningful change.
3005 // Either the kernel timestamp must be valid or we have written something.
3006 if (kernelLocationUpdate || serverLocationUpdate) {
3007 if (serverLocationUpdate) {
3008 // use the time before we called the HAL write - it is a bit more accurate
3009 // to when the server last read data than the current time here.
3010 //
3011 // If we haven't written anything, mLastWriteTime will be -1
3012 // and we use systemTime().
3013 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3014 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3015 ? systemTime() : mLastWriteTime;
3016 }
Andy Hungdae27702016-10-31 14:01:16 -07003017
3018 for (const sp<Track> &t : mActiveTracks) {
3019 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003020 t->updateTrackFrameInfo(
3021 t->mAudioTrackServerProxy->framesReleased(),
3022 mFramesWritten,
3023 mTimestamp);
3024 }
Andy Hunge10393e2015-06-12 13:59:33 -07003025 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003026 }
3027
Eric Laurent81784c32012-11-19 14:55:58 -08003028 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003029 if (mSignalPending) {
3030 // A signal was raised while we were unlocked
3031 mSignalPending = false;
3032 } else if (waitingAsyncCallback_l()) {
3033 if (exitPending()) {
3034 break;
3035 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003036 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003037 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003038 releaseWakeLock_l();
3039 released = true;
3040 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003041 ALOGV("wait async completion");
3042 mWaitWorkCV.wait(mLock);
3043 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003044 if (released) {
3045 acquireWakeLock_l();
3046 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003047 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3048 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003049
3050 continue;
3051 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003052 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003053 isSuspended()) {
3054 // put audio hardware into standby after short delay
3055 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003056
3057 threadLoop_standby();
3058
3059 mStandby = true;
3060 }
3061
3062 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3063 // we're about to wait, flush the binder command buffer
3064 IPCThreadState::self()->flushCommands();
3065
3066 clearOutputTracks();
3067
3068 if (exitPending()) {
3069 break;
3070 }
3071
3072 releaseWakeLock_l();
3073 // wait until we have something to do...
3074 ALOGV("%s going to sleep", myName.string());
3075 mWaitWorkCV.wait(mLock);
3076 ALOGV("%s waking up", myName.string());
3077 acquireWakeLock_l();
3078
3079 mMixerStatus = MIXER_IDLE;
3080 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3081 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003082 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003083 checkSilentMode_l();
3084
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003085 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3086 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003087 if (mType == MIXER) {
3088 sleepTimeShift = 0;
3089 }
3090
3091 continue;
3092 }
3093 }
Eric Laurent81784c32012-11-19 14:55:58 -08003094 // mMixerStatusIgnoringFastTracks is also updated internally
3095 mMixerStatus = prepareTracks_l(&tracksToRemove);
3096
Andy Hungdae27702016-10-31 14:01:16 -07003097 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003098
Eric Laurent81784c32012-11-19 14:55:58 -08003099 // prevent any changes in effect chain list and in each effect chain
3100 // during mixing and effect process as the audio buffers could be deleted
3101 // or modified if an effect is created or deleted
3102 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003103 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003104
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 if (mBytesRemaining == 0) {
3106 mCurrentWriteLength = 0;
3107 if (mMixerStatus == MIXER_TRACKS_READY) {
3108 // threadLoop_mix() sets mCurrentWriteLength
3109 threadLoop_mix();
3110 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3111 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003112 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003113 // must be written to HAL
3114 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003115 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003116 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117 }
3118 }
Andy Hung98ef9782014-03-04 14:46:50 -08003119 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003120 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003121 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3122 // or mSinkBuffer (if there are no effects).
3123 //
3124 // This is done pre-effects computation; if effects change to
3125 // support higher precision, this needs to move.
3126 //
3127 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003128 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003129 if (mMixerBufferValid) {
3130 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3131 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3132
Andy Hung2ddee192015-12-18 17:34:44 -08003133 // mono blend occurs for mixer threads only (not direct or offloaded)
3134 // and is handled here if we're going directly to the sink.
3135 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003136 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3137 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003138 }
3139
Andy Hung98ef9782014-03-04 14:46:50 -08003140 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3141 mNormalFrameCount * mChannelCount);
3142 }
3143
Eric Laurentbfb1b832013-01-07 09:53:42 -08003144 mBytesRemaining = mCurrentWriteLength;
3145 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003146 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3147 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3148 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3149 mBytesWritten += mBytesRemaining;
3150 mFramesWritten += framesRemaining;
3151 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003152 mBytesRemaining = 0;
3153 }
Eric Laurent81784c32012-11-19 14:55:58 -08003154
Eric Laurentbfb1b832013-01-07 09:53:42 -08003155 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003156 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 for (size_t i = 0; i < effectChains.size(); i ++) {
3158 effectChains[i]->process_l();
3159 }
Eric Laurent81784c32012-11-19 14:55:58 -08003160 }
3161 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003162 // Process effect chains for offloaded thread even if no audio
3163 // was read from audio track: process only updates effect state
3164 // and thus does have to be synchronized with audio writes but may have
3165 // to be called while waiting for async write callback
3166 if (mType == OFFLOAD) {
3167 for (size_t i = 0; i < effectChains.size(); i ++) {
3168 effectChains[i]->process_l();
3169 }
3170 }
Eric Laurent81784c32012-11-19 14:55:58 -08003171
Andy Hung98ef9782014-03-04 14:46:50 -08003172 // Only if the Effects buffer is enabled and there is data in the
3173 // Effects buffer (buffer valid), we need to
3174 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003175 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003176 if (mEffectBufferValid) {
3177 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003178
3179 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003180 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3181 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003182 }
3183
Andy Hung98ef9782014-03-04 14:46:50 -08003184 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3185 mNormalFrameCount * mChannelCount);
3186 }
3187
Eric Laurent81784c32012-11-19 14:55:58 -08003188 // enable changes in effect chain
3189 unlockEffectChains(effectChains);
3190
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003192 // mSleepTimeUs == 0 means we must write to audio hardware
3193 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003194 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003195 // We save lastWriteFinished here, as previousLastWriteFinished,
3196 // for throttling. On thread start, previousLastWriteFinished will be
3197 // set to -1, which properly results in no throttling after the first write.
3198 nsecs_t previousLastWriteFinished = lastWriteFinished;
3199 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003200 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003201 // FIXME rewrite to reduce number of system calls
3202 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003203 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003204 lastWriteFinished = systemTime();
3205 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003206 if (ret < 0) {
3207 mBytesRemaining = 0;
3208 } else {
3209 mBytesWritten += ret;
3210 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003211 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003212 }
3213 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3214 (mMixerStatus == MIXER_DRAIN_ALL)) {
3215 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003216 }
Andy Hung08fb1742015-05-31 23:22:10 -07003217 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003218 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003219 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003220 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003221 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003222 ATRACE_NAME("underrun");
3223 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003224 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003225 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003226 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003227 }
Andy Hung08fb1742015-05-31 23:22:10 -07003228
3229 if (mThreadThrottle
3230 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3231 && ret > 0) { // we wrote something
3232 // Limit MixerThread data processing to no more than twice the
3233 // expected processing rate.
3234 //
3235 // This helps prevent underruns with NuPlayer and other applications
3236 // which may set up buffers that are close to the minimum size, or use
3237 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3238 //
3239 // The throttle smooths out sudden large data drains from the device,
3240 // e.g. when it comes out of standby, which often causes problems with
3241 // (1) mixer threads without a fast mixer (which has its own warm-up)
3242 // (2) minimum buffer sized tracks (even if the track is full,
3243 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003244 //
3245 // Total time spent in last processing cycle equals time spent in
3246 // 1. threadLoop_write, as well as time spent in
3247 // 2. threadLoop_mix (significant for heavy mixing, especially
3248 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003249
Andy Hung69488c42016-05-16 18:43:33 -07003250 // it's OK if deltaMs is an overestimate.
3251 const int32_t deltaMs =
3252 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003253 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3254 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3255 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003256 // notify of throttle start on verbose log
3257 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3258 "mixer(%p) throttle begin:"
3259 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003260 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003261 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003262 // Throttle must be attributed to the previous mixer loop's write time
3263 // to allow back-to-back throttling.
3264 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003265 } else {
3266 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3267 if (diff > 0) {
3268 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003269 // but prevent spamming for bluetooth
3270 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3271 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003272 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3273 }
Andy Hung08fb1742015-05-31 23:22:10 -07003274 }
3275 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003276 }
Eric Laurent81784c32012-11-19 14:55:58 -08003277
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003279 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003280 Mutex::Autolock _l(mLock);
3281 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3282 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003283 }
Glenn Kastene7754022014-10-31 12:11:26 -07003284 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003285 }
Eric Laurent81784c32012-11-19 14:55:58 -08003286 }
3287
3288 // Finally let go of removed track(s), without the lock held
3289 // since we can't guarantee the destructors won't acquire that
3290 // same lock. This will also mutate and push a new fast mixer state.
3291 threadLoop_removeTracks(tracksToRemove);
3292 tracksToRemove.clear();
3293
3294 // FIXME I don't understand the need for this here;
3295 // it was in the original code but maybe the
3296 // assignment in saveOutputTracks() makes this unnecessary?
3297 clearOutputTracks();
3298
3299 // Effect chains will be actually deleted here if they were removed from
3300 // mEffectChains list during mixing or effects processing
3301 effectChains.clear();
3302
3303 // FIXME Note that the above .clear() is no longer necessary since effectChains
3304 // is now local to this block, but will keep it for now (at least until merge done).
3305 }
3306
Eric Laurentbfb1b832013-01-07 09:53:42 -08003307 threadLoop_exit();
3308
Eric Laurentcf817a22014-08-04 20:36:31 -07003309 if (!mStandby) {
3310 threadLoop_standby();
3311 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003312 }
3313
3314 releaseWakeLock();
3315
3316 ALOGV("Thread %p type %d exiting", this, mType);
3317 return false;
3318}
3319
Eric Laurentbfb1b832013-01-07 09:53:42 -08003320// removeTracks_l() must be called with ThreadBase::mLock held
3321void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3322{
3323 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003324 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003325 for (size_t i=0 ; i<count ; i++) {
3326 const sp<Track>& track = tracksToRemove.itemAt(i);
3327 mActiveTracks.remove(track);
3328 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3329 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3330 if (chain != 0) {
3331 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3332 track->sessionId());
3333 chain->decActiveTrackCnt();
3334 }
3335 if (track->isTerminated()) {
3336 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003337 } else { // inactive but not terminated
3338 char buffer[256];
3339 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3340 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003341 }
3342 }
3343 }
3344
3345}
Eric Laurent81784c32012-11-19 14:55:58 -08003346
Eric Laurentaccc1472013-09-20 09:36:34 -07003347status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3348{
3349 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003350 ExtendedTimestamp ets;
3351 status_t status = mNormalSink->getTimestamp(ets);
3352 if (status == NO_ERROR) {
3353 status = ets.getBestTimestamp(&timestamp);
3354 }
3355 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003356 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003357 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003358 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003359 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003360 timestamp.mPosition = (uint32_t)position64;
3361 return NO_ERROR;
3362 }
3363 }
3364 return INVALID_OPERATION;
3365}
Eric Laurent1c333e22014-05-20 10:48:17 -07003366
Eric Laurent054d9d32015-04-24 08:48:48 -07003367status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3368 audio_patch_handle_t *handle)
3369{
Andy Hungf60abce2016-08-26 11:37:54 -07003370 status_t status;
3371 if (property_get_bool("af.patch_park", false /* default_value */)) {
3372 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3373 // or if HAL does not properly lock against access.
3374 AutoPark<FastMixer> park(mFastMixer);
3375 status = PlaybackThread::createAudioPatch_l(patch, handle);
3376 } else {
3377 status = PlaybackThread::createAudioPatch_l(patch, handle);
3378 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003379 return status;
3380}
3381
Eric Laurent1c333e22014-05-20 10:48:17 -07003382status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3383 audio_patch_handle_t *handle)
3384{
3385 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003386
3387 // store new device and send to effects
3388 audio_devices_t type = AUDIO_DEVICE_NONE;
3389 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3390 type |= patch->sinks[i].ext.device.type;
3391 }
3392
3393#ifdef ADD_BATTERY_DATA
3394 // when changing the audio output device, call addBatteryData to notify
3395 // the change
3396 if (mOutDevice != type) {
3397 uint32_t params = 0;
3398 // check whether speaker is on
3399 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3400 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003401 }
3402
Eric Laurent054d9d32015-04-24 08:48:48 -07003403 audio_devices_t deviceWithoutSpeaker
3404 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3405 // check if any other device (except speaker) is on
3406 if (type & deviceWithoutSpeaker) {
3407 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3408 }
3409
3410 if (params != 0) {
3411 addBatteryData(params);
3412 }
3413 }
3414#endif
3415
3416 for (size_t i = 0; i < mEffectChains.size(); i++) {
3417 mEffectChains[i]->setDevice_l(type);
3418 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003419
3420 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3421 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3422 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003423 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003424 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003425
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003426 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003427 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3428 status = hwDevice->createAudioPatch(patch->num_sources,
3429 patch->sources,
3430 patch->num_sinks,
3431 patch->sinks,
3432 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003433 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003434 char *address;
3435 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3436 //FIXME: we only support address on first sink with HAL version < 3.0
3437 address = audio_device_address_to_parameter(
3438 patch->sinks[0].ext.device.type,
3439 patch->sinks[0].ext.device.address);
3440 } else {
3441 address = (char *)calloc(1, 1);
3442 }
3443 AudioParameter param = AudioParameter(String8(address));
3444 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003445 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003446 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003447 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003448 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003449 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003450 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003451 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3452 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003453 return status;
3454}
3455
Eric Laurent054d9d32015-04-24 08:48:48 -07003456status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3457{
Andy Hungf60abce2016-08-26 11:37:54 -07003458 status_t status;
3459 if (property_get_bool("af.patch_park", false /* default_value */)) {
3460 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3461 // or if HAL does not properly lock against access.
3462 AutoPark<FastMixer> park(mFastMixer);
3463 status = PlaybackThread::releaseAudioPatch_l(handle);
3464 } else {
3465 status = PlaybackThread::releaseAudioPatch_l(handle);
3466 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003467 return status;
3468}
3469
Eric Laurent1c333e22014-05-20 10:48:17 -07003470status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3471{
3472 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003473
3474 mOutDevice = AUDIO_DEVICE_NONE;
3475
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003476 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003477 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3478 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003479 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003480 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003481 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003482 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 }
3484 return status;
3485}
3486
Eric Laurent83b88082014-06-20 18:31:16 -07003487void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3488{
3489 Mutex::Autolock _l(mLock);
3490 mTracks.add(track);
3491}
3492
3493void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3494{
3495 Mutex::Autolock _l(mLock);
3496 destroyTrack_l(track);
3497}
3498
3499void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3500{
3501 ThreadBase::getAudioPortConfig(config);
3502 config->role = AUDIO_PORT_ROLE_SOURCE;
3503 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3504 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3505}
3506
Eric Laurent81784c32012-11-19 14:55:58 -08003507// ----------------------------------------------------------------------------
3508
3509AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003510 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3511 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003512 // mAudioMixer below
3513 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003514 mFastMixerFutex(0),
3515 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003516 // mOutputSink below
3517 // mPipeSink below
3518 // mNormalSink below
3519{
3520 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003521 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3522 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003523 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3524 mNormalFrameCount);
3525 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3526
Andy Hungfbfc3952015-01-15 13:33:51 -08003527 if (type == DUPLICATING) {
3528 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3529 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3530 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3531 return;
3532 }
Eric Laurent81784c32012-11-19 14:55:58 -08003533 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003534 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003535 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003536 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003537#if !LOG_NDEBUG
3538 ssize_t index =
3539#else
3540 (void)
3541#endif
3542 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003543 ALOG_ASSERT(index == 0);
3544
3545 // initialize fast mixer depending on configuration
3546 bool initFastMixer;
3547 switch (kUseFastMixer) {
3548 case FastMixer_Never:
3549 initFastMixer = false;
3550 break;
3551 case FastMixer_Always:
3552 initFastMixer = true;
3553 break;
3554 case FastMixer_Static:
3555 case FastMixer_Dynamic:
3556 initFastMixer = mFrameCount < mNormalFrameCount;
3557 break;
3558 }
3559 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003560 audio_format_t fastMixerFormat;
3561 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3562 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3563 } else {
3564 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3565 }
3566 if (mFormat != fastMixerFormat) {
3567 // change our Sink format to accept our intermediate precision
3568 mFormat = fastMixerFormat;
3569 free(mSinkBuffer);
3570 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3571 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3572 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3573 }
Eric Laurent81784c32012-11-19 14:55:58 -08003574
3575 // create a MonoPipe to connect our submix to FastMixer
3576 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003577#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003578 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003579#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003580 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003581 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003582 format.mFormat = fastMixerFormat;
3583 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3584
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3586 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3587 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3588 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3589 const NBAIO_Format offers[1] = {format};
3590 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003591#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003592 ssize_t index =
3593#else
3594 (void)
3595#endif
3596 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003597 ALOG_ASSERT(index == 0);
3598 monoPipe->setAvgFrames((mScreenState & 1) ?
3599 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3600 mPipeSink = monoPipe;
3601
Glenn Kasten46909e72013-02-26 09:20:22 -08003602#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003603 if (mTeeSinkOutputEnabled) {
3604 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003605 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3606 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003607 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003608 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003609 ALOG_ASSERT(index == 0);
3610 mTeeSink = teeSink;
3611 PipeReader *teeSource = new PipeReader(*teeSink);
3612 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003613 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003614 ALOG_ASSERT(index == 0);
3615 mTeeSource = teeSource;
3616 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003617#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003618
3619 // create fast mixer and configure it initially with just one fast track for our submix
3620 mFastMixer = new FastMixer();
3621 FastMixerStateQueue *sq = mFastMixer->sq();
3622#ifdef STATE_QUEUE_DUMP
3623 sq->setObserverDump(&mStateQueueObserverDump);
3624 sq->setMutatorDump(&mStateQueueMutatorDump);
3625#endif
3626 FastMixerState *state = sq->begin();
3627 FastTrack *fastTrack = &state->mFastTracks[0];
3628 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3629 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3630 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003631 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3632 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003633 fastTrack->mGeneration++;
3634 state->mFastTracksGen++;
3635 state->mTrackMask = 1;
3636 // fast mixer will use the HAL output sink
3637 state->mOutputSink = mOutputSink.get();
3638 state->mOutputSinkGen++;
3639 state->mFrameCount = mFrameCount;
3640 state->mCommand = FastMixerState::COLD_IDLE;
3641 // already done in constructor initialization list
3642 //mFastMixerFutex = 0;
3643 state->mColdFutexAddr = &mFastMixerFutex;
3644 state->mColdGen++;
3645 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003646#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003647 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003648#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003649 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3650 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003651 sq->end();
3652 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3653
3654 // start the fast mixer
3655 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3656 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003657 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003658 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003659
3660#ifdef AUDIO_WATCHDOG
3661 // create and start the watchdog
3662 mAudioWatchdog = new AudioWatchdog();
3663 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3664 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3665 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003666 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003667#endif
3668
Eric Laurent81784c32012-11-19 14:55:58 -08003669 }
3670
3671 switch (kUseFastMixer) {
3672 case FastMixer_Never:
3673 case FastMixer_Dynamic:
3674 mNormalSink = mOutputSink;
3675 break;
3676 case FastMixer_Always:
3677 mNormalSink = mPipeSink;
3678 break;
3679 case FastMixer_Static:
3680 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3681 break;
3682 }
3683}
3684
3685AudioFlinger::MixerThread::~MixerThread()
3686{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003687 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003688 FastMixerStateQueue *sq = mFastMixer->sq();
3689 FastMixerState *state = sq->begin();
3690 if (state->mCommand == FastMixerState::COLD_IDLE) {
3691 int32_t old = android_atomic_inc(&mFastMixerFutex);
3692 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003693 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003694 }
3695 }
3696 state->mCommand = FastMixerState::EXIT;
3697 sq->end();
3698 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3699 mFastMixer->join();
3700 // Though the fast mixer thread has exited, it's state queue is still valid.
3701 // We'll use that extract the final state which contains one remaining fast track
3702 // corresponding to our sub-mix.
3703 state = sq->begin();
3704 ALOG_ASSERT(state->mTrackMask == 1);
3705 FastTrack *fastTrack = &state->mFastTracks[0];
3706 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3707 delete fastTrack->mBufferProvider;
3708 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003709 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003710#ifdef AUDIO_WATCHDOG
3711 if (mAudioWatchdog != 0) {
3712 mAudioWatchdog->requestExit();
3713 mAudioWatchdog->requestExitAndWait();
3714 mAudioWatchdog.clear();
3715 }
3716#endif
3717 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003718 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003719 delete mAudioMixer;
3720}
3721
3722
3723uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3724{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003725 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003726 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3727 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3728 }
3729 return latency;
3730}
3731
3732
3733void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3734{
3735 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3736}
3737
Eric Laurentbfb1b832013-01-07 09:53:42 -08003738ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003739{
3740 // FIXME we should only do one push per cycle; confirm this is true
3741 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003742 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003743 FastMixerStateQueue *sq = mFastMixer->sq();
3744 FastMixerState *state = sq->begin();
3745 if (state->mCommand != FastMixerState::MIX_WRITE &&
3746 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3747 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003748
3749 // FIXME workaround for first HAL write being CPU bound on some devices
3750 ATRACE_BEGIN("write");
3751 mOutput->write((char *)mSinkBuffer, 0);
3752 ATRACE_END();
3753
Eric Laurent81784c32012-11-19 14:55:58 -08003754 int32_t old = android_atomic_inc(&mFastMixerFutex);
3755 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003756 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003757 }
3758#ifdef AUDIO_WATCHDOG
3759 if (mAudioWatchdog != 0) {
3760 mAudioWatchdog->resume();
3761 }
3762#endif
3763 }
3764 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003765#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003766 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003767 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003768#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003769 sq->end();
3770 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3771 if (kUseFastMixer == FastMixer_Dynamic) {
3772 mNormalSink = mPipeSink;
3773 }
3774 } else {
3775 sq->end(false /*didModify*/);
3776 }
3777 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003778 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003779}
3780
3781void AudioFlinger::MixerThread::threadLoop_standby()
3782{
3783 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003784 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003785 FastMixerStateQueue *sq = mFastMixer->sq();
3786 FastMixerState *state = sq->begin();
3787 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003788 // Report any frames trapped in the Monopipe
3789 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3790 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3791 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3792 "monoPipeWritten:%lld monoPipeLeft:%lld",
3793 (long long)mFramesWritten, (long long)mSuspendedFrames,
3794 (long long)mPipeSink->framesWritten(), pipeFrames);
3795 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3796
Eric Laurent81784c32012-11-19 14:55:58 -08003797 state->mCommand = FastMixerState::COLD_IDLE;
3798 state->mColdFutexAddr = &mFastMixerFutex;
3799 state->mColdGen++;
3800 mFastMixerFutex = 0;
3801 sq->end();
3802 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3803 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3804 if (kUseFastMixer == FastMixer_Dynamic) {
3805 mNormalSink = mOutputSink;
3806 }
3807#ifdef AUDIO_WATCHDOG
3808 if (mAudioWatchdog != 0) {
3809 mAudioWatchdog->pause();
3810 }
3811#endif
3812 } else {
3813 sq->end(false /*didModify*/);
3814 }
3815 }
3816 PlaybackThread::threadLoop_standby();
3817}
3818
Eric Laurentbfb1b832013-01-07 09:53:42 -08003819bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3820{
3821 return false;
3822}
3823
3824bool AudioFlinger::PlaybackThread::shouldStandby_l()
3825{
3826 return !mStandby;
3827}
3828
3829bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3830{
3831 Mutex::Autolock _l(mLock);
3832 return waitingAsyncCallback_l();
3833}
3834
Eric Laurent81784c32012-11-19 14:55:58 -08003835// shared by MIXER and DIRECT, overridden by DUPLICATING
3836void AudioFlinger::PlaybackThread::threadLoop_standby()
3837{
3838 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003839 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003840 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003841 // discard any pending drain or write ack by incrementing sequence
3842 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3843 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003844 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003845 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3846 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003847 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003848 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003849}
3850
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003851void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3852{
3853 ALOGV("signal playback thread");
3854 broadcast_l();
3855}
3856
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003857void AudioFlinger::PlaybackThread::onAsyncError()
3858{
3859 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3860 invalidateTracks((audio_stream_type_t)i);
3861 }
3862}
3863
Eric Laurent81784c32012-11-19 14:55:58 -08003864void AudioFlinger::MixerThread::threadLoop_mix()
3865{
Eric Laurent81784c32012-11-19 14:55:58 -08003866 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003867 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003868 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003869 // increase sleep time progressively when application underrun condition clears.
3870 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3871 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3872 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003873 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003874 sleepTimeShift--;
3875 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003876 mSleepTimeUs = 0;
3877 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003878 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003879
Eric Laurent81784c32012-11-19 14:55:58 -08003880}
3881
3882void AudioFlinger::MixerThread::threadLoop_sleepTime()
3883{
3884 // If no tracks are ready, sleep once for the duration of an output
3885 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003886 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003887 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003888 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3889 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3890 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003891 }
3892 // reduce sleep time in case of consecutive application underruns to avoid
3893 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3894 // duration we would end up writing less data than needed by the audio HAL if
3895 // the condition persists.
3896 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3897 sleepTimeShift++;
3898 }
3899 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003900 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003901 }
3902 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003903 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3904 // before effects processing or output.
3905 if (mMixerBufferValid) {
3906 memset(mMixerBuffer, 0, mMixerBufferSize);
3907 } else {
3908 memset(mSinkBuffer, 0, mSinkBufferSize);
3909 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003910 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003911 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3912 "anticipated start");
3913 }
3914 // TODO add standby time extension fct of effect tail
3915}
3916
3917// prepareTracks_l() must be called with ThreadBase::mLock held
3918AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3919 Vector< sp<Track> > *tracksToRemove)
3920{
3921
3922 mixer_state mixerStatus = MIXER_IDLE;
3923 // find out which tracks need to be processed
3924 size_t count = mActiveTracks.size();
3925 size_t mixedTracks = 0;
3926 size_t tracksWithEffect = 0;
3927 // counts only _active_ fast tracks
3928 size_t fastTracks = 0;
3929 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3930
3931 float masterVolume = mMasterVolume;
3932 bool masterMute = mMasterMute;
3933
3934 if (masterMute) {
3935 masterVolume = 0;
3936 }
3937 // Delegate master volume control to effect in output mix effect chain if needed
3938 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3939 if (chain != 0) {
3940 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3941 chain->setVolume_l(&v, &v);
3942 masterVolume = (float)((v + (1 << 23)) >> 24);
3943 chain.clear();
3944 }
3945
3946 // prepare a new state to push
3947 FastMixerStateQueue *sq = NULL;
3948 FastMixerState *state = NULL;
3949 bool didModify = false;
3950 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003951 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003952 sq = mFastMixer->sq();
3953 state = sq->begin();
3954 }
3955
Andy Hung69aed5f2014-02-25 17:24:40 -08003956 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003957 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003958
Eric Laurent81784c32012-11-19 14:55:58 -08003959 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003960 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003961
3962 // this const just means the local variable doesn't change
3963 Track* const track = t.get();
3964
3965 // process fast tracks
3966 if (track->isFastTrack()) {
3967
3968 // It's theoretically possible (though unlikely) for a fast track to be created
3969 // and then removed within the same normal mix cycle. This is not a problem, as
3970 // the track never becomes active so it's fast mixer slot is never touched.
3971 // The converse, of removing an (active) track and then creating a new track
3972 // at the identical fast mixer slot within the same normal mix cycle,
3973 // is impossible because the slot isn't marked available until the end of each cycle.
3974 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003975 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003976 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3977 FastTrack *fastTrack = &state->mFastTracks[j];
3978
3979 // Determine whether the track is currently in underrun condition,
3980 // and whether it had a recent underrun.
3981 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3982 FastTrackUnderruns underruns = ftDump->mUnderruns;
3983 uint32_t recentFull = (underruns.mBitFields.mFull -
3984 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3985 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3986 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3987 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3988 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3989 uint32_t recentUnderruns = recentPartial + recentEmpty;
3990 track->mObservedUnderruns = underruns;
3991 // don't count underruns that occur while stopping or pausing
3992 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003993 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3994 recentUnderruns > 0) {
3995 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3996 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003997 } else {
3998 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08003999 }
4000
4001 // This is similar to the state machine for normal tracks,
4002 // with a few modifications for fast tracks.
4003 bool isActive = true;
4004 switch (track->mState) {
4005 case TrackBase::STOPPING_1:
4006 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004007 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004008 track->mState = TrackBase::STOPPING_2;
4009 }
4010 break;
4011 case TrackBase::PAUSING:
4012 // ramp down is not yet implemented
4013 track->setPaused();
4014 break;
4015 case TrackBase::RESUMING:
4016 // ramp up is not yet implemented
4017 track->mState = TrackBase::ACTIVE;
4018 break;
4019 case TrackBase::ACTIVE:
4020 if (recentFull > 0 || recentPartial > 0) {
4021 // track has provided at least some frames recently: reset retry count
4022 track->mRetryCount = kMaxTrackRetries;
4023 }
4024 if (recentUnderruns == 0) {
4025 // no recent underruns: stay active
4026 break;
4027 }
4028 // there has recently been an underrun of some kind
4029 if (track->sharedBuffer() == 0) {
4030 // were any of the recent underruns "empty" (no frames available)?
4031 if (recentEmpty == 0) {
4032 // no, then ignore the partial underruns as they are allowed indefinitely
4033 break;
4034 }
4035 // there has recently been an "empty" underrun: decrement the retry counter
4036 if (--(track->mRetryCount) > 0) {
4037 break;
4038 }
4039 // indicate to client process that the track was disabled because of underrun;
4040 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004041 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004042 // remove from active list, but state remains ACTIVE [confusing but true]
4043 isActive = false;
4044 break;
4045 }
4046 // fall through
4047 case TrackBase::STOPPING_2:
4048 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004049 case TrackBase::STOPPED:
4050 case TrackBase::FLUSHED: // flush() while active
4051 // Check for presentation complete if track is inactive
4052 // We have consumed all the buffers of this track.
4053 // This would be incomplete if we auto-paused on underrun
4054 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004055 uint32_t latency = 0;
4056 status_t result = mOutput->stream->getLatency(&latency);
4057 ALOGE_IF(result != OK,
4058 "Error when retrieving output stream latency: %d", result);
4059 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004060 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004061 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4062 // track stays in active list until presentation is complete
4063 break;
4064 }
4065 }
4066 if (track->isStopping_2()) {
4067 track->mState = TrackBase::STOPPED;
4068 }
4069 if (track->isStopped()) {
4070 // Can't reset directly, as fast mixer is still polling this track
4071 // track->reset();
4072 // So instead mark this track as needing to be reset after push with ack
4073 resetMask |= 1 << i;
4074 }
4075 isActive = false;
4076 break;
4077 case TrackBase::IDLE:
4078 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004079 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004080 }
4081
4082 if (isActive) {
4083 // was it previously inactive?
4084 if (!(state->mTrackMask & (1 << j))) {
4085 ExtendedAudioBufferProvider *eabp = track;
4086 VolumeProvider *vp = track;
4087 fastTrack->mBufferProvider = eabp;
4088 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004089 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004090 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004091 fastTrack->mGeneration++;
4092 state->mTrackMask |= 1 << j;
4093 didModify = true;
4094 // no acknowledgement required for newly active tracks
4095 }
4096 // cache the combined master volume and stream type volume for fast mixer; this
4097 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004098 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004099 ++fastTracks;
4100 } else {
4101 // was it previously active?
4102 if (state->mTrackMask & (1 << j)) {
4103 fastTrack->mBufferProvider = NULL;
4104 fastTrack->mGeneration++;
4105 state->mTrackMask &= ~(1 << j);
4106 didModify = true;
4107 // If any fast tracks were removed, we must wait for acknowledgement
4108 // because we're about to decrement the last sp<> on those tracks.
4109 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4110 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004111 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4112 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4113 j, track->mState, state->mTrackMask, recentUnderruns,
4114 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004115 }
4116 tracksToRemove->add(track);
4117 // Avoids a misleading display in dumpsys
4118 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4119 }
4120 continue;
4121 }
4122
4123 { // local variable scope to avoid goto warning
4124
4125 audio_track_cblk_t* cblk = track->cblk();
4126
4127 // The first time a track is added we wait
4128 // for all its buffers to be filled before processing it
4129 int name = track->name();
4130 // make sure that we have enough frames to mix one full buffer.
4131 // enforce this condition only once to enable draining the buffer in case the client
4132 // app does not call stop() and relies on underrun to stop:
4133 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4134 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004135 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004136 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004137 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004138
4139 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004140 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004141 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4142 // add frames already consumed but not yet released by the resampler
4143 // because mAudioTrackServerProxy->framesReady() will include these frames
4144 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4145
Eric Laurent81784c32012-11-19 14:55:58 -08004146 uint32_t minFrames = 1;
4147 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4148 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004149 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004150 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004151
4152 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004153 if (ATRACE_ENABLED()) {
4154 // I wish we had formatted trace names
4155 char traceName[16];
4156 strcpy(traceName, "nRdy");
4157 int name = track->name();
4158 if (AudioMixer::TRACK0 <= name &&
4159 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4160 name -= AudioMixer::TRACK0;
4161 traceName[4] = (name / 10) + '0';
4162 traceName[5] = (name % 10) + '0';
4163 } else {
4164 traceName[4] = '?';
4165 traceName[5] = '?';
4166 }
4167 traceName[6] = '\0';
4168 ATRACE_INT(traceName, framesReady);
4169 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004170 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004171 !track->isPaused() && !track->isTerminated())
4172 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004173 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004174
4175 mixedTracks++;
4176
Andy Hung69aed5f2014-02-25 17:24:40 -08004177 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4178 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004179 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004180 if (track->mainBuffer() != mSinkBuffer &&
4181 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004182 if (mEffectBufferEnabled) {
4183 mEffectBufferValid = true; // Later can set directly.
4184 }
Eric Laurent81784c32012-11-19 14:55:58 -08004185 chain = getEffectChain_l(track->sessionId());
4186 // Delegate volume control to effect in track effect chain if needed
4187 if (chain != 0) {
4188 tracksWithEffect++;
4189 } else {
4190 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4191 "session %d",
4192 name, track->sessionId());
4193 }
4194 }
4195
4196
4197 int param = AudioMixer::VOLUME;
4198 if (track->mFillingUpStatus == Track::FS_FILLED) {
4199 // no ramp for the first volume setting
4200 track->mFillingUpStatus = Track::FS_ACTIVE;
4201 if (track->mState == TrackBase::RESUMING) {
4202 track->mState = TrackBase::ACTIVE;
4203 param = AudioMixer::RAMP_VOLUME;
4204 }
4205 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004206 // FIXME should not make a decision based on mServer
4207 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004208 // If the track is stopped before the first frame was mixed,
4209 // do not apply ramp
4210 param = AudioMixer::RAMP_VOLUME;
4211 }
4212
4213 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004214 uint32_t vl, vr; // in U8.24 integer format
4215 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004216 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004217 vl = vr = 0;
4218 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004219 if (track->isPausing()) {
4220 track->setPaused();
4221 }
4222 } else {
4223
4224 // read original volumes with volume control
4225 float typeVolume = mStreamTypes[track->streamType()].volume;
4226 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004227 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004228 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004229 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4230 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004231 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004232 if (vlf > GAIN_FLOAT_UNITY) {
4233 ALOGV("Track left volume out of range: %.3g", vlf);
4234 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004235 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004236 if (vrf > GAIN_FLOAT_UNITY) {
4237 ALOGV("Track right volume out of range: %.3g", vrf);
4238 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004239 }
4240 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004241 vlf *= v;
4242 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004243 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004244 // then derive vl and vr as U8.24 versions for the effect chain
4245 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4246 vl = (uint32_t) (scaleto8_24 * vlf);
4247 vr = (uint32_t) (scaleto8_24 * vrf);
4248 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004249 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004250 // send level comes from shared memory and so may be corrupt
4251 if (sendLevel > MAX_GAIN_INT) {
4252 ALOGV("Track send level out of range: %04X", sendLevel);
4253 sendLevel = MAX_GAIN_INT;
4254 }
Andy Hung6be49402014-05-30 10:42:03 -07004255 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4256 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004257 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004258
Eric Laurent81784c32012-11-19 14:55:58 -08004259 // Delegate volume control to effect in track effect chain if needed
4260 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4261 // Do not ramp volume if volume is controlled by effect
4262 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004263 // Update remaining floating point volume levels
4264 vlf = (float)vl / (1 << 24);
4265 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004266 track->mHasVolumeController = true;
4267 } else {
4268 // force no volume ramp when volume controller was just disabled or removed
4269 // from effect chain to avoid volume spike
4270 if (track->mHasVolumeController) {
4271 param = AudioMixer::VOLUME;
4272 }
4273 track->mHasVolumeController = false;
4274 }
4275
Eric Laurent81784c32012-11-19 14:55:58 -08004276 // XXX: these things DON'T need to be done each time
4277 mAudioMixer->setBufferProvider(name, track);
4278 mAudioMixer->enable(name);
4279
Andy Hung6be49402014-05-30 10:42:03 -07004280 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4281 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4282 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004283 mAudioMixer->setParameter(
4284 name,
4285 AudioMixer::TRACK,
4286 AudioMixer::FORMAT, (void *)track->format());
4287 mAudioMixer->setParameter(
4288 name,
4289 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004290 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004291 mAudioMixer->setParameter(
4292 name,
4293 AudioMixer::TRACK,
4294 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004295 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004296 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004297 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004298 if (reqSampleRate == 0) {
4299 reqSampleRate = mSampleRate;
4300 } else if (reqSampleRate > maxSampleRate) {
4301 reqSampleRate = maxSampleRate;
4302 }
Eric Laurent81784c32012-11-19 14:55:58 -08004303 mAudioMixer->setParameter(
4304 name,
4305 AudioMixer::RESAMPLE,
4306 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004307 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004308
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004309 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004310 mAudioMixer->setParameter(
4311 name,
4312 AudioMixer::TIMESTRETCH,
4313 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004314 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004315
Andy Hung69aed5f2014-02-25 17:24:40 -08004316 /*
4317 * Select the appropriate output buffer for the track.
4318 *
Andy Hung98ef9782014-03-04 14:46:50 -08004319 * Tracks with effects go into their own effects chain buffer
4320 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004321 *
4322 * Other tracks can use mMixerBuffer for higher precision
4323 * channel accumulation. If this buffer is enabled
4324 * (mMixerBufferEnabled true), then selected tracks will accumulate
4325 * into it.
4326 *
4327 */
4328 if (mMixerBufferEnabled
4329 && (track->mainBuffer() == mSinkBuffer
4330 || track->mainBuffer() == mMixerBuffer)) {
4331 mAudioMixer->setParameter(
4332 name,
4333 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004334 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004335 mAudioMixer->setParameter(
4336 name,
4337 AudioMixer::TRACK,
4338 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4339 // TODO: override track->mainBuffer()?
4340 mMixerBufferValid = true;
4341 } else {
4342 mAudioMixer->setParameter(
4343 name,
4344 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004345 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004346 mAudioMixer->setParameter(
4347 name,
4348 AudioMixer::TRACK,
4349 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4350 }
Eric Laurent81784c32012-11-19 14:55:58 -08004351 mAudioMixer->setParameter(
4352 name,
4353 AudioMixer::TRACK,
4354 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4355
4356 // reset retry count
4357 track->mRetryCount = kMaxTrackRetries;
4358
4359 // If one track is ready, set the mixer ready if:
4360 // - the mixer was not ready during previous round OR
4361 // - no other track is not ready
4362 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4363 mixerStatus != MIXER_TRACKS_ENABLED) {
4364 mixerStatus = MIXER_TRACKS_READY;
4365 }
4366 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004367 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004368 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4369 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004370 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004371 } else {
4372 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004373 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004374
Eric Laurent81784c32012-11-19 14:55:58 -08004375 // clear effect chain input buffer if an active track underruns to avoid sending
4376 // previous audio buffer again to effects
4377 chain = getEffectChain_l(track->sessionId());
4378 if (chain != 0) {
4379 chain->clearInputBuffer();
4380 }
4381
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004382 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004383 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4384 track->isStopped() || track->isPaused()) {
4385 // We have consumed all the buffers of this track.
4386 // Remove it from the list of active tracks.
4387 // TODO: use actual buffer filling status instead of latency when available from
4388 // audio HAL
4389 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004390 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004391 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4392 if (track->isStopped()) {
4393 track->reset();
4394 }
4395 tracksToRemove->add(track);
4396 }
4397 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004398 // No buffers for this track. Give it a few chances to
4399 // fill a buffer, then remove it from active list.
4400 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004401 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004402 tracksToRemove->add(track);
4403 // indicate to client process that the track was disabled because of underrun;
4404 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004405 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004406 // If one track is not ready, mark the mixer also not ready if:
4407 // - the mixer was ready during previous round OR
4408 // - no other track is ready
4409 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4410 mixerStatus != MIXER_TRACKS_READY) {
4411 mixerStatus = MIXER_TRACKS_ENABLED;
4412 }
4413 }
4414 mAudioMixer->disable(name);
4415 }
4416
4417 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004418
4419 }
4420
4421 // Push the new FastMixer state if necessary
4422 bool pauseAudioWatchdog = false;
4423 if (didModify) {
4424 state->mFastTracksGen++;
4425 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4426 if (kUseFastMixer == FastMixer_Dynamic &&
4427 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4428 state->mCommand = FastMixerState::COLD_IDLE;
4429 state->mColdFutexAddr = &mFastMixerFutex;
4430 state->mColdGen++;
4431 mFastMixerFutex = 0;
4432 if (kUseFastMixer == FastMixer_Dynamic) {
4433 mNormalSink = mOutputSink;
4434 }
4435 // If we go into cold idle, need to wait for acknowledgement
4436 // so that fast mixer stops doing I/O.
4437 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4438 pauseAudioWatchdog = true;
4439 }
Eric Laurent81784c32012-11-19 14:55:58 -08004440 }
4441 if (sq != NULL) {
4442 sq->end(didModify);
4443 sq->push(block);
4444 }
4445#ifdef AUDIO_WATCHDOG
4446 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4447 mAudioWatchdog->pause();
4448 }
4449#endif
4450
4451 // Now perform the deferred reset on fast tracks that have stopped
4452 while (resetMask != 0) {
4453 size_t i = __builtin_ctz(resetMask);
4454 ALOG_ASSERT(i < count);
4455 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004456 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004457 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4458 track->reset();
4459 }
4460
4461 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004462 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004463
Eric Laurent97d547d2014-09-02 14:45:53 -07004464 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4465 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004466 }
4467
4468 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004469 // as long as there are effects we should clear the effects buffer, to avoid
4470 // passing a non-clean buffer to the effect chain
4471 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004472 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004473 // sink or mix buffer must be cleared if all tracks are connected to an
4474 // effect chain as in this case the mixer will not write to the sink or mix buffer
4475 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004476 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4477 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004478 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004479 if (mMixerBufferValid) {
4480 memset(mMixerBuffer, 0, mMixerBufferSize);
4481 // TODO: In testing, mSinkBuffer below need not be cleared because
4482 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4483 // after mixing.
4484 //
4485 // To enforce this guarantee:
4486 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4487 // (mixedTracks == 0 && fastTracks > 0))
4488 // must imply MIXER_TRACKS_READY.
4489 // Later, we may clear buffers regardless, and skip much of this logic.
4490 }
Andy Hung98ef9782014-03-04 14:46:50 -08004491 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004492 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004493 }
4494
4495 // if any fast tracks, then status is ready
4496 mMixerStatusIgnoringFastTracks = mixerStatus;
4497 if (fastTracks > 0) {
4498 mixerStatus = MIXER_TRACKS_READY;
4499 }
4500 return mixerStatus;
4501}
4502
Eric Laurentad7dd962016-09-22 12:38:37 -07004503// trackCountForUid_l() must be called with ThreadBase::mLock held
4504uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4505{
4506 uint32_t trackCount = 0;
4507 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004508 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004509 trackCount++;
4510 }
4511 }
4512 return trackCount;
4513}
4514
Eric Laurent81784c32012-11-19 14:55:58 -08004515// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004516int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004517 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004518{
Eric Laurentad7dd962016-09-22 12:38:37 -07004519 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4520 return -1;
4521 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004522 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004523}
4524
4525// deleteTrackName_l() must be called with ThreadBase::mLock held
4526void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4527{
4528 ALOGV("remove track (%d) and delete from mixer", name);
4529 mAudioMixer->deleteTrackName(name);
4530}
4531
Eric Laurent10351942014-05-08 18:49:52 -07004532// checkForNewParameter_l() must be called with ThreadBase::mLock held
4533bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4534 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004535{
Eric Laurent81784c32012-11-19 14:55:58 -08004536 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004537 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004538
Eric Laurent10351942014-05-08 18:49:52 -07004539 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004540
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004541 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004542
Eric Laurent10351942014-05-08 18:49:52 -07004543 AudioParameter param = AudioParameter(keyValuePair);
4544 int value;
4545 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4546 reconfig = true;
4547 }
4548 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004549 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004550 status = BAD_VALUE;
4551 } else {
4552 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004553 reconfig = true;
4554 }
Eric Laurent10351942014-05-08 18:49:52 -07004555 }
4556 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004557 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004558 status = BAD_VALUE;
4559 } else {
4560 // no need to save value, since it's constant
4561 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004562 }
Eric Laurent10351942014-05-08 18:49:52 -07004563 }
4564 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4565 // do not accept frame count changes if tracks are open as the track buffer
4566 // size depends on frame count and correct behavior would not be guaranteed
4567 // if frame count is changed after track creation
4568 if (!mTracks.isEmpty()) {
4569 status = INVALID_OPERATION;
4570 } else {
4571 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004572 }
Eric Laurent10351942014-05-08 18:49:52 -07004573 }
4574 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004575#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004576 // when changing the audio output device, call addBatteryData to notify
4577 // the change
4578 if (mOutDevice != value) {
4579 uint32_t params = 0;
4580 // check whether speaker is on
4581 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4582 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004583 }
Eric Laurent10351942014-05-08 18:49:52 -07004584
4585 audio_devices_t deviceWithoutSpeaker
4586 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4587 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004588 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004589 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4590 }
4591
4592 if (params != 0) {
4593 addBatteryData(params);
4594 }
4595 }
Eric Laurent81784c32012-11-19 14:55:58 -08004596#endif
4597
Eric Laurent10351942014-05-08 18:49:52 -07004598 // forward device change to effects that have requested to be
4599 // aware of attached audio device.
4600 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004601 a2dpDeviceChanged =
4602 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004603 mOutDevice = value;
4604 for (size_t i = 0; i < mEffectChains.size(); i++) {
4605 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004606 }
4607 }
Eric Laurent10351942014-05-08 18:49:52 -07004608 }
Eric Laurent81784c32012-11-19 14:55:58 -08004609
Eric Laurent10351942014-05-08 18:49:52 -07004610 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004611 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004612 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004613 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004614 mStandby = true;
4615 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004616 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004617 }
Eric Laurent10351942014-05-08 18:49:52 -07004618 if (status == NO_ERROR && reconfig) {
4619 readOutputParameters_l();
4620 delete mAudioMixer;
4621 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4622 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004623 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004624 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004625 if (name < 0) {
4626 break;
4627 }
4628 mTracks[i]->mName = name;
4629 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004630 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004631 }
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
4633
Eric Laurent42537be2016-01-08 17:16:42 -08004634 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004635}
4636
4637
4638void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4639{
Eric Laurent81784c32012-11-19 14:55:58 -08004640 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004641 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004642 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004643 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004644
4645 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004646 // while we are dumping it. It may be inconsistent, but it won't mutate!
4647 // This is a large object so we place it on the heap.
4648 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4649 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4650 copy->dump(fd);
4651 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004652
4653#ifdef STATE_QUEUE_DUMP
4654 // Similar for state queue
4655 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4656 observerCopy.dump(fd);
4657 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4658 mutatorCopy.dump(fd);
4659#endif
4660
Glenn Kasten46909e72013-02-26 09:20:22 -08004661#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004662 // Write the tee output to a .wav file
4663 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004664#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004665
4666#ifdef AUDIO_WATCHDOG
4667 if (mAudioWatchdog != 0) {
4668 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4669 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4670 wdCopy.dump(fd);
4671 }
4672#endif
4673}
4674
4675uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4676{
4677 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4678}
4679
4680uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4681{
4682 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4683}
4684
4685void AudioFlinger::MixerThread::cacheParameters_l()
4686{
4687 PlaybackThread::cacheParameters_l();
4688
4689 // FIXME: Relaxed timing because of a certain device that can't meet latency
4690 // Should be reduced to 2x after the vendor fixes the driver issue
4691 // increase threshold again due to low power audio mode. The way this warning
4692 // threshold is calculated and its usefulness should be reconsidered anyway.
4693 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4694}
4695
4696// ----------------------------------------------------------------------------
4697
4698AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004699 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4700 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004701 // mLeftVolFloat, mRightVolFloat
4702{
4703}
4704
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4706 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004707 ThreadBase::type_t type, bool systemReady)
4708 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 // mLeftVolFloat, mRightVolFloat
4710{
4711}
4712
Eric Laurent81784c32012-11-19 14:55:58 -08004713AudioFlinger::DirectOutputThread::~DirectOutputThread()
4714{
4715}
4716
Eric Laurent5850c4c2016-11-10 13:04:31 -08004717void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004718{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004719 float left, right;
4720
4721 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4722 left = right = 0;
4723 } else {
4724 float typeVolume = mStreamTypes[track->streamType()].volume;
4725 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004726 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004727 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4728 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4729 if (left > GAIN_FLOAT_UNITY) {
4730 left = GAIN_FLOAT_UNITY;
4731 }
4732 left *= v;
4733 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4734 if (right > GAIN_FLOAT_UNITY) {
4735 right = GAIN_FLOAT_UNITY;
4736 }
4737 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738 }
4739
4740 if (lastTrack) {
4741 if (left != mLeftVolFloat || right != mRightVolFloat) {
4742 mLeftVolFloat = left;
4743 mRightVolFloat = right;
4744
4745 // Convert volumes from float to 8.24
4746 uint32_t vl = (uint32_t)(left * (1 << 24));
4747 uint32_t vr = (uint32_t)(right * (1 << 24));
4748
4749 // Delegate volume control to effect in track effect chain if needed
4750 // only one effect chain can be present on DirectOutputThread, so if
4751 // there is one, the track is connected to it
4752 if (!mEffectChains.isEmpty()) {
4753 mEffectChains[0]->setVolume_l(&vl, &vr);
4754 left = (float)vl / (1 << 24);
4755 right = (float)vr / (1 << 24);
4756 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004757 status_t result = mOutput->stream->setVolume(left, right);
4758 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004759 }
4760 }
4761}
4762
Phil Burk43b4dcc2015-06-09 16:53:44 -07004763void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4764{
4765 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004766 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004767
Eric Laurent0f0631e2015-07-06 18:01:25 -07004768 if (previousTrack != 0 && latestTrack != 0) {
4769 if (mType == DIRECT) {
4770 if (previousTrack.get() != latestTrack.get()) {
4771 mFlushPending = true;
4772 }
4773 } else /* mType == OFFLOAD */ {
4774 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4775 mFlushPending = true;
4776 }
4777 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004778 }
4779 PlaybackThread::onAddNewTrack_l();
4780}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004781
Eric Laurent81784c32012-11-19 14:55:58 -08004782AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4783 Vector< sp<Track> > *tracksToRemove
4784)
4785{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004786 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004787 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004788 bool doHwPause = false;
4789 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004790
4791 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004792 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004793 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004794 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004795 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004796 continue;
4797 }
4798
Eric Laurent5850c4c2016-11-10 13:04:31 -08004799 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004800#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004801 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004802#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004803 // Only consider last track started for volume and mixer state control.
4804 // In theory an older track could underrun and restart after the new one starts
4805 // but as we only care about the transition phase between two tracks on a
4806 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004807 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004808 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004809
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004810 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004811 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004812 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004813 doHwPause = true;
4814 mHwPaused = true;
4815 }
4816 tracksToRemove->add(track);
4817 } else if (track->isFlushPending()) {
4818 track->flushAck();
4819 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004820 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004821 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004822 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004823 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004824 if (last) {
4825 mLeftVolFloat = mRightVolFloat = -1.0;
4826 if (mHwPaused) {
4827 doHwResume = true;
4828 mHwPaused = false;
4829 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004830 }
4831 }
4832
Eric Laurent81784c32012-11-19 14:55:58 -08004833 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004834 // for all its buffers to be filled before processing it.
4835 // Allow draining the buffer in case the client
4836 // app does not call stop() and relies on underrun to stop:
4837 // hence the test on (track->mRetryCount > 1).
4838 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004839 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004840 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004841 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004842 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004843 minFrames = mNormalFrameCount;
4844 } else {
4845 minFrames = 1;
4846 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004847
Eric Laurentab5cdba2014-06-09 17:22:27 -07004848 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4849 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004850 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004851 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004852
4853 if (track->mFillingUpStatus == Track::FS_FILLED) {
4854 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004855 if (last) {
4856 // make sure processVolume_l() will apply new volume even if 0
4857 mLeftVolFloat = mRightVolFloat = -1.0;
4858 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004859 if (!mHwSupportsPause) {
4860 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004861 }
4862 }
4863
4864 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004865 processVolume_l(track, last);
4866 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004867 sp<Track> previousTrack = mPreviousTrack.promote();
4868 if (previousTrack != 0) {
4869 if (track != previousTrack.get()) {
4870 // Flush any data still being written from last track
4871 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004872 // Invalidate previous track to force a seek when resuming.
4873 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004874 }
4875 }
4876 mPreviousTrack = track;
4877
Eric Laurentd595b7c2013-04-03 17:27:56 -07004878 // reset retry count
4879 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004880 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004881 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004882 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004883 doHwResume = true;
4884 mHwPaused = false;
4885 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004886 }
Eric Laurent81784c32012-11-19 14:55:58 -08004887 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004888 // clear effect chain input buffer if the last active track started underruns
4889 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004890 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004891 mEffectChains[0]->clearInputBuffer();
4892 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004893 if (track->isStopping_1()) {
4894 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004895 if (last && mHwPaused) {
4896 doHwResume = true;
4897 mHwPaused = false;
4898 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004899 }
4900 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4901 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004902 // We have consumed all the buffers of this track.
4903 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004904 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004905 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004906 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4907 } else {
4908 audioHALFrames = 0;
4909 }
4910
Andy Hung818e7a32016-02-16 18:08:07 -08004911 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004912 if (mStandby || !last ||
4913 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004914 if (track->isStopping_2()) {
4915 track->mState = TrackBase::STOPPED;
4916 }
Eric Laurent81784c32012-11-19 14:55:58 -08004917 if (track->isStopped()) {
4918 track->reset();
4919 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004920 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004921 }
4922 } else {
4923 // No buffers for this track. Give it a few chances to
4924 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004925 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004926 if (--(track->mRetryCount) <= 0) {
4927 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004928 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004929 // indicate to client process that the track was disabled because of underrun;
4930 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004931 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004932 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004933 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4934 "minFrames = %u, mFormat = %#x",
4935 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004936 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004937 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004938 doHwPause = true;
4939 mHwPaused = true;
4940 }
Eric Laurent81784c32012-11-19 14:55:58 -08004941 }
4942 }
4943 }
4944 }
4945
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004947 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004948 for (size_t i = 0; i < mTracks.size(); i++) {
4949 if (mTracks[i]->isFlushPending()) {
4950 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004951 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004952 }
4953 }
4954 }
4955
4956 // make sure the pause/flush/resume sequence is executed in the right order.
4957 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4958 // before flush and then resume HW. This can happen in case of pause/flush/resume
4959 // if resume is received before pause is executed.
4960 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004961 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004962 status_t result = mOutput->stream->pause();
4963 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004964 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004965 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004966 flushHw_l();
4967 }
4968 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004969 status_t result = mOutput->stream->resume();
4970 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004971 }
Eric Laurent81784c32012-11-19 14:55:58 -08004972 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004973 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004974
4975 return mixerStatus;
4976}
4977
4978void AudioFlinger::DirectOutputThread::threadLoop_mix()
4979{
Eric Laurent81784c32012-11-19 14:55:58 -08004980 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004981 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004982 // output audio to hardware
4983 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004984 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004985 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004986 status_t status = mActiveTrack->getNextBuffer(&buffer);
4987 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004988 // no need to pad with 0 for compressed audio
4989 if (audio_has_proportional_frames(mFormat)) {
4990 memset(curBuf, 0, frameCount * mFrameSize);
4991 }
Eric Laurent81784c32012-11-19 14:55:58 -08004992 break;
4993 }
4994 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4995 frameCount -= buffer.frameCount;
4996 curBuf += buffer.frameCount * mFrameSize;
4997 mActiveTrack->releaseBuffer(&buffer);
4998 }
Andy Hung2098f272014-02-27 14:00:06 -08004999 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005000 mSleepTimeUs = 0;
5001 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005002 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005003}
5004
5005void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5006{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005007 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005008 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005009 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005010 return;
5011 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005012 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005013 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005014 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005015 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005016 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005017 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005018 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005019 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005020 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005021 }
5022}
5023
Eric Laurentd1f69b02014-12-15 14:33:13 -08005024void AudioFlinger::DirectOutputThread::threadLoop_exit()
5025{
5026 {
5027 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005028 for (size_t i = 0; i < mTracks.size(); i++) {
5029 if (mTracks[i]->isFlushPending()) {
5030 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005031 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005032 }
5033 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005034 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005035 flushHw_l();
5036 }
5037 }
5038 PlaybackThread::threadLoop_exit();
5039}
5040
5041// must be called with thread mutex locked
5042bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5043{
5044 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005045 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005046
vivek mehta9cd7ad12016-03-17 00:18:29 -07005047 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5048 return !mStandby;
5049 }
5050
Eric Laurentd1f69b02014-12-15 14:33:13 -08005051 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5052 // after a timeout and we will enter standby then.
5053 if (mTracks.size() > 0) {
5054 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005055 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5056 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 }
5058
Eric Laurent5cff4032015-05-26 13:49:58 -07005059 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005060}
5061
Eric Laurent81784c32012-11-19 14:55:58 -08005062// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005063int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005064 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005065{
Eric Laurentad7dd962016-09-22 12:38:37 -07005066 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5067 return -1;
5068 }
Eric Laurent81784c32012-11-19 14:55:58 -08005069 return 0;
5070}
5071
5072// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005073void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005074{
5075}
5076
Eric Laurent10351942014-05-08 18:49:52 -07005077// checkForNewParameter_l() must be called with ThreadBase::mLock held
5078bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5079 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005080{
5081 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005082 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005083
Eric Laurent10351942014-05-08 18:49:52 -07005084 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005085
Eric Laurent10351942014-05-08 18:49:52 -07005086 AudioParameter param = AudioParameter(keyValuePair);
5087 int value;
5088 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5089 // forward device change to effects that have requested to be
5090 // aware of attached audio device.
5091 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005092 a2dpDeviceChanged =
5093 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005094 mOutDevice = value;
5095 for (size_t i = 0; i < mEffectChains.size(); i++) {
5096 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005097 }
5098 }
Eric Laurent81784c32012-11-19 14:55:58 -08005099 }
Eric Laurent10351942014-05-08 18:49:52 -07005100 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5101 // do not accept frame count changes if tracks are open as the track buffer
5102 // size depends on frame count and correct behavior would not be garantied
5103 // if frame count is changed after track creation
5104 if (!mTracks.isEmpty()) {
5105 status = INVALID_OPERATION;
5106 } else {
5107 reconfig = true;
5108 }
5109 }
5110 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005111 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005112 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005113 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005114 mStandby = true;
5115 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005116 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005117 }
5118 if (status == NO_ERROR && reconfig) {
5119 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005120 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005121 }
5122 }
5123
Eric Laurent42537be2016-01-08 17:16:42 -08005124 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005125}
5126
5127uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5128{
5129 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005130 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005131 time = PlaybackThread::activeSleepTimeUs();
5132 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005133 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005134 }
5135 return time;
5136}
5137
5138uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5139{
5140 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005141 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005142 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5143 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005144 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005145 }
5146 return time;
5147}
5148
5149uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5150{
5151 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005152 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005153 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5154 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005155 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005156 }
5157 return time;
5158}
5159
5160void AudioFlinger::DirectOutputThread::cacheParameters_l()
5161{
5162 PlaybackThread::cacheParameters_l();
5163
5164 // use shorter standby delay as on normal output to release
5165 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005166 // no delay on outputs with HW A/V sync
5167 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005168 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005169 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005170 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005171 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005172 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005173 }
Eric Laurent81784c32012-11-19 14:55:58 -08005174}
5175
Eric Laurente659ef42014-09-29 13:06:46 -07005176void AudioFlinger::DirectOutputThread::flushHw_l()
5177{
Phil Burk062e67a2015-02-11 13:40:50 -08005178 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005179 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005180 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005181}
5182
Eric Laurent81784c32012-11-19 14:55:58 -08005183// ----------------------------------------------------------------------------
5184
Eric Laurentbfb1b832013-01-07 09:53:42 -08005185AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005186 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005187 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005188 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005189 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005190 mDrainSequence(0),
5191 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005192{
5193}
5194
5195AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5196{
5197}
5198
5199void AudioFlinger::AsyncCallbackThread::onFirstRef()
5200{
5201 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5202}
5203
5204bool AudioFlinger::AsyncCallbackThread::threadLoop()
5205{
5206 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005207 uint32_t writeAckSequence;
5208 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005209 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005210
5211 {
5212 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005213 while (!((mWriteAckSequence & 1) ||
5214 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005215 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005216 exitPending())) {
5217 mWaitWorkCV.wait(mLock);
5218 }
5219
Eric Laurentbfb1b832013-01-07 09:53:42 -08005220 if (exitPending()) {
5221 break;
5222 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005223 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5224 mWriteAckSequence, mDrainSequence);
5225 writeAckSequence = mWriteAckSequence;
5226 mWriteAckSequence &= ~1;
5227 drainSequence = mDrainSequence;
5228 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005229 asyncError = mAsyncError;
5230 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005231 }
5232 {
Eric Laurent4de95592013-09-26 15:28:21 -07005233 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5234 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005235 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005236 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005238 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005239 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005241 if (asyncError) {
5242 playbackThread->onAsyncError();
5243 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005244 }
5245 }
5246 }
5247 return false;
5248}
5249
5250void AudioFlinger::AsyncCallbackThread::exit()
5251{
5252 ALOGV("AsyncCallbackThread::exit");
5253 Mutex::Autolock _l(mLock);
5254 requestExit();
5255 mWaitWorkCV.broadcast();
5256}
5257
Eric Laurent3b4529e2013-09-05 18:09:19 -07005258void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005259{
5260 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005261 // bit 0 is cleared
5262 mWriteAckSequence = sequence << 1;
5263}
5264
5265void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5266{
5267 Mutex::Autolock _l(mLock);
5268 // ignore unexpected callbacks
5269 if (mWriteAckSequence & 2) {
5270 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005271 mWaitWorkCV.signal();
5272 }
5273}
5274
Eric Laurent3b4529e2013-09-05 18:09:19 -07005275void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005276{
5277 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005278 // bit 0 is cleared
5279 mDrainSequence = sequence << 1;
5280}
5281
5282void AudioFlinger::AsyncCallbackThread::resetDraining()
5283{
5284 Mutex::Autolock _l(mLock);
5285 // ignore unexpected callbacks
5286 if (mDrainSequence & 2) {
5287 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005288 mWaitWorkCV.signal();
5289 }
5290}
5291
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005292void AudioFlinger::AsyncCallbackThread::setAsyncError()
5293{
5294 Mutex::Autolock _l(mLock);
5295 mAsyncError = true;
5296 mWaitWorkCV.signal();
5297}
5298
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299
5300// ----------------------------------------------------------------------------
5301AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005302 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5303 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005304 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5305 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306{
Eric Laurentfd477972013-10-25 18:10:40 -07005307 //FIXME: mStandby should be set to true by ThreadBase constructor
5308 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005309 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310}
5311
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312void AudioFlinger::OffloadThread::threadLoop_exit()
5313{
5314 if (mFlushPending || mHwPaused) {
5315 // If a flush is pending or track was paused, just discard buffered data
5316 flushHw_l();
5317 } else {
5318 mMixerStatus = MIXER_DRAIN_ALL;
5319 threadLoop_drain();
5320 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005321 if (mUseAsyncWrite) {
5322 ALOG_ASSERT(mCallbackThread != 0);
5323 mCallbackThread->exit();
5324 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005325 PlaybackThread::threadLoop_exit();
5326}
5327
5328AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5329 Vector< sp<Track> > *tracksToRemove
5330)
5331{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005332 size_t count = mActiveTracks.size();
5333
5334 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005335 bool doHwPause = false;
5336 bool doHwResume = false;
5337
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005338 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005339
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005341 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005342 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005343#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005345#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005346 // Only consider last track started for volume and mixer state control.
5347 // In theory an older track could underrun and restart after the new one starts
5348 // but as we only care about the transition phase between two tracks on a
5349 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005350 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005351 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005352
Haynes Mathew George7844f672014-01-15 12:32:55 -08005353 if (track->isInvalid()) {
5354 ALOGW("An invalidated track shouldn't be in active list");
5355 tracksToRemove->add(track);
5356 continue;
5357 }
5358
5359 if (track->mState == TrackBase::IDLE) {
5360 ALOGW("An idle track shouldn't be in active list");
5361 continue;
5362 }
5363
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364 if (track->isPausing()) {
5365 track->setPaused();
5366 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005367 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005368 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005369 mHwPaused = true;
5370 }
5371 // If we were part way through writing the mixbuffer to
5372 // the HAL we must save this until we resume
5373 // BUG - this will be wrong if a different track is made active,
5374 // in that case we want to discard the pending data in the
5375 // mixbuffer and tell the client to present it again when the
5376 // track is resumed
5377 mPausedWriteLength = mCurrentWriteLength;
5378 mPausedBytesRemaining = mBytesRemaining;
5379 mBytesRemaining = 0; // stop writing
5380 }
5381 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005382 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005383 if (track->isStopping_1()) {
5384 track->mRetryCount = kMaxTrackStopRetriesOffload;
5385 } else {
5386 track->mRetryCount = kMaxTrackRetriesOffload;
5387 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005388 track->flushAck();
5389 if (last) {
5390 mFlushPending = true;
5391 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005392 } else if (track->isResumePending()){
5393 track->resumeAck();
5394 if (last) {
5395 if (mPausedBytesRemaining) {
5396 // Need to continue write that was interrupted
5397 mCurrentWriteLength = mPausedWriteLength;
5398 mBytesRemaining = mPausedBytesRemaining;
5399 mPausedBytesRemaining = 0;
5400 }
5401 if (mHwPaused) {
5402 doHwResume = true;
5403 mHwPaused = false;
5404 // threadLoop_mix() will handle the case that we need to
5405 // resume an interrupted write
5406 }
5407 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005408 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005409
Eric Laurent3df841a2016-07-15 15:15:40 -07005410 mLeftVolFloat = mRightVolFloat = -1.0;
5411
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005412 // Do not handle new data in this iteration even if track->framesReady()
5413 mixerStatus = MIXER_TRACKS_ENABLED;
5414 }
5415 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005416 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005417 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005418 if (track->mFillingUpStatus == Track::FS_FILLED) {
5419 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005420 if (last) {
5421 // make sure processVolume_l() will apply new volume even if 0
5422 mLeftVolFloat = mRightVolFloat = -1.0;
5423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005424 }
5425
5426 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005427 sp<Track> previousTrack = mPreviousTrack.promote();
5428 if (previousTrack != 0) {
5429 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005430 // Flush any data still being written from last track
5431 mBytesRemaining = 0;
5432 if (mPausedBytesRemaining) {
5433 // Last track was paused so we also need to flush saved
5434 // mixbuffer state and invalidate track so that it will
5435 // re-submit that unwritten data when it is next resumed
5436 mPausedBytesRemaining = 0;
5437 // Invalidate is a bit drastic - would be more efficient
5438 // to have a flag to tell client that some of the
5439 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005440 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005441 }
5442 // flush data already sent to the DSP if changing audio session as audio
5443 // comes from a different source. Also invalidate previous track to force a
5444 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005445 if (previousTrack->sessionId() != track->sessionId()) {
5446 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005447 }
5448 }
5449 }
5450 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005451 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005452 if (track->isStopping_1()) {
5453 track->mRetryCount = kMaxTrackStopRetriesOffload;
5454 } else {
5455 track->mRetryCount = kMaxTrackRetriesOffload;
5456 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005457 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 mixerStatus = MIXER_TRACKS_READY;
5459 }
5460 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005461 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005463 if (--(track->mRetryCount) <= 0) {
5464 // Hardware buffer can hold a large amount of audio so we must
5465 // wait for all current track's data to drain before we say
5466 // that the track is stopped.
5467 if (mBytesRemaining == 0) {
5468 // Only start draining when all data in mixbuffer
5469 // has been written
5470 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5471 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5472 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5473 if (last && !mStandby) {
5474 // do not modify drain sequence if we are already draining. This happens
5475 // when resuming from pause after drain.
5476 if ((mDrainSequence & 1) == 0) {
5477 mSleepTimeUs = 0;
5478 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5479 mixerStatus = MIXER_DRAIN_TRACK;
5480 mDrainSequence += 2;
5481 }
5482 if (mHwPaused) {
5483 // It is possible to move from PAUSED to STOPPING_1 without
5484 // a resume so we must ensure hardware is running
5485 doHwResume = true;
5486 mHwPaused = false;
5487 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005488 }
5489 }
Eric Laurente93cc032016-05-05 10:15:10 -07005490 } else if (last) {
5491 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5492 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005493 }
5494 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005495 // Drain has completed or we are in standby, signal presentation complete
5496 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005497 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005498 uint32_t latency = 0;
5499 status_t result = mOutput->stream->getLatency(&latency);
5500 ALOGE_IF(result != OK,
5501 "Error when retrieving output stream latency: %d", result);
5502 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005503 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005504 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005505 track->presentationComplete(framesWritten, audioHALFrames);
5506 track->reset();
5507 tracksToRemove->add(track);
5508 }
5509 } else {
5510 // No buffers for this track. Give it a few chances to
5511 // fill a buffer, then remove it from active list.
5512 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005513 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005514 uint64_t position = 0;
5515 struct timespec unused;
5516 // The running check restarts the retry counter at least once.
5517 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5518 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5519 running = true;
5520 mOffloadUnderrunPosition = position;
5521 }
5522 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005523 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5524 (long long)position, (long long)mOffloadUnderrunPosition);
5525 }
5526 if (running) { // still running, give us more time.
5527 track->mRetryCount = kMaxTrackRetriesOffload;
5528 } else {
5529 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5530 track->name());
5531 tracksToRemove->add(track);
5532 // indicate to client process that the track was disabled because of underrun;
5533 // it will then automatically call start() when data is available
5534 track->disable();
5535 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005536 } else if (last){
5537 mixerStatus = MIXER_TRACKS_ENABLED;
5538 }
5539 }
5540 }
5541 // compute volume for this track
5542 processVolume_l(track, last);
5543 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005544
Eric Laurentea0fade2013-10-04 16:23:48 -07005545 // make sure the pause/flush/resume sequence is executed in the right order.
5546 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5547 // before flush and then resume HW. This can happen in case of pause/flush/resume
5548 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005549 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005550 status_t result = mOutput->stream->pause();
5551 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005552 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005553 if (mFlushPending) {
5554 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005555 }
Eric Laurentfd477972013-10-25 18:10:40 -07005556 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005557 status_t result = mOutput->stream->resume();
5558 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005559 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005560
Eric Laurentbfb1b832013-01-07 09:53:42 -08005561 // remove all the tracks that need to be...
5562 removeTracks_l(*tracksToRemove);
5563
5564 return mixerStatus;
5565}
5566
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567// must be called with thread mutex locked
5568bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5569{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005570 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5571 mWriteAckSequence, mDrainSequence);
5572 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005573 return true;
5574 }
5575 return false;
5576}
5577
Eric Laurentbfb1b832013-01-07 09:53:42 -08005578bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5579{
5580 Mutex::Autolock _l(mLock);
5581 return waitingAsyncCallback_l();
5582}
5583
5584void AudioFlinger::OffloadThread::flushHw_l()
5585{
Eric Laurente659ef42014-09-29 13:06:46 -07005586 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005587 // Flush anything still waiting in the mixbuffer
5588 mCurrentWriteLength = 0;
5589 mBytesRemaining = 0;
5590 mPausedWriteLength = 0;
5591 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005592 // reset bytes written count to reflect that DSP buffers are empty after flush.
5593 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005594 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005595
Eric Laurentbfb1b832013-01-07 09:53:42 -08005596 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005597 // discard any pending drain or write ack by incrementing sequence
5598 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5599 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005600 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005601 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5602 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005603 }
5604}
5605
Haynes Mathew George05317d22016-05-03 16:34:26 -07005606void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5607{
5608 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005609 if (PlaybackThread::invalidateTracks_l(streamType)) {
5610 mFlushPending = true;
5611 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005612}
5613
Eric Laurentbfb1b832013-01-07 09:53:42 -08005614// ----------------------------------------------------------------------------
5615
Eric Laurent81784c32012-11-19 14:55:58 -08005616AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005617 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005618 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005619 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005620 mWaitTimeMs(UINT_MAX)
5621{
5622 addOutputTrack(mainThread);
5623}
5624
5625AudioFlinger::DuplicatingThread::~DuplicatingThread()
5626{
5627 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5628 mOutputTracks[i]->destroy();
5629 }
5630}
5631
5632void AudioFlinger::DuplicatingThread::threadLoop_mix()
5633{
5634 // mix buffers...
5635 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005636 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005637 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005638 if (mMixerBufferValid) {
5639 memset(mMixerBuffer, 0, mMixerBufferSize);
5640 } else {
5641 memset(mSinkBuffer, 0, mSinkBufferSize);
5642 }
Eric Laurent81784c32012-11-19 14:55:58 -08005643 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005644 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005645 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005646 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005647 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005648}
5649
5650void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5651{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005652 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005653 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005654 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005655 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005656 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005657 }
5658 } else if (mBytesWritten != 0) {
5659 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5660 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005661 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005662 } else {
5663 // flush remaining overflow buffers in output tracks
5664 writeFrames = 0;
5665 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005666 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005667 }
5668}
5669
Eric Laurentbfb1b832013-01-07 09:53:42 -08005670ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005671{
5672 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005673 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005674 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005675 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005676 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005677}
5678
5679void AudioFlinger::DuplicatingThread::threadLoop_standby()
5680{
5681 // DuplicatingThread implements standby by stopping all tracks
5682 for (size_t i = 0; i < outputTracks.size(); i++) {
5683 outputTracks[i]->stop();
5684 }
5685}
5686
5687void AudioFlinger::DuplicatingThread::saveOutputTracks()
5688{
5689 outputTracks = mOutputTracks;
5690}
5691
5692void AudioFlinger::DuplicatingThread::clearOutputTracks()
5693{
5694 outputTracks.clear();
5695}
5696
5697void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5698{
5699 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005700 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5701 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5702 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5703 const size_t frameCount =
5704 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5705 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5706 // from different OutputTracks and their associated MixerThreads (e.g. one may
5707 // nearly empty and the other may be dropping data).
5708
5709 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005710 this,
5711 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005712 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005713 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005714 frameCount,
5715 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005716 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5717 if (status != NO_ERROR) {
5718 ALOGE("addOutputTrack() initCheck failed %d", status);
5719 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005720 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005721 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5722 mOutputTracks.add(outputTrack);
5723 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5724 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005725}
5726
5727void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5728{
5729 Mutex::Autolock _l(mLock);
5730 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5731 if (mOutputTracks[i]->thread() == thread) {
5732 mOutputTracks[i]->destroy();
5733 mOutputTracks.removeAt(i);
5734 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005735 if (thread->getOutput() == mOutput) {
5736 mOutput = NULL;
5737 }
Eric Laurent81784c32012-11-19 14:55:58 -08005738 return;
5739 }
5740 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005741 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005742}
5743
5744// caller must hold mLock
5745void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5746{
5747 mWaitTimeMs = UINT_MAX;
5748 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5749 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5750 if (strong != 0) {
5751 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5752 if (waitTimeMs < mWaitTimeMs) {
5753 mWaitTimeMs = waitTimeMs;
5754 }
5755 }
5756 }
5757}
5758
5759
5760bool AudioFlinger::DuplicatingThread::outputsReady(
5761 const SortedVector< sp<OutputTrack> > &outputTracks)
5762{
5763 for (size_t i = 0; i < outputTracks.size(); i++) {
5764 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5765 if (thread == 0) {
5766 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5767 outputTracks[i].get());
5768 return false;
5769 }
5770 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5771 // see note at standby() declaration
5772 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5773 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5774 thread.get());
5775 return false;
5776 }
5777 }
5778 return true;
5779}
5780
5781uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5782{
5783 return (mWaitTimeMs * 1000) / 2;
5784}
5785
5786void AudioFlinger::DuplicatingThread::cacheParameters_l()
5787{
5788 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5789 updateWaitTime_l();
5790
5791 MixerThread::cacheParameters_l();
5792}
5793
5794// ----------------------------------------------------------------------------
5795// Record
5796// ----------------------------------------------------------------------------
5797
5798AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5799 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005800 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005801 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005802 audio_devices_t inDevice,
5803 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005804#ifdef TEE_SINK
5805 , const sp<NBAIO_Sink>& teeSink
5806#endif
5807 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005808 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005809 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005810 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005811 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005812#ifdef TEE_SINK
5813 , mTeeSink(teeSink)
5814#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005815 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5816 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005817 // mFastCapture below
5818 , mFastCaptureFutex(0)
5819 // mInputSource
5820 // mPipeSink
5821 // mPipeSource
5822 , mPipeFramesP2(0)
5823 // mPipeMemory
5824 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005825 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005826{
Glenn Kastend7dca052015-03-05 16:05:54 -08005827 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5828 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005829
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005830 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005831
5832 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005833 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005834 size_t numCounterOffers = 0;
5835 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005836#if !LOG_NDEBUG
5837 ssize_t index =
5838#else
5839 (void)
5840#endif
5841 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005842 ALOG_ASSERT(index == 0);
5843
5844 // initialize fast capture depending on configuration
5845 bool initFastCapture;
5846 switch (kUseFastCapture) {
5847 case FastCapture_Never:
5848 initFastCapture = false;
5849 break;
5850 case FastCapture_Always:
5851 initFastCapture = true;
5852 break;
5853 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005854 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005855 break;
5856 // case FastCapture_Dynamic:
5857 }
5858
5859 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005860 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005861 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005862 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5863 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005864 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5865 void *pipeBuffer;
5866 const sp<MemoryDealer> roHeap(readOnlyHeap());
5867 sp<IMemory> pipeMemory;
5868 if ((roHeap == 0) ||
5869 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5870 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5871 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5872 goto failed;
5873 }
5874 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5875 memset(pipeBuffer, 0, pipeSize);
5876 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5877 const NBAIO_Format offers[1] = {format};
5878 size_t numCounterOffers = 0;
5879 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5880 ALOG_ASSERT(index == 0);
5881 mPipeSink = pipe;
5882 PipeReader *pipeReader = new PipeReader(*pipe);
5883 numCounterOffers = 0;
5884 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5885 ALOG_ASSERT(index == 0);
5886 mPipeSource = pipeReader;
5887 mPipeFramesP2 = pipeFramesP2;
5888 mPipeMemory = pipeMemory;
5889
5890 // create fast capture
5891 mFastCapture = new FastCapture();
5892 FastCaptureStateQueue *sq = mFastCapture->sq();
5893#ifdef STATE_QUEUE_DUMP
5894 // FIXME
5895#endif
5896 FastCaptureState *state = sq->begin();
5897 state->mCblk = NULL;
5898 state->mInputSource = mInputSource.get();
5899 state->mInputSourceGen++;
5900 state->mPipeSink = pipe;
5901 state->mPipeSinkGen++;
5902 state->mFrameCount = mFrameCount;
5903 state->mCommand = FastCaptureState::COLD_IDLE;
5904 // already done in constructor initialization list
5905 //mFastCaptureFutex = 0;
5906 state->mColdFutexAddr = &mFastCaptureFutex;
5907 state->mColdGen++;
5908 state->mDumpState = &mFastCaptureDumpState;
5909#ifdef TEE_SINK
5910 // FIXME
5911#endif
5912 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5913 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5914 sq->end();
5915 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5916
5917 // start the fast capture
5918 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5919 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005920 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005921 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005922#ifdef AUDIO_WATCHDOG
5923 // FIXME
5924#endif
5925
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005926 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005927 }
5928failed: ;
5929
5930 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005931}
5932
Eric Laurent81784c32012-11-19 14:55:58 -08005933AudioFlinger::RecordThread::~RecordThread()
5934{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005935 if (mFastCapture != 0) {
5936 FastCaptureStateQueue *sq = mFastCapture->sq();
5937 FastCaptureState *state = sq->begin();
5938 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5939 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5940 if (old == -1) {
5941 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5942 }
5943 }
5944 state->mCommand = FastCaptureState::EXIT;
5945 sq->end();
5946 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5947 mFastCapture->join();
5948 mFastCapture.clear();
5949 }
5950 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005951 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005952 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005953}
5954
5955void AudioFlinger::RecordThread::onFirstRef()
5956{
Glenn Kastend7dca052015-03-05 16:05:54 -08005957 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005958}
5959
Eric Laurent81784c32012-11-19 14:55:58 -08005960bool AudioFlinger::RecordThread::threadLoop()
5961{
Eric Laurent81784c32012-11-19 14:55:58 -08005962 nsecs_t lastWarning = 0;
5963
5964 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005965
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005966reacquire_wakelock:
5967 sp<RecordTrack> activeTrack;
5968 {
5969 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005970 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005971 }
5972
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005973 // used to request a deferred sleep, to be executed later while mutex is unlocked
5974 uint32_t sleepUs = 0;
5975
5976 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005977 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005978 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005979
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005980 // activeTracks accumulates a copy of a subset of mActiveTracks
5981 Vector< sp<RecordTrack> > activeTracks;
5982
Glenn Kasten735f45f2014-08-18 15:51:59 -07005983 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005984 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005985
Glenn Kasten735f45f2014-08-18 15:51:59 -07005986 // reference to a fast track which is about to be removed
5987 sp<RecordTrack> fastTrackToRemove;
5988
Eric Laurent81784c32012-11-19 14:55:58 -08005989 { // scope for mLock
5990 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005991
Eric Laurent021cf962014-05-13 10:18:14 -07005992 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005993
Eric Laurent000a4192014-01-29 15:17:32 -08005994 // check exitPending here because checkForNewParameters_l() and
5995 // checkForNewParameters_l() can temporarily release mLock
5996 if (exitPending()) {
5997 break;
5998 }
5999
Eric Laurent5c25d562016-07-13 17:17:45 -07006000 // sleep with mutex unlocked
6001 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006002 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006003 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6004 ATRACE_END();
6005 sleepUs = 0;
6006 continue;
6007 }
6008
Glenn Kasten2b806402013-11-20 16:37:38 -08006009 // if no active track(s), then standby and release wakelock
6010 size_t size = mActiveTracks.size();
6011 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006012 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006013 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006014 releaseWakeLock_l();
6015 ALOGV("RecordThread: loop stopping");
6016 // go to sleep
6017 mWaitWorkCV.wait(mLock);
6018 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006019 goto reacquire_wakelock;
6020 }
6021
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006022 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006023 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006024 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006025
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 activeTrack = mActiveTracks[i];
6027 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006028 if (activeTrack->isFastTrack()) {
6029 ALOG_ASSERT(fastTrackToRemove == 0);
6030 fastTrackToRemove = activeTrack;
6031 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006032 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006033 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006035 continue;
6036 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006037
6038 TrackBase::track_state activeTrackState = activeTrack->mState;
6039 switch (activeTrackState) {
6040
6041 case TrackBase::PAUSING:
6042 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006043 doBroadcast = true;
6044 size--;
6045 continue;
6046
6047 case TrackBase::STARTING_1:
6048 sleepUs = 10000;
6049 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006050 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006051 continue;
6052
6053 case TrackBase::STARTING_2:
6054 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006055 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006056 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006057 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006058 break;
6059
6060 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006061 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006062 break;
6063
6064 case TrackBase::IDLE:
6065 i++;
6066 continue;
6067
6068 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006069 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006070 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006071
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006072 activeTracks.add(activeTrack);
6073 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006074
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 if (activeTrack->isFastTrack()) {
6076 ALOG_ASSERT(!mFastTrackAvail);
6077 ALOG_ASSERT(fastTrack == 0);
6078 fastTrack = activeTrack;
6079 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006080 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006081
Andy Hungdae27702016-10-31 14:01:16 -07006082 mActiveTracks.updatePowerState(this);
6083
Eric Laurent5c25d562016-07-13 17:17:45 -07006084 if (allStopped) {
6085 standbyIfNotAlreadyInStandby();
6086 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006087 if (doBroadcast) {
6088 mStartStopCond.broadcast();
6089 }
6090
6091 // sleep if there are no active tracks to process
6092 if (activeTracks.size() == 0) {
6093 if (sleepUs == 0) {
6094 sleepUs = kRecordThreadSleepUs;
6095 }
6096 continue;
6097 }
6098 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006099
Eric Laurent81784c32012-11-19 14:55:58 -08006100 lockEffectChains_l(effectChains);
6101 }
6102
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006103 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006104
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105 size_t size = effectChains.size();
6106 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006107 // thread mutex is not locked, but effect chain is locked
6108 effectChains[i]->process_l();
6109 }
6110
Glenn Kasten735f45f2014-08-18 15:51:59 -07006111 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006112 if (mFastCapture != 0) {
6113 FastCaptureStateQueue *sq = mFastCapture->sq();
6114 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006115 bool didModify = false;
6116 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006117 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6118 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6119 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6120 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6121 if (old == -1) {
6122 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6123 }
6124 }
6125 state->mCommand = FastCaptureState::READ_WRITE;
6126#if 0 // FIXME
6127 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006128 FastThreadDumpState::kSamplingNforLowRamDevice :
6129 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006130#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006131 didModify = true;
6132 }
6133 audio_track_cblk_t *cblkOld = state->mCblk;
6134 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6135 if (cblkNew != cblkOld) {
6136 state->mCblk = cblkNew;
6137 // block until acked if removing a fast track
6138 if (cblkOld != NULL) {
6139 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6140 }
6141 didModify = true;
6142 }
6143 sq->end(didModify);
6144 if (didModify) {
6145 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006146#if 0
6147 if (kUseFastCapture == FastCapture_Dynamic) {
6148 mNormalSource = mPipeSource;
6149 }
6150#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006151 }
6152 }
6153
Glenn Kasten735f45f2014-08-18 15:51:59 -07006154 // now run the fast track destructor with thread mutex unlocked
6155 fastTrackToRemove.clear();
6156
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006157 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6158 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6159 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6160 // If destination is non-contiguous, first read past the nominal end of buffer, then
6161 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006162
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006163 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006164 ssize_t framesRead;
6165
6166 // If an NBAIO source is present, use it to read the normal capture's data
6167 if (mPipeSource != 0) {
6168 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006169 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006170 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006171 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006172 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6173 // buffer size or at least for 20ms.
6174 size_t sleepFrames = max(
6175 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6176 if (framesRead <= (ssize_t) sleepFrames) {
6177 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6178 }
6179 if (framesRead < 0) {
6180 status_t status = (status_t) framesRead;
6181 switch (status) {
6182 case OVERRUN:
6183 ALOGW("overrun on read from pipe");
6184 framesRead = 0;
6185 break;
6186 case NEGOTIATE:
6187 ALOGE("re-negotiation is needed");
6188 framesRead = -1; // Will cause an attempt to recover.
6189 break;
6190 default:
6191 ALOGE("unknown error %d on read from pipe", status);
6192 break;
6193 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006194 }
6195 // otherwise use the HAL / AudioStreamIn directly
6196 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006197 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006198 size_t bytesRead;
6199 status_t result = mInput->stream->read(
6200 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006201 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006202 if (result < 0) {
6203 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006204 } else {
6205 framesRead = bytesRead / mFrameSize;
6206 }
6207 }
6208
Andy Hung3f0c9022016-01-15 17:49:46 -08006209 // Update server timestamp with server stats
6210 // systemTime() is optional if the hardware supports timestamps.
6211 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6212 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6213
6214 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006215 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006216 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006217 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006218 if (ret == NO_ERROR) {
6219 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6220 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6221 // Note: In general record buffers should tend to be empty in
6222 // a properly running pipeline.
6223 //
6224 // Also, it is not advantageous to call get_presentation_position during the read
6225 // as the read obtains a lock, preventing the timestamp call from executing.
6226 }
6227 }
6228 // Use this to track timestamp information
6229 // ALOGD("%s", mTimestamp.toString().c_str());
6230
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006231 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006232 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006233 // Force input into standby so that it tries to recover at next read attempt
6234 inputStandBy();
6235 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006236 }
6237 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006238 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006239 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006240 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006241
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006243 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006244 }
6245 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006246 {
6247 size_t part1 = mRsmpInFramesP2 - rear;
6248 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006249 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006250 (framesRead - part1) * mFrameSize);
6251 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006252 }
6253 rear = mRsmpInRear += framesRead;
6254
6255 size = activeTracks.size();
6256 // loop over each active track
6257 for (size_t i = 0; i < size; i++) {
6258 activeTrack = activeTracks[i];
6259
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006260 // skip fast tracks, as those are handled directly by FastCapture
6261 if (activeTrack->isFastTrack()) {
6262 continue;
6263 }
6264
Andy Hung73c02e42015-03-29 01:13:58 -07006265 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006266 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6267
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006268 enum {
6269 OVERRUN_UNKNOWN,
6270 OVERRUN_TRUE,
6271 OVERRUN_FALSE
6272 } overrun = OVERRUN_UNKNOWN;
6273
6274 // loop over getNextBuffer to handle circular sink
6275 for (;;) {
6276
6277 activeTrack->mSink.frameCount = ~0;
6278 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6279 size_t framesOut = activeTrack->mSink.frameCount;
6280 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6281
Andy Hung73c02e42015-03-29 01:13:58 -07006282 // check available frames and handle overrun conditions
6283 // if the record track isn't draining fast enough.
6284 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006285 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006286 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6287 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006288 overrun = OVERRUN_TRUE;
6289 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006290 if (framesOut == 0 || framesIn == 0) {
6291 break;
6292 }
6293
Andy Hung6770c6f2015-04-07 13:43:36 -07006294 // Don't allow framesOut to be larger than what is possible with resampling
6295 // from framesIn.
6296 // This isn't strictly necessary but helps limit buffer resizing in
6297 // RecordBufferConverter. TODO: remove when no longer needed.
6298 framesOut = min(framesOut,
6299 destinationFramesPossible(
6300 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006301 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6302 framesOut = activeTrack->mRecordBufferConverter->convert(
6303 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006304
6305 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6306 overrun = OVERRUN_FALSE;
6307 }
6308
6309 if (activeTrack->mFramesToDrop == 0) {
6310 if (framesOut > 0) {
6311 activeTrack->mSink.frameCount = framesOut;
6312 activeTrack->releaseBuffer(&activeTrack->mSink);
6313 }
6314 } else {
6315 // FIXME could do a partial drop of framesOut
6316 if (activeTrack->mFramesToDrop > 0) {
6317 activeTrack->mFramesToDrop -= framesOut;
6318 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006319 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006320 }
6321 } else {
6322 activeTrack->mFramesToDrop += framesOut;
6323 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6324 activeTrack->mSyncStartEvent->isCancelled()) {
6325 ALOGW("Synced record %s, session %d, trigger session %d",
6326 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6327 activeTrack->sessionId(),
6328 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006329 activeTrack->mSyncStartEvent->triggerSession() :
6330 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006331 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006332 }
6333 }
6334 }
6335
6336 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006337 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006338 }
6339 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006340
6341 switch (overrun) {
6342 case OVERRUN_TRUE:
6343 // client isn't retrieving buffers fast enough
6344 if (!activeTrack->setOverflow()) {
6345 nsecs_t now = systemTime();
6346 // FIXME should lastWarning per track?
6347 if ((now - lastWarning) > kWarningThrottleNs) {
6348 ALOGW("RecordThread: buffer overflow");
6349 lastWarning = now;
6350 }
6351 }
6352 break;
6353 case OVERRUN_FALSE:
6354 activeTrack->clearOverflow();
6355 break;
6356 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006357 break;
6358 }
6359
Andy Hung3f0c9022016-01-15 17:49:46 -08006360 // update frame information and push timestamp out
6361 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006362 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006363 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6364 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006365 }
6366
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006367unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006368 // enable changes in effect chain
6369 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006370 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006371 }
6372
Glenn Kasten93e471f2013-08-19 08:40:07 -07006373 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006374
6375 {
6376 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006377 for (size_t i = 0; i < mTracks.size(); i++) {
6378 sp<RecordTrack> track = mTracks[i];
6379 track->invalidate();
6380 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006381 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006382 mStartStopCond.broadcast();
6383 }
6384
6385 releaseWakeLock();
6386
6387 ALOGV("RecordThread %p exiting", this);
6388 return false;
6389}
6390
Glenn Kasten93e471f2013-08-19 08:40:07 -07006391void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006392{
6393 if (!mStandby) {
6394 inputStandBy();
6395 mStandby = true;
6396 }
6397}
6398
6399void AudioFlinger::RecordThread::inputStandBy()
6400{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006401 // Idle the fast capture if it's currently running
6402 if (mFastCapture != 0) {
6403 FastCaptureStateQueue *sq = mFastCapture->sq();
6404 FastCaptureState *state = sq->begin();
6405 if (!(state->mCommand & FastCaptureState::IDLE)) {
6406 state->mCommand = FastCaptureState::COLD_IDLE;
6407 state->mColdFutexAddr = &mFastCaptureFutex;
6408 state->mColdGen++;
6409 mFastCaptureFutex = 0;
6410 sq->end();
6411 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6412 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6413#if 0
6414 if (kUseFastCapture == FastCapture_Dynamic) {
6415 // FIXME
6416 }
6417#endif
6418#ifdef AUDIO_WATCHDOG
6419 // FIXME
6420#endif
6421 } else {
6422 sq->end(false /*didModify*/);
6423 }
6424 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006425 status_t result = mInput->stream->standby();
6426 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006427
6428 // If going into standby, flush the pipe source.
6429 if (mPipeSource.get() != nullptr) {
6430 const ssize_t flushed = mPipeSource->flush();
6431 if (flushed > 0) {
6432 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6433 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6434 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6435 }
6436 }
Eric Laurent81784c32012-11-19 14:55:58 -08006437}
6438
Glenn Kasten05997e22014-03-13 15:08:33 -07006439// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006440sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006441 const sp<AudioFlinger::Client>& client,
6442 uint32_t sampleRate,
6443 audio_format_t format,
6444 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006445 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006446 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006447 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006448 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006449 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006450 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006451 status_t *status,
6452 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006453{
Glenn Kasten74935e42013-12-19 08:56:45 -08006454 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006455 sp<RecordTrack> track;
6456 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006457 audio_input_flags_t inputFlags = mInput->flags;
6458
6459 // special case for FAST flag considered OK if fast capture is present
6460 if (hasFastCapture()) {
6461 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6462 }
6463
6464 // Check if requested flags are compatible with output stream flags
6465 if ((*flags & inputFlags) != *flags) {
6466 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6467 " input flags (%08x)",
6468 *flags, inputFlags);
6469 *flags = (audio_input_flags_t)(*flags & inputFlags);
6470 }
Eric Laurent81784c32012-11-19 14:55:58 -08006471
Glenn Kasten90e58b12013-07-31 16:16:02 -07006472 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006473 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006474 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006475 // we formerly checked for a callback handler (non-0 tid),
6476 // but that is no longer required for TRANSFER_OBTAIN mode
6477 //
Glenn Kasten74105912014-07-03 12:28:53 -07006478 // frame count is not specified, or is exactly the pipe depth
6479 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006480 // PCM data
6481 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006482 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006483 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006484 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006485 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006486 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006487 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006488 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006489 hasFastCapture() &&
6490 // there are sufficient fast track slots available
6491 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006492 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006493 // check compatibility with audio effects.
6494 Mutex::Autolock _l(mLock);
6495 // Do not accept FAST flag if the session has software effects
6496 sp<EffectChain> chain = getEffectChain_l(sessionId);
6497 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006498 audio_input_flags_t old = *flags;
6499 chain->checkInputFlagCompatibility(flags);
6500 if (old != *flags) {
6501 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6502 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006503 }
6504 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006505 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006506 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6507 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006508 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006509 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006510 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006511 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006512 frameCount, mFrameCount, mPipeFramesP2,
6513 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6514 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006515 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006516 }
6517 }
6518
6519 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006520 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006521 // fast track: frame count is exactly the pipe depth
6522 frameCount = mPipeFramesP2;
6523 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6524 *notificationFrames = mFrameCount;
6525 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006526 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6527 // or 20 ms if there is a fast capture
6528 // TODO This could be a roundupRatio inline, and const
6529 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6530 * sampleRate + mSampleRate - 1) / mSampleRate;
6531 // minimum number of notification periods is at least kMinNotifications,
6532 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6533 static const size_t kMinNotifications = 3;
6534 static const uint32_t kMinMs = 30;
6535 // TODO This could be a roundupRatio inline
6536 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6537 // TODO This could be a roundupRatio inline
6538 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6539 maxNotificationFrames;
6540 const size_t minFrameCount = maxNotificationFrames *
6541 max(kMinNotifications, minNotificationsByMs);
6542 frameCount = max(frameCount, minFrameCount);
6543 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6544 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006545 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006546 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006547 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006548
Glenn Kasten15e57982013-09-24 11:52:37 -07006549 lStatus = initCheck();
6550 if (lStatus != NO_ERROR) {
6551 ALOGE("createRecordTrack_l() audio driver not initialized");
6552 goto Exit;
6553 }
Eric Laurent81784c32012-11-19 14:55:58 -08006554
6555 { // scope for mLock
6556 Mutex::Autolock _l(mLock);
6557
6558 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006559 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006560 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006561
Glenn Kasten03003332013-08-06 15:40:54 -07006562 lStatus = track->initCheck();
6563 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006564 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006565 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006566 goto Exit;
6567 }
6568 mTracks.add(track);
6569
6570 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6571 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6572 mAudioFlinger->btNrecIsOff();
6573 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6574 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006575
Eric Laurent05067782016-06-01 18:27:28 -07006576 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006577 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6578 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6579 // so ask activity manager to do this on our behalf
6580 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6581 }
Eric Laurent81784c32012-11-19 14:55:58 -08006582 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006583
Eric Laurent81784c32012-11-19 14:55:58 -08006584 lStatus = NO_ERROR;
6585
6586Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006587 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006588 return track;
6589}
6590
6591status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6592 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006593 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006594{
6595 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6596 sp<ThreadBase> strongMe = this;
6597 status_t status = NO_ERROR;
6598
6599 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006600 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006601 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006602 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006603 triggerSession,
6604 recordTrack->sessionId(),
6605 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006606 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006607 // Sync event can be cancelled by the trigger session if the track is not in a
6608 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006609 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006610 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006611 } else {
6612 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006613 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006614 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006615 }
6616 }
6617
6618 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006619 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006620 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006621 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6622 if (recordTrack->mState == TrackBase::PAUSING) {
6623 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006624 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006625 } else {
6626 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006627 }
6628 return status;
6629 }
6630
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006631 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6632 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6633 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006634 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006635 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006636 status_t status = NO_ERROR;
6637 if (recordTrack->isExternalTrack()) {
6638 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006639 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006640 mLock.lock();
6641 // FIXME should verify that recordTrack is still in mActiveTracks
6642 if (status != NO_ERROR) {
6643 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006644 recordTrack->clearSyncStartEvent();
6645 ALOGV("RecordThread::start error %d", status);
6646 return status;
6647 }
Eric Laurent81784c32012-11-19 14:55:58 -08006648 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006649 // Catch up with current buffer indices if thread is already running.
6650 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6651 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6652 // see previously buffered data before it called start(), but with greater risk of overrun.
6653
Andy Hung73c02e42015-03-29 01:13:58 -07006654 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006655 // clear any converter state as new data will be discontinuous
6656 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006657 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006658 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006659 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006660 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006661 ALOGV("Record failed to start");
6662 status = BAD_VALUE;
6663 goto startError;
6664 }
Eric Laurent81784c32012-11-19 14:55:58 -08006665 return status;
6666 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006667
Eric Laurent81784c32012-11-19 14:55:58 -08006668startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006669 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006670 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006671 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006672 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006673 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006674 return status;
6675}
6676
Eric Laurent81784c32012-11-19 14:55:58 -08006677void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6678{
6679 sp<SyncEvent> strongEvent = event.promote();
6680
6681 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006682 sp<RefBase> ptr = strongEvent->cookie().promote();
6683 if (ptr != 0) {
6684 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6685 recordTrack->handleSyncStartEvent(strongEvent);
6686 }
Eric Laurent81784c32012-11-19 14:55:58 -08006687 }
6688}
6689
Glenn Kastena8356f62013-07-25 14:37:52 -07006690bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006691 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006692 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006693 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006694 return false;
6695 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006696 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006697 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006698 // signal thread to stop
6699 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006700 // do not wait for mStartStopCond if exiting
6701 if (exitPending()) {
6702 return true;
6703 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006704 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006705 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006706 // if we have been restarted, recordTrack is in mActiveTracks here
6707 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006708 ALOGV("Record stopped OK");
6709 return true;
6710 }
6711 return false;
6712}
6713
Glenn Kasten0f11b512014-01-31 16:18:54 -08006714bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006715{
6716 return false;
6717}
6718
Glenn Kasten0f11b512014-01-31 16:18:54 -08006719status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006720{
6721#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6722 if (!isValidSyncEvent(event)) {
6723 return BAD_VALUE;
6724 }
6725
Glenn Kastend848eb42016-03-08 13:42:11 -08006726 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006727 status_t ret = NAME_NOT_FOUND;
6728
6729 Mutex::Autolock _l(mLock);
6730
6731 for (size_t i = 0; i < mTracks.size(); i++) {
6732 sp<RecordTrack> track = mTracks[i];
6733 if (eventSession == track->sessionId()) {
6734 (void) track->setSyncEvent(event);
6735 ret = NO_ERROR;
6736 }
6737 }
6738 return ret;
6739#else
6740 return BAD_VALUE;
6741#endif
6742}
6743
6744// destroyTrack_l() must be called with ThreadBase::mLock held
6745void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6746{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 track->terminate();
6748 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006749 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006750 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006751 removeTrack_l(track);
6752 }
6753}
6754
6755void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6756{
6757 mTracks.remove(track);
6758 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006759 if (track->isFastTrack()) {
6760 ALOG_ASSERT(!mFastTrackAvail);
6761 mFastTrackAvail = true;
6762 }
Eric Laurent81784c32012-11-19 14:55:58 -08006763}
6764
6765void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6766{
6767 dumpInternals(fd, args);
6768 dumpTracks(fd, args);
6769 dumpEffectChains(fd, args);
6770}
6771
6772void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6773{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006774 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006775
Glenn Kasten44182c22015-03-05 17:12:23 -08006776 dumpBase(fd, args);
6777
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006778 AudioStreamIn *input = mInput;
6779 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6780 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6781 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006782 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006783 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006784 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006785 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006786 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006787
Glenn Kasten2f90c512015-12-02 11:40:09 -08006788 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6789 // while we are dumping it. It may be inconsistent, but it won't mutate!
6790 // This is a large object so we place it on the heap.
6791 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6792 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6793 copy->dump(fd);
6794 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006795}
6796
Glenn Kasten0f11b512014-01-31 16:18:54 -08006797void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006798{
6799 const size_t SIZE = 256;
6800 char buffer[SIZE];
6801 String8 result;
6802
Marco Nelissenb2208842014-02-07 14:00:50 -08006803 size_t numtracks = mTracks.size();
6804 size_t numactive = mActiveTracks.size();
6805 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006806 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006807 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006808 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006809 RecordTrack::appendDumpHeader(result);
6810 for (size_t i = 0; i < numtracks ; ++i) {
6811 sp<RecordTrack> track = mTracks[i];
6812 if (track != 0) {
6813 bool active = mActiveTracks.indexOf(track) >= 0;
6814 if (active) {
6815 numactiveseen++;
6816 }
6817 track->dump(buffer, SIZE, active);
6818 result.append(buffer);
6819 }
Eric Laurent81784c32012-11-19 14:55:58 -08006820 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006821 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006822 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006823 }
6824
Marco Nelissenb2208842014-02-07 14:00:50 -08006825 if (numactiveseen != numactive) {
6826 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6827 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006828 result.append(buffer);
6829 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006830 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006831 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006832 if (mTracks.indexOf(track) < 0) {
6833 track->dump(buffer, SIZE, true);
6834 result.append(buffer);
6835 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006836 }
Eric Laurent81784c32012-11-19 14:55:58 -08006837
6838 }
6839 write(fd, result.string(), result.size());
6840}
6841
Andy Hung73c02e42015-03-29 01:13:58 -07006842
6843void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6844{
6845 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6846 RecordThread *recordThread = (RecordThread *) threadBase.get();
6847 mRsmpInFront = recordThread->mRsmpInRear;
6848 mRsmpInUnrel = 0;
6849}
6850
6851void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6852 size_t *framesAvailable, bool *hasOverrun)
6853{
6854 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6855 RecordThread *recordThread = (RecordThread *) threadBase.get();
6856 const int32_t rear = recordThread->mRsmpInRear;
6857 const int32_t front = mRsmpInFront;
6858 const ssize_t filled = rear - front;
6859
6860 size_t framesIn;
6861 bool overrun = false;
6862 if (filled < 0) {
6863 // should not happen, but treat like a massive overrun and re-sync
6864 framesIn = 0;
6865 mRsmpInFront = rear;
6866 overrun = true;
6867 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6868 framesIn = (size_t) filled;
6869 } else {
6870 // client is not keeping up with server, but give it latest data
6871 framesIn = recordThread->mRsmpInFrames;
6872 mRsmpInFront = /* front = */ rear - framesIn;
6873 overrun = true;
6874 }
6875 if (framesAvailable != NULL) {
6876 *framesAvailable = framesIn;
6877 }
6878 if (hasOverrun != NULL) {
6879 *hasOverrun = overrun;
6880 }
6881}
6882
Eric Laurent81784c32012-11-19 14:55:58 -08006883// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006884status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006885 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006886{
Andy Hung73c02e42015-03-29 01:13:58 -07006887 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006888 if (threadBase == 0) {
6889 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006890 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006891 return NOT_ENOUGH_DATA;
6892 }
6893 RecordThread *recordThread = (RecordThread *) threadBase.get();
6894 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006895 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006896 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006897 // FIXME should not be P2 (don't want to increase latency)
6898 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006899 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006900 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006901 front &= recordThread->mRsmpInFramesP2 - 1;
6902 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006903 if (part1 > (size_t) filled) {
6904 part1 = filled;
6905 }
6906 size_t ask = buffer->frameCount;
6907 ALOG_ASSERT(ask > 0);
6908 if (part1 > ask) {
6909 part1 = ask;
6910 }
6911 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006912 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006913 buffer->raw = NULL;
6914 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006915 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006916 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006917 }
6918
Andy Hung57446612015-04-19 23:56:46 -07006919 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006920 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006921 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006922 return NO_ERROR;
6923}
6924
6925// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006926void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6927 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006928{
Glenn Kasten85948432013-08-19 12:09:05 -07006929 size_t stepCount = buffer->frameCount;
6930 if (stepCount == 0) {
6931 return;
6932 }
Andy Hung73c02e42015-03-29 01:13:58 -07006933 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6934 mRsmpInUnrel -= stepCount;
6935 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006936 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006937 buffer->frameCount = 0;
6938}
6939
Andy Hung97a893e2015-03-29 01:03:07 -07006940
Eric Laurent10351942014-05-08 18:49:52 -07006941bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6942 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006943{
6944 bool reconfig = false;
6945
Eric Laurent10351942014-05-08 18:49:52 -07006946 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006947
Eric Laurent10351942014-05-08 18:49:52 -07006948 audio_format_t reqFormat = mFormat;
6949 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006950 // 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 -07006951 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6952
6953 AudioParameter param = AudioParameter(keyValuePair);
6954 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006955
6956 // scope for AutoPark extends to end of method
6957 AutoPark<FastCapture> park(mFastCapture);
6958
Eric Laurent10351942014-05-08 18:49:52 -07006959 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6960 // channel count change can be requested. Do we mandate the first client defines the
6961 // HAL sampling rate and channel count or do we allow changes on the fly?
6962 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6963 samplingRate = value;
6964 reconfig = true;
6965 }
6966 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006967 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006968 status = BAD_VALUE;
6969 } else {
6970 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006971 reconfig = true;
6972 }
Eric Laurent10351942014-05-08 18:49:52 -07006973 }
6974 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6975 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006976 if (!audio_is_input_channel(mask) ||
6977 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006978 status = BAD_VALUE;
6979 } else {
6980 channelMask = mask;
6981 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006982 }
Eric Laurent10351942014-05-08 18:49:52 -07006983 }
6984 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6985 // do not accept frame count changes if tracks are open as the track buffer
6986 // size depends on frame count and correct behavior would not be guaranteed
6987 // if frame count is changed after track creation
6988 if (mActiveTracks.size() > 0) {
6989 status = INVALID_OPERATION;
6990 } else {
6991 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006992 }
Eric Laurent10351942014-05-08 18:49:52 -07006993 }
6994 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6995 // forward device change to effects that have requested to be
6996 // aware of attached audio device.
6997 for (size_t i = 0; i < mEffectChains.size(); i++) {
6998 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08006999 }
Eric Laurent81784c32012-11-19 14:55:58 -08007000
Eric Laurent10351942014-05-08 18:49:52 -07007001 // store input device and output device but do not forward output device to audio HAL.
7002 // Note that status is ignored by the caller for output device
7003 // (see AudioFlinger::setParameters()
7004 if (audio_is_output_devices(value)) {
7005 mOutDevice = value;
7006 status = BAD_VALUE;
7007 } else {
7008 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007009 if (value != AUDIO_DEVICE_NONE) {
7010 mPrevInDevice = value;
7011 }
Eric Laurent10351942014-05-08 18:49:52 -07007012 // disable AEC and NS if the device is a BT SCO headset supporting those
7013 // pre processings
7014 if (mTracks.size() > 0) {
7015 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7016 mAudioFlinger->btNrecIsOff();
7017 for (size_t i = 0; i < mTracks.size(); i++) {
7018 sp<RecordTrack> track = mTracks[i];
7019 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7020 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007021 }
7022 }
7023 }
Eric Laurent10351942014-05-08 18:49:52 -07007024 }
7025 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7026 mAudioSource != (audio_source_t)value) {
7027 // forward device change to effects that have requested to be
7028 // aware of attached audio device.
7029 for (size_t i = 0; i < mEffectChains.size(); i++) {
7030 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007031 }
Eric Laurent10351942014-05-08 18:49:52 -07007032 mAudioSource = (audio_source_t)value;
7033 }
Glenn Kastene198c362013-08-13 09:13:36 -07007034
Eric Laurent10351942014-05-08 18:49:52 -07007035 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007036 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007037 if (status == INVALID_OPERATION) {
7038 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007039 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007040 }
7041 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007042 if (status == BAD_VALUE) {
7043 uint32_t sRate;
7044 audio_channel_mask_t channelMask;
7045 audio_format_t format;
7046 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7047 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7048 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7049 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7050 status = NO_ERROR;
7051 }
Eric Laurent81784c32012-11-19 14:55:58 -08007052 }
Eric Laurent10351942014-05-08 18:49:52 -07007053 if (status == NO_ERROR) {
7054 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007055 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007056 }
7057 }
Eric Laurent81784c32012-11-19 14:55:58 -08007058 }
Eric Laurent10351942014-05-08 18:49:52 -07007059
Eric Laurent81784c32012-11-19 14:55:58 -08007060 return reconfig;
7061}
7062
7063String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7064{
Eric Laurent81784c32012-11-19 14:55:58 -08007065 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007066 if (initCheck() == NO_ERROR) {
7067 String8 out_s8;
7068 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7069 return out_s8;
7070 }
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007072 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007073}
7074
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007075void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007076 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7077
7078 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007079
7080 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007081 case AUDIO_INPUT_OPENED:
7082 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007083 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007084 desc->mChannelMask = mChannelMask;
7085 desc->mSamplingRate = mSampleRate;
7086 desc->mFormat = mFormat;
7087 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007088 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007089 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007090 break;
7091
Eric Laurent73e26b62015-04-27 16:55:58 -07007092 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007093 default:
7094 break;
7095 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007096 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007097}
7098
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007099void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007100{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007101 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7102 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007103 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007104 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007105 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007106 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7107 result = mInput->stream->getFrameSize(&mFrameSize);
7108 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7109 result = mInput->stream->getBufferSize(&mBufferSize);
7110 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007111 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007112 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007113 // 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 -07007114 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007115 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007116 // A larger value should allow more old data to be read after a track calls start(),
7117 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007118 //
7119 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007120 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007121 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007122 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007123 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007124
7125 // TODO optimize audio capture buffer sizes ...
7126 // Here we calculate the size of the sliding buffer used as a source
7127 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7128 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7129 // be better to have it derived from the pipe depth in the long term.
7130 // The current value is higher than necessary. However it should not add to latency.
7131
Glenn Kasten85948432013-08-19 12:09:05 -07007132 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007133 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7134 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7135 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007136
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007137 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7138 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007139}
7140
Glenn Kasten5f972c02014-01-13 09:59:31 -08007141uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007142{
7143 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007144 uint32_t result;
7145 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7146 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007147 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007148 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007149}
7150
Eric Laurent4c415062016-06-17 16:14:16 -07007151// hasAudioSession_l() must be called with ThreadBase::mLock held
7152uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007153{
Eric Laurent81784c32012-11-19 14:55:58 -08007154 uint32_t result = 0;
7155 if (getEffectChain_l(sessionId) != 0) {
7156 result = EFFECT_SESSION;
7157 }
7158
7159 for (size_t i = 0; i < mTracks.size(); ++i) {
7160 if (sessionId == mTracks[i]->sessionId()) {
7161 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007162 if (mTracks[i]->isFastTrack()) {
7163 result |= FAST_SESSION;
7164 }
Eric Laurent81784c32012-11-19 14:55:58 -08007165 break;
7166 }
7167 }
7168
7169 return result;
7170}
7171
Glenn Kastend848eb42016-03-08 13:42:11 -08007172KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007173{
Glenn Kastend848eb42016-03-08 13:42:11 -08007174 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007175 Mutex::Autolock _l(mLock);
7176 for (size_t j = 0; j < mTracks.size(); ++j) {
7177 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007178 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007179 if (ids.indexOfKey(sessionId) < 0) {
7180 ids.add(sessionId, true);
7181 }
7182 }
7183 return ids;
7184}
7185
7186AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7187{
7188 Mutex::Autolock _l(mLock);
7189 AudioStreamIn *input = mInput;
7190 mInput = NULL;
7191 return input;
7192}
7193
7194// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007195sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007196{
7197 if (mInput == NULL) {
7198 return NULL;
7199 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007200 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007201}
7202
7203status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7204{
7205 // only one chain per input thread
7206 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007207 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007208 return INVALID_OPERATION;
7209 }
7210 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007211 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007212 chain->setInBuffer(NULL);
7213 chain->setOutBuffer(NULL);
7214
7215 checkSuspendOnAddEffectChain_l(chain);
7216
Eric Laurent1b928682014-10-02 19:41:47 -07007217 // make sure enabled pre processing effects state is communicated to the HAL as we
7218 // just moved them to a new input stream.
7219 chain->syncHalEffectsState();
7220
Eric Laurent81784c32012-11-19 14:55:58 -08007221 mEffectChains.add(chain);
7222
7223 return NO_ERROR;
7224}
7225
7226size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7227{
7228 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7229 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007230 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007231 chain.get(), mEffectChains.size(), this);
7232 if (mEffectChains.size() == 1) {
7233 mEffectChains.removeAt(0);
7234 }
7235 return 0;
7236}
7237
Eric Laurent1c333e22014-05-20 10:48:17 -07007238status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7239 audio_patch_handle_t *handle)
7240{
7241 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007242
7243 // store new device and send to effects
7244 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007245 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007246 for (size_t i = 0; i < mEffectChains.size(); i++) {
7247 mEffectChains[i]->setDevice_l(mInDevice);
7248 }
7249
7250 // disable AEC and NS if the device is a BT SCO headset supporting those
7251 // pre processings
7252 if (mTracks.size() > 0) {
7253 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7254 mAudioFlinger->btNrecIsOff();
7255 for (size_t i = 0; i < mTracks.size(); i++) {
7256 sp<RecordTrack> track = mTracks[i];
7257 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7258 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7259 }
7260 }
7261
7262 // store new source and send to effects
7263 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7264 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007265 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007266 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007267 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007268 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007269
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007270 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007271 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7272 status = hwDevice->createAudioPatch(patch->num_sources,
7273 patch->sources,
7274 patch->num_sinks,
7275 patch->sinks,
7276 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007277 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007278 char *address;
7279 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7280 address = audio_device_address_to_parameter(
7281 patch->sources[0].ext.device.type,
7282 patch->sources[0].ext.device.address);
7283 } else {
7284 address = (char *)calloc(1, 1);
7285 }
7286 AudioParameter param = AudioParameter(String8(address));
7287 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007288 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007289 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007290 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007291 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007292 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007293 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007294 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007295
Eric Laurente8726fe2015-06-26 09:39:24 -07007296 if (mInDevice != mPrevInDevice) {
7297 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7298 mPrevInDevice = mInDevice;
7299 }
Eric Laurent296fb132015-05-01 11:38:42 -07007300
Eric Laurent1c333e22014-05-20 10:48:17 -07007301 return status;
7302}
7303
7304status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7305{
7306 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007307
7308 mInDevice = AUDIO_DEVICE_NONE;
7309
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007310 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007311 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7312 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007313 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007314 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007315 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007316 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007317 }
7318 return status;
7319}
7320
Eric Laurent83b88082014-06-20 18:31:16 -07007321void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7322{
7323 Mutex::Autolock _l(mLock);
7324 mTracks.add(record);
7325}
7326
7327void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7328{
7329 Mutex::Autolock _l(mLock);
7330 destroyTrack_l(record);
7331}
7332
7333void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7334{
7335 ThreadBase::getAudioPortConfig(config);
7336 config->role = AUDIO_PORT_ROLE_SINK;
7337 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7338 config->ext.mix.usecase.source = mAudioSource;
7339}
Eric Laurent1c333e22014-05-20 10:48:17 -07007340
Glenn Kasten63238ef2015-03-02 15:50:29 -08007341} // namespace android