blob: b1ede3010ca1209094b75ffbb05b59d5c5902bbf [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;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001267 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001268
1269 lStatus = initCheck();
1270 if (lStatus != NO_ERROR) {
1271 ALOGW("createEffect_l() Audio driver not initialized.");
1272 goto Exit;
1273 }
1274
Eric Laurent81784c32012-11-19 14:55:58 -08001275 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1276
1277 { // scope for mLock
1278 Mutex::Autolock _l(mLock);
1279
Eric Laurent4c415062016-06-17 16:14:16 -07001280 lStatus = checkEffectCompatibility_l(desc, sessionId);
1281 if (lStatus != NO_ERROR) {
1282 goto Exit;
1283 }
1284
Eric Laurent81784c32012-11-19 14:55:58 -08001285 // check for existing effect chain with the requested audio session
1286 chain = getEffectChain_l(sessionId);
1287 if (chain == 0) {
1288 // create a new chain for this session
1289 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1290 chain = new EffectChain(this, sessionId);
1291 addEffectChain_l(chain);
1292 chain->setStrategy(getStrategyForSession_l(sessionId));
1293 chainCreated = true;
1294 } else {
1295 effect = chain->getEffectFromDesc_l(desc);
1296 }
1297
1298 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1299
1300 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001301 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001302 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001303 lStatus = AudioSystem::registerEffect(
1304 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001305 if (lStatus != NO_ERROR) {
1306 goto Exit;
1307 }
1308 effectRegistered = true;
1309 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001310 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001311 if (lStatus != NO_ERROR) {
1312 goto Exit;
1313 }
1314 effectCreated = true;
1315
1316 effect->setDevice(mOutDevice);
1317 effect->setDevice(mInDevice);
1318 effect->setMode(mAudioFlinger->getMode());
1319 effect->setAudioSource(mAudioSource);
1320 }
1321 // create effect handle and connect it to effect module
1322 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001323 lStatus = handle->initCheck();
1324 if (lStatus == OK) {
1325 lStatus = effect->addHandle(handle.get());
1326 }
Eric Laurent81784c32012-11-19 14:55:58 -08001327 if (enabled != NULL) {
1328 *enabled = (int)effect->isEnabled();
1329 }
1330 }
1331
1332Exit:
1333 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1334 Mutex::Autolock _l(mLock);
1335 if (effectCreated) {
1336 chain->removeEffect_l(effect);
1337 }
1338 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001339 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001340 }
1341 if (chainCreated) {
1342 removeEffectChain_l(chain);
1343 }
1344 handle.clear();
1345 }
1346
Glenn Kasten9156ef32013-08-06 15:39:08 -07001347 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001348 return handle;
1349}
1350
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001351void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1352 bool unpinIfLast)
1353{
1354 bool remove = false;
1355 sp<EffectModule> effect;
1356 {
1357 Mutex::Autolock _l(mLock);
1358
1359 effect = handle->effect().promote();
1360 if (effect == 0) {
1361 return;
1362 }
1363 // restore suspended effects if the disconnected handle was enabled and the last one.
1364 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1365 if (remove) {
1366 removeEffect_l(effect, true);
1367 }
1368 }
1369 if (remove) {
1370 mAudioFlinger->updateOrphanEffectChains(effect);
1371 AudioSystem::unregisterEffect(effect->id());
1372 if (handle->enabled()) {
1373 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1374 }
1375 }
1376}
1377
Glenn Kastend848eb42016-03-08 13:42:11 -08001378sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1379 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001380{
1381 Mutex::Autolock _l(mLock);
1382 return getEffect_l(sessionId, effectId);
1383}
1384
Glenn Kastend848eb42016-03-08 13:42:11 -08001385sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1386 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001387{
1388 sp<EffectChain> chain = getEffectChain_l(sessionId);
1389 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1390}
1391
1392// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1393// PlaybackThread::mLock held
1394status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1395{
1396 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001397 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001398 sp<EffectChain> chain = getEffectChain_l(sessionId);
1399 bool chainCreated = false;
1400
Eric Laurent5baf2af2013-09-12 17:37:00 -07001401 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1402 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1403 this, effect->desc().name, effect->desc().flags);
1404
Eric Laurent81784c32012-11-19 14:55:58 -08001405 if (chain == 0) {
1406 // create a new chain for this session
1407 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1408 chain = new EffectChain(this, sessionId);
1409 addEffectChain_l(chain);
1410 chain->setStrategy(getStrategyForSession_l(sessionId));
1411 chainCreated = true;
1412 }
1413 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1414
1415 if (chain->getEffectFromId_l(effect->id()) != 0) {
1416 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1417 this, effect->desc().name, chain.get());
1418 return BAD_VALUE;
1419 }
1420
Eric Laurent5baf2af2013-09-12 17:37:00 -07001421 effect->setOffloaded(mType == OFFLOAD, mId);
1422
Eric Laurent81784c32012-11-19 14:55:58 -08001423 status_t status = chain->addEffect_l(effect);
1424 if (status != NO_ERROR) {
1425 if (chainCreated) {
1426 removeEffectChain_l(chain);
1427 }
1428 return status;
1429 }
1430
1431 effect->setDevice(mOutDevice);
1432 effect->setDevice(mInDevice);
1433 effect->setMode(mAudioFlinger->getMode());
1434 effect->setAudioSource(mAudioSource);
1435 return NO_ERROR;
1436}
1437
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001438void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001439
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001440 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001441 effect_descriptor_t desc = effect->desc();
1442 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1443 detachAuxEffect_l(effect->id());
1444 }
1445
1446 sp<EffectChain> chain = effect->chain().promote();
1447 if (chain != 0) {
1448 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001449 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001450 removeEffectChain_l(chain);
1451 }
1452 } else {
1453 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1454 }
1455}
1456
1457void AudioFlinger::ThreadBase::lockEffectChains_l(
1458 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1459{
1460 effectChains = mEffectChains;
1461 for (size_t i = 0; i < mEffectChains.size(); i++) {
1462 mEffectChains[i]->lock();
1463 }
1464}
1465
1466void AudioFlinger::ThreadBase::unlockEffectChains(
1467 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1468{
1469 for (size_t i = 0; i < effectChains.size(); i++) {
1470 effectChains[i]->unlock();
1471 }
1472}
1473
Glenn Kastend848eb42016-03-08 13:42:11 -08001474sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001475{
1476 Mutex::Autolock _l(mLock);
1477 return getEffectChain_l(sessionId);
1478}
1479
Glenn Kastend848eb42016-03-08 13:42:11 -08001480sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1481 const
Eric Laurent81784c32012-11-19 14:55:58 -08001482{
1483 size_t size = mEffectChains.size();
1484 for (size_t i = 0; i < size; i++) {
1485 if (mEffectChains[i]->sessionId() == sessionId) {
1486 return mEffectChains[i];
1487 }
1488 }
1489 return 0;
1490}
1491
1492void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1493{
1494 Mutex::Autolock _l(mLock);
1495 size_t size = mEffectChains.size();
1496 for (size_t i = 0; i < size; i++) {
1497 mEffectChains[i]->setMode_l(mode);
1498 }
1499}
1500
Eric Laurent83b88082014-06-20 18:31:16 -07001501void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1502{
1503 config->type = AUDIO_PORT_TYPE_MIX;
1504 config->ext.mix.handle = mId;
1505 config->sample_rate = mSampleRate;
1506 config->format = mFormat;
1507 config->channel_mask = mChannelMask;
1508 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1509 AUDIO_PORT_CONFIG_FORMAT;
1510}
1511
Eric Laurent72e3f392015-05-20 14:43:50 -07001512void AudioFlinger::ThreadBase::systemReady()
1513{
1514 Mutex::Autolock _l(mLock);
1515 if (mSystemReady) {
1516 return;
1517 }
1518 mSystemReady = true;
1519
1520 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1521 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1522 }
1523 mPendingConfigEvents.clear();
1524}
1525
Andy Hungdae27702016-10-31 14:01:16 -07001526template <typename T>
1527ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1528 ssize_t index = mActiveTracks.indexOf(track);
1529 if (index >= 0) {
1530 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1531 return index;
1532 }
1533 mActiveTracksGeneration++;
1534 mLatestActiveTrack = track;
1535 ++mBatteryCounter[track->uid()].second;
1536 return mActiveTracks.add(track);
1537}
1538
1539template <typename T>
1540ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1541 ssize_t index = mActiveTracks.remove(track);
1542 if (index < 0) {
1543 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1544 return index;
1545 }
1546 mActiveTracksGeneration++;
1547 --mBatteryCounter[track->uid()].second;
1548 // mLatestActiveTrack is not cleared even if is the same as track.
1549 return index;
1550}
1551
1552template <typename T>
1553void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1554 for (const sp<T> &track : mActiveTracks) {
1555 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1556 }
1557 mLastActiveTracksGeneration = mActiveTracksGeneration;
1558 mActiveTracks.clear();
1559 mLatestActiveTrack.clear();
1560 mBatteryCounter.clear();
1561}
1562
1563template <typename T>
1564void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1565 sp<ThreadBase> thread, bool force) {
1566 // Updates ActiveTracks client uids to the thread wakelock.
1567 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1568 thread->updateWakeLockUids_l(getWakeLockUids());
1569 mLastActiveTracksGeneration = mActiveTracksGeneration;
1570 }
1571
1572 // Updates BatteryNotifier uids
1573 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1574 const uid_t uid = it->first;
1575 ssize_t &previous = it->second.first;
1576 ssize_t &current = it->second.second;
1577 if (current > 0) {
1578 if (previous == 0) {
1579 BatteryNotifier::getInstance().noteStartAudio(uid);
1580 }
1581 previous = current;
1582 ++it;
1583 } else if (current == 0) {
1584 if (previous > 0) {
1585 BatteryNotifier::getInstance().noteStopAudio(uid);
1586 }
1587 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1588 } else /* (current < 0) */ {
1589 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1590 }
1591 }
1592}
Eric Laurent83b88082014-06-20 18:31:16 -07001593
Eric Laurent81784c32012-11-19 14:55:58 -08001594// ----------------------------------------------------------------------------
1595// Playback
1596// ----------------------------------------------------------------------------
1597
1598AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1599 AudioStreamOut* output,
1600 audio_io_handle_t id,
1601 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001602 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001603 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001604 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001605 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001606 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001607 mMixerBuffer(NULL),
1608 mMixerBufferSize(0),
1609 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1610 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001611 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001612 mEffectBuffer(NULL),
1613 mEffectBufferSize(0),
1614 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1615 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001616 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001617 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001618 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001619 // mStreamTypes[] initialized in constructor body
1620 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001621 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001622 mMixerStatus(MIXER_IDLE),
1623 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001624 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001625 mBytesRemaining(0),
1626 mCurrentWriteLength(0),
1627 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001628 mWriteAckSequence(0),
1629 mDrainSequence(0),
Eric Laurentede6c3b2013-09-19 14:37:46 -07001630 mSignalPending(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001631 mScreenState(AudioFlinger::mScreenState),
1632 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001633 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001634 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001635{
Glenn Kastend7dca052015-03-05 16:05:54 -08001636 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1637 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001638
1639 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1640 // it would be safer to explicitly pass initial masterVolume/masterMute as
1641 // parameter.
1642 //
1643 // If the HAL we are using has support for master volume or master mute,
1644 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1645 // and the mute set to false).
1646 mMasterVolume = audioFlinger->masterVolume_l();
1647 mMasterMute = audioFlinger->masterMute_l();
1648 if (mOutput && mOutput->audioHwDev) {
1649 if (mOutput->audioHwDev->canSetMasterVolume()) {
1650 mMasterVolume = 1.0;
1651 }
1652
1653 if (mOutput->audioHwDev->canSetMasterMute()) {
1654 mMasterMute = false;
1655 }
1656 }
1657
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001658 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001659
Eric Laurent223fd5c2014-11-11 13:43:36 -08001660 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001661 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001662 stream = (audio_stream_type_t) (stream + 1)) {
1663 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1664 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1665 }
Eric Laurent81784c32012-11-19 14:55:58 -08001666}
1667
1668AudioFlinger::PlaybackThread::~PlaybackThread()
1669{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001670 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001671 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001672 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001673 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001674}
1675
1676void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1677{
1678 dumpInternals(fd, args);
1679 dumpTracks(fd, args);
1680 dumpEffectChains(fd, args);
Andy Hung2148bf02016-11-28 19:01:02 -08001681 mLocalLog.dump(fd, args, " " /* prefix */);
Eric Laurent81784c32012-11-19 14:55:58 -08001682}
1683
Glenn Kasten0f11b512014-01-31 16:18:54 -08001684void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001685{
1686 const size_t SIZE = 256;
1687 char buffer[SIZE];
1688 String8 result;
1689
Marco Nelissenb2208842014-02-07 14:00:50 -08001690 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001691 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1692 const stream_type_t *st = &mStreamTypes[i];
1693 if (i > 0) {
1694 result.appendFormat(", ");
1695 }
1696 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1697 if (st->mute) {
1698 result.append("M");
1699 }
1700 }
1701 result.append("\n");
1702 write(fd, result.string(), result.length());
1703 result.clear();
1704
Eric Laurent81784c32012-11-19 14:55:58 -08001705 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1706 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001707 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001708 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001709
1710 size_t numtracks = mTracks.size();
1711 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001712 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001713 size_t numactiveseen = 0;
1714 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001715 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001716 Track::appendDumpHeader(result);
1717 for (size_t i = 0; i < numtracks; ++i) {
1718 sp<Track> track = mTracks[i];
1719 if (track != 0) {
1720 bool active = mActiveTracks.indexOf(track) >= 0;
1721 if (active) {
1722 numactiveseen++;
1723 }
1724 track->dump(buffer, SIZE, active);
1725 result.append(buffer);
1726 }
1727 }
1728 } else {
1729 result.append("\n");
1730 }
1731 if (numactiveseen != numactive) {
1732 // some tracks in the active list were not in the tracks list
1733 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1734 " not in the track list\n");
1735 result.append(buffer);
1736 Track::appendDumpHeader(result);
1737 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001738 sp<Track> track = mActiveTracks[i];
1739 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001740 track->dump(buffer, SIZE, true);
1741 result.append(buffer);
1742 }
1743 }
1744 }
1745
1746 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001747}
1748
1749void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1750{
Glenn Kasten97b7b752014-09-28 13:04:24 -07001751 dprintf(fd, "\nOutput thread %p type %d (%s):\n", this, type(), threadTypeToString(type()));
Glenn Kasten44182c22015-03-05 17:12:23 -08001752
1753 dumpBase(fd, args);
1754
Elliott Hughes87cebad2014-05-22 10:14:43 -07001755 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001756 dprintf(fd, " Last write occurred (msecs): %llu\n",
1757 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001758 dprintf(fd, " Total writes: %d\n", mNumWrites);
1759 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1760 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1761 dprintf(fd, " Suspend count: %d\n", mSuspended);
1762 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1763 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1764 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1765 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001766 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001767 AudioStreamOut *output = mOutput;
1768 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001769 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1770 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001771 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1772 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1773 if (mPipeSink.get() != nullptr) {
1774 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1775 }
1776 if (output != nullptr) {
1777 dprintf(fd, " Hal stream dump:\n");
1778 (void)output->stream->dump(fd);
1779 }
Eric Laurent81784c32012-11-19 14:55:58 -08001780}
1781
1782// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001783
1784void AudioFlinger::PlaybackThread::onFirstRef()
1785{
Glenn Kastend7dca052015-03-05 16:05:54 -08001786 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001787}
1788
1789// ThreadBase virtuals
1790void AudioFlinger::PlaybackThread::preExit()
1791{
1792 ALOGV(" preExit()");
1793 // FIXME this is using hard-coded strings but in the future, this functionality will be
1794 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001795 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1796 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001797}
1798
1799// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1800sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1801 const sp<AudioFlinger::Client>& client,
1802 audio_stream_type_t streamType,
1803 uint32_t sampleRate,
1804 audio_format_t format,
1805 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001806 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001807 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001808 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001809 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001810 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001811 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001812 status_t *status,
1813 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001814{
Glenn Kasten74935e42013-12-19 08:56:45 -08001815 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001816 sp<Track> track;
1817 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001818 audio_output_flags_t outputFlags = mOutput->flags;
1819
1820 // special case for FAST flag considered OK if fast mixer is present
1821 if (hasFastMixer()) {
1822 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1823 }
1824
1825 // Check if requested flags are compatible with output stream flags
1826 if ((*flags & outputFlags) != *flags) {
1827 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1828 *flags, outputFlags);
1829 *flags = (audio_output_flags_t)(*flags & outputFlags);
1830 }
Eric Laurent81784c32012-11-19 14:55:58 -08001831
Eric Laurent81784c32012-11-19 14:55:58 -08001832 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001833 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001834 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001835 // PCM data
1836 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001837 // TODO: extract as a data library function that checks that a computationally
1838 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001839 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001840 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1841 (channelMask == AUDIO_CHANNEL_OUT_MONO
1842 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001843 // hardware sample rate
1844 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001845 // normal mixer has an associated fast mixer
1846 hasFastMixer() &&
1847 // there are sufficient fast track slots available
1848 (mFastTrackAvailMask != 0)
1849 // FIXME test that MixerThread for this fast track has a capable output HAL
1850 // FIXME add a permission test also?
1851 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001852 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1853 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001854 // read the fast track multiplier property the first time it is needed
1855 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1856 if (ok != 0) {
1857 ALOGE("%s pthread_once failed: %d", __func__, ok);
1858 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001859 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001860 }
Eric Laurent4c415062016-06-17 16:14:16 -07001861
1862 // check compatibility with audio effects.
1863 { // scope for mLock
1864 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001865 for (audio_session_t session : {
1866 AUDIO_SESSION_OUTPUT_STAGE,
1867 AUDIO_SESSION_OUTPUT_MIX,
1868 sessionId,
1869 }) {
1870 sp<EffectChain> chain = getEffectChain_l(session);
1871 if (chain.get() != nullptr) {
1872 audio_output_flags_t old = *flags;
1873 chain->checkOutputFlagCompatibility(flags);
1874 if (old != *flags) {
1875 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1876 (int)session, (int)old, (int)*flags);
1877 }
Eric Laurent4c415062016-06-17 16:14:16 -07001878 }
1879 }
1880 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001881 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001882 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1883 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001884 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001885 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1886 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001887 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001888 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001889 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001890 audio_is_linear_pcm(format),
1891 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001892 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001893 }
1894 }
1895 // For normal PCM streaming tracks, update minimum frame count.
1896 // For compatibility with AudioTrack calculation, buffer depth is forced
1897 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1898 // This is probably too conservative, but legacy application code may depend on it.
1899 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001900 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001901 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001902 // this must match AudioTrack.cpp calculateMinFrameCount().
1903 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001904 uint32_t latencyMs = 0;
1905 lStatus = mOutput->stream->getLatency(&latencyMs);
1906 if (lStatus != OK) {
1907 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1908 goto Exit;
1909 }
Eric Laurent81784c32012-11-19 14:55:58 -08001910 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1911 if (minBufCount < 2) {
1912 minBufCount = 2;
1913 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001914 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1915 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001916 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001917 minBufCount * sourceFramesNeededWithTimestretch(
1918 sampleRate, mNormalFrameCount,
1919 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001920 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001921 frameCount = minFrameCount;
1922 }
Eric Laurent81784c32012-11-19 14:55:58 -08001923 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001924 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001925
Glenn Kastenc3df8382014-03-13 15:05:25 -07001926 switch (mType) {
1927
1928 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001929 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001930 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001931 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1932 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001933 sampleRate, format, channelMask, mOutput, mFormat);
1934 lStatus = BAD_VALUE;
1935 goto Exit;
1936 }
1937 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001938 break;
1939
1940 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001941 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001942 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1943 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001944 sampleRate, format, channelMask, mOutput, mFormat);
1945 lStatus = BAD_VALUE;
1946 goto Exit;
1947 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001948 break;
1949
1950 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001951 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001952 ALOGE("createTrack_l() Bad parameter: format %#x \""
1953 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001954 format, mOutput, mFormat);
1955 lStatus = BAD_VALUE;
1956 goto Exit;
1957 }
Andy Hungcd044842014-08-07 11:04:34 -07001958 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001959 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1960 lStatus = BAD_VALUE;
1961 goto Exit;
1962 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001963 break;
1964
Eric Laurent81784c32012-11-19 14:55:58 -08001965 }
1966
1967 lStatus = initCheck();
1968 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001969 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001970 goto Exit;
1971 }
1972
1973 { // scope for mLock
1974 Mutex::Autolock _l(mLock);
1975
1976 // all tracks in same audio session must share the same routing strategy otherwise
1977 // conflicts will happen when tracks are moved from one output to another by audio policy
1978 // manager
1979 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
1980 for (size_t i = 0; i < mTracks.size(); ++i) {
1981 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07001982 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001983 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
1984 if (sessionId == t->sessionId() && strategy != actual) {
1985 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1986 strategy, actual);
1987 lStatus = BAD_VALUE;
1988 goto Exit;
1989 }
1990 }
1991 }
1992
Glenn Kastend79072e2016-01-06 08:41:20 -08001993 track = new Track(this, client, streamType, sampleRate, format,
1994 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001995 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07001996
Glenn Kasten03003332013-08-06 15:40:54 -07001997 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
1998 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08001999 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002000 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002001 goto Exit;
2002 }
2003 mTracks.add(track);
2004
2005 sp<EffectChain> chain = getEffectChain_l(sessionId);
2006 if (chain != 0) {
2007 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2008 track->setMainBuffer(chain->inBuffer());
2009 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2010 chain->incTrackCnt();
2011 }
2012
Eric Laurent05067782016-06-01 18:27:28 -07002013 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002014 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2015 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2016 // so ask activity manager to do this on our behalf
2017 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
2018 }
2019 }
2020
2021 lStatus = NO_ERROR;
2022
2023Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002024 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002025 return track;
2026}
2027
2028uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2029{
2030 return latency;
2031}
2032
2033uint32_t AudioFlinger::PlaybackThread::latency() const
2034{
2035 Mutex::Autolock _l(mLock);
2036 return latency_l();
2037}
2038uint32_t AudioFlinger::PlaybackThread::latency_l() const
2039{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002040 uint32_t latency;
2041 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2042 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002043 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002044 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002045}
2046
2047void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2048{
2049 Mutex::Autolock _l(mLock);
2050 // Don't apply master volume in SW if our HAL can do it for us.
2051 if (mOutput && mOutput->audioHwDev &&
2052 mOutput->audioHwDev->canSetMasterVolume()) {
2053 mMasterVolume = 1.0;
2054 } else {
2055 mMasterVolume = value;
2056 }
2057}
2058
2059void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2060{
2061 Mutex::Autolock _l(mLock);
2062 // Don't apply master mute in SW if our HAL can do it for us.
2063 if (mOutput && mOutput->audioHwDev &&
2064 mOutput->audioHwDev->canSetMasterMute()) {
2065 mMasterMute = false;
2066 } else {
2067 mMasterMute = muted;
2068 }
2069}
2070
2071void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2072{
2073 Mutex::Autolock _l(mLock);
2074 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002075 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002076}
2077
2078void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2079{
2080 Mutex::Autolock _l(mLock);
2081 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002082 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002083}
2084
2085float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2086{
2087 Mutex::Autolock _l(mLock);
2088 return mStreamTypes[stream].volume;
2089}
2090
2091// addTrack_l() must be called with ThreadBase::mLock held
2092status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2093{
2094 status_t status = ALREADY_EXISTS;
2095
Eric Laurent81784c32012-11-19 14:55:58 -08002096 if (mActiveTracks.indexOf(track) < 0) {
2097 // the track is newly added, make sure it fills up all its
2098 // buffers before playing. This is to ensure the client will
2099 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002100 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002101 TrackBase::track_state state = track->mState;
2102 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002103 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002104 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002105 mLock.lock();
2106 // abort track was stopped/paused while we released the lock
2107 if (state != track->mState) {
2108 if (status == NO_ERROR) {
2109 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002110 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002111 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 mLock.lock();
2113 }
2114 return INVALID_OPERATION;
2115 }
2116 // abort if start is rejected by audio policy manager
2117 if (status != NO_ERROR) {
2118 return PERMISSION_DENIED;
2119 }
2120#ifdef ADD_BATTERY_DATA
2121 // to track the speaker usage
2122 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2123#endif
2124 }
2125
Eric Laurent51716182016-02-29 18:00:56 -08002126 // set retry count for buffer fill
2127 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002128 if (track->isStopping_1()) {
2129 track->mRetryCount = kMaxTrackStopRetriesOffload;
2130 } else {
2131 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2132 }
2133 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002134 } else {
2135 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002136 track->mFillingUpStatus =
2137 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002138 }
2139
Eric Laurent81784c32012-11-19 14:55:58 -08002140 track->mResetDone = false;
2141 track->mPresentationCompleteFrames = 0;
2142 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002143 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2144 if (chain != 0) {
2145 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2146 track->sessionId());
2147 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002148 }
2149
Andy Hung2148bf02016-11-28 19:01:02 -08002150 char buffer[256];
2151 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2152 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2153
Eric Laurent81784c32012-11-19 14:55:58 -08002154 status = NO_ERROR;
2155 }
2156
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002157 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002158 return status;
2159}
2160
Eric Laurentbfb1b832013-01-07 09:53:42 -08002161bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002162{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002163 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002165 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2166 track->mState = TrackBase::STOPPED;
2167 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002168 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002169 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002170 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002171 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002172
2173 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002174}
2175
2176void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2177{
2178 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002179
2180 char buffer[256];
2181 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
2182 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2183
Eric Laurent81784c32012-11-19 14:55:58 -08002184 mTracks.remove(track);
2185 deleteTrackName_l(track->name());
2186 // redundant as track is about to be destroyed, for dumpsys only
2187 track->mName = -1;
2188 if (track->isFastTrack()) {
2189 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002190 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002191 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2192 mFastTrackAvailMask |= 1 << index;
2193 // redundant as track is about to be destroyed, for dumpsys only
2194 track->mFastIndex = -1;
2195 }
2196 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2197 if (chain != 0) {
2198 chain->decTrackCnt();
2199 }
2200}
2201
Eric Laurentede6c3b2013-09-19 14:37:46 -07002202void AudioFlinger::PlaybackThread::broadcast_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002203{
2204 // Thread could be blocked waiting for async
2205 // so signal it to handle state changes immediately
2206 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2207 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2208 mSignalPending = true;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002209 mWaitWorkCV.broadcast();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002210}
2211
Eric Laurent81784c32012-11-19 14:55:58 -08002212String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2213{
Eric Laurent81784c32012-11-19 14:55:58 -08002214 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002215 String8 out_s8;
2216 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2217 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002218 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002219 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002220}
2221
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002222void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002223 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2224 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002225
Eric Laurent73e26b62015-04-27 16:55:58 -07002226 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002227
2228 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002229 case AUDIO_OUTPUT_OPENED:
2230 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002231 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002232 desc->mChannelMask = mChannelMask;
2233 desc->mSamplingRate = mSampleRate;
2234 desc->mFormat = mFormat;
2235 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002236 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002237 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002238 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002239 break;
2240
Eric Laurent73e26b62015-04-27 16:55:58 -07002241 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002242 default:
2243 break;
2244 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002245 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002246}
2247
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002248void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002249{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002250 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002251}
2252
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002253void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002254{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002255 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002256}
2257
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002258void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002259{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002260 mCallbackThread->setAsyncError();
2261}
2262
Eric Laurent3b4529e2013-09-05 18:09:19 -07002263void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002264{
2265 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002266 // reject out of sequence requests
2267 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2268 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269 mWaitWorkCV.signal();
2270 }
2271}
2272
Eric Laurent3b4529e2013-09-05 18:09:19 -07002273void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274{
2275 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002276 // reject out of sequence requests
2277 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2278 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279 mWaitWorkCV.signal();
2280 }
2281}
2282
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002283void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002284{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002285 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002286 mSampleRate = mOutput->getSampleRate();
2287 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002288 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002289 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002290 }
Andy Hung9a592762014-07-21 21:56:01 -07002291 if ((mType == MIXER || mType == DUPLICATING)
2292 && !isValidPcmSinkChannelMask(mChannelMask)) {
2293 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2294 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002295 }
Andy Hunge5412692014-05-16 11:25:07 -07002296 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002297
2298 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002299 status_t result = mOutput->stream->getFormat(&mHALFormat);
2300 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002301 // Get format from the shim, which will be different than the HAL format
2302 // if playing compressed audio over HDMI passthrough.
2303 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002304 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002305 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002306 }
Andy Hung6146c082014-03-18 11:56:15 -07002307 if ((mType == MIXER || mType == DUPLICATING)
2308 && !isValidPcmSinkFormat(mFormat)) {
2309 LOG_FATAL("HAL format %#x not supported for mixed output",
2310 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002311 }
Phil Burk062e67a2015-02-11 13:40:50 -08002312 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002313 result = mOutput->stream->getBufferSize(&mBufferSize);
2314 LOG_ALWAYS_FATAL_IF(result != OK,
2315 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002316 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002317 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002318 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002319 mFrameCount);
2320 }
2321
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002322 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2323 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002325 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002326 }
2327 }
2328
Eric Laurentd1f69b02014-12-15 14:33:13 -08002329 mHwSupportsPause = false;
2330 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002331 bool supportsPause = false, supportsResume = false;
2332 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2333 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002334 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002335 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002336 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002337 } else if (supportsResume) {
2338 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002339 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002340 }
2341 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002342 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2343 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2344 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002345
Andy Hungfbfc3952015-01-15 13:33:51 -08002346 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2347 // For best precision, we use float instead of the associated output
2348 // device format (typically PCM 16 bit).
2349
2350 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2351 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2352 mBufferSize = mFrameSize * mFrameCount;
2353
2354 // TODO: We currently use the associated output device channel mask and sample rate.
2355 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2356 // (if a valid mask) to avoid premature downmix.
2357 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2358 // instead of the output device sample rate to avoid loss of high frequency information.
2359 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2360 }
2361
Andy Hung09a50072014-02-27 14:30:47 -08002362 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002363 double multiplier = 1.0;
2364 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2365 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002366 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2367 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002368
Eric Laurent81784c32012-11-19 14:55:58 -08002369 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2370 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2371 maxNormalFrameCount = maxNormalFrameCount & ~15;
2372 if (maxNormalFrameCount < minNormalFrameCount) {
2373 maxNormalFrameCount = minNormalFrameCount;
2374 }
2375 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2376 if (multiplier <= 1.0) {
2377 multiplier = 1.0;
2378 } else if (multiplier <= 2.0) {
2379 if (2 * mFrameCount <= maxNormalFrameCount) {
2380 multiplier = 2.0;
2381 } else {
2382 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2383 }
2384 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002385 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002386 }
2387 }
2388 mNormalFrameCount = multiplier * mFrameCount;
2389 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002390 if (mType == MIXER || mType == DUPLICATING) {
2391 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2392 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002393 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002394 mNormalFrameCount);
2395
Andy Hung08fb1742015-05-31 23:22:10 -07002396 // Check if we want to throttle the processing to no more than 2x normal rate
2397 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002398 mThreadThrottleTimeMs = 0;
2399 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002400 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2401
Andy Hung010a1a12014-03-13 13:57:33 -07002402 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2403 // Originally this was int16_t[] array, need to remove legacy implications.
2404 free(mSinkBuffer);
2405 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002406 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2407 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2408 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002409 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002410
Andy Hung69aed5f2014-02-25 17:24:40 -08002411 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2412 // drives the output.
2413 free(mMixerBuffer);
2414 mMixerBuffer = NULL;
2415 if (mMixerBufferEnabled) {
2416 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2417 mMixerBufferSize = mNormalFrameCount * mChannelCount
2418 * audio_bytes_per_sample(mMixerBufferFormat);
2419 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2420 }
Andy Hung98ef9782014-03-04 14:46:50 -08002421 free(mEffectBuffer);
2422 mEffectBuffer = NULL;
2423 if (mEffectBufferEnabled) {
2424 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2425 mEffectBufferSize = mNormalFrameCount * mChannelCount
2426 * audio_bytes_per_sample(mEffectBufferFormat);
2427 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2428 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002429
Eric Laurent81784c32012-11-19 14:55:58 -08002430 // force reconfiguration of effect chains and engines to take new buffer size and audio
2431 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002432 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002433 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2434 // matter.
2435 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2436 Vector< sp<EffectChain> > effectChains = mEffectChains;
2437 for (size_t i = 0; i < effectChains.size(); i ++) {
2438 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2439 }
2440}
2441
2442
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002443status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002444{
2445 if (halFrames == NULL || dspFrames == NULL) {
2446 return BAD_VALUE;
2447 }
2448 Mutex::Autolock _l(mLock);
2449 if (initCheck() != NO_ERROR) {
2450 return INVALID_OPERATION;
2451 }
Andy Hung818e7a32016-02-16 18:08:07 -08002452 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002453 *halFrames = framesWritten;
2454
2455 if (isSuspended()) {
2456 // return an estimation of rendered frames when the output is suspended
2457 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002458 *dspFrames = (uint32_t)
2459 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002460 return NO_ERROR;
2461 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002462 status_t status;
2463 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002464 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002465 *dspFrames = (size_t)frames;
2466 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002467 }
2468}
2469
Eric Laurent4c415062016-06-17 16:14:16 -07002470// hasAudioSession_l() must be called with ThreadBase::mLock held
2471uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002472{
Eric Laurent81784c32012-11-19 14:55:58 -08002473 uint32_t result = 0;
2474 if (getEffectChain_l(sessionId) != 0) {
2475 result = EFFECT_SESSION;
2476 }
2477
2478 for (size_t i = 0; i < mTracks.size(); ++i) {
2479 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002480 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002481 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002482 if (track->isFastTrack()) {
2483 result |= FAST_SESSION;
2484 }
Eric Laurent81784c32012-11-19 14:55:58 -08002485 break;
2486 }
2487 }
2488
2489 return result;
2490}
2491
Glenn Kastend848eb42016-03-08 13:42:11 -08002492uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002493{
2494 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2495 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2496 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2497 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2498 }
2499 for (size_t i = 0; i < mTracks.size(); i++) {
2500 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002501 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002502 return AudioSystem::getStrategyForStream(track->streamType());
2503 }
2504 }
2505 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2506}
2507
2508
Phil Burk062e67a2015-02-11 13:40:50 -08002509AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002510{
2511 Mutex::Autolock _l(mLock);
2512 return mOutput;
2513}
2514
Phil Burk062e67a2015-02-11 13:40:50 -08002515AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002516{
2517 Mutex::Autolock _l(mLock);
2518 AudioStreamOut *output = mOutput;
2519 mOutput = NULL;
2520 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2521 // must push a NULL and wait for ack
2522 mOutputSink.clear();
2523 mPipeSink.clear();
2524 mNormalSink.clear();
2525 return output;
2526}
2527
2528// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002529sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002530{
2531 if (mOutput == NULL) {
2532 return NULL;
2533 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002534 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002535}
2536
2537uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2538{
2539 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2540}
2541
2542status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2543{
2544 if (!isValidSyncEvent(event)) {
2545 return BAD_VALUE;
2546 }
2547
2548 Mutex::Autolock _l(mLock);
2549
2550 for (size_t i = 0; i < mTracks.size(); ++i) {
2551 sp<Track> track = mTracks[i];
2552 if (event->triggerSession() == track->sessionId()) {
2553 (void) track->setSyncEvent(event);
2554 return NO_ERROR;
2555 }
2556 }
2557
2558 return NAME_NOT_FOUND;
2559}
2560
2561bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2562{
2563 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2564}
2565
2566void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2567 const Vector< sp<Track> >& tracksToRemove)
2568{
2569 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002570 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002571 for (size_t i = 0 ; i < count ; i++) {
2572 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002573 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002574 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002575 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002576#ifdef ADD_BATTERY_DATA
2577 // to track the speaker usage
2578 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2579#endif
2580 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002581 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002582 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002583 }
Eric Laurent81784c32012-11-19 14:55:58 -08002584 }
2585 }
2586 }
Eric Laurent81784c32012-11-19 14:55:58 -08002587}
2588
2589void AudioFlinger::PlaybackThread::checkSilentMode_l()
2590{
2591 if (!mMasterMute) {
2592 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002593 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2594 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2595 return;
2596 }
Eric Laurent81784c32012-11-19 14:55:58 -08002597 if (property_get("ro.audio.silent", value, "0") > 0) {
2598 char *endptr;
2599 unsigned long ul = strtoul(value, &endptr, 0);
2600 if (*endptr == '\0' && ul != 0) {
2601 ALOGD("Silence is golden");
2602 // The setprop command will not allow a property to be changed after
2603 // the first time it is set, so we don't have to worry about un-muting.
2604 setMasterMute_l(true);
2605 }
2606 }
2607 }
2608}
2609
2610// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002611ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002612{
Eric Laurent81784c32012-11-19 14:55:58 -08002613 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002615 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002616
2617 // If an NBAIO sink is present, use it to write the normal mixer's submix
2618 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002619
Andy Hung010a1a12014-03-13 13:57:33 -07002620 const size_t count = mBytesRemaining / mFrameSize;
2621
Simon Wilson2d590962012-11-29 15:18:50 -08002622 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002623 // update the setpoint when AudioFlinger::mScreenState changes
2624 uint32_t screenState = AudioFlinger::mScreenState;
2625 if (screenState != mScreenState) {
2626 mScreenState = screenState;
2627 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2628 if (pipe != NULL) {
2629 pipe->setAvgFrames((mScreenState & 1) ?
2630 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2631 }
2632 }
Andy Hung010a1a12014-03-13 13:57:33 -07002633 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002634 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002635 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002636 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002637 } else {
2638 bytesWritten = framesWritten;
2639 }
2640 // otherwise use the HAL / AudioStreamOut directly
2641 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002643
Eric Laurentbfb1b832013-01-07 09:53:42 -08002644 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002645 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2646 mWriteAckSequence += 2;
2647 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002649 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002650 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002651 // FIXME We should have an implementation of timestamps for direct output threads.
2652 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002653 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002654
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 if (mUseAsyncWrite &&
2656 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2657 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002658 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002660 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 }
Eric Laurent81784c32012-11-19 14:55:58 -08002662 }
2663
Eric Laurent81784c32012-11-19 14:55:58 -08002664 mNumWrites++;
2665 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002666 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 return bytesWritten;
2668}
2669
2670void AudioFlinger::PlaybackThread::threadLoop_drain()
2671{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002672 bool supportsDrain = false;
2673 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2675 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002676 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2677 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002678 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002679 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002681 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002682 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002683 }
2684}
2685
2686void AudioFlinger::PlaybackThread::threadLoop_exit()
2687{
Eric Laurent275e8e92014-11-30 15:14:47 -08002688 {
2689 Mutex::Autolock _l(mLock);
2690 for (size_t i = 0; i < mTracks.size(); i++) {
2691 sp<Track> track = mTracks[i];
2692 track->invalidate();
2693 }
Andy Hungdae27702016-10-31 14:01:16 -07002694 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2695 // After we exit there are no more track changes sent to BatteryNotifier
2696 // because that requires an active threadLoop.
2697 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2698 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002699 }
Eric Laurent81784c32012-11-19 14:55:58 -08002700}
2701
2702/*
2703The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002704 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002705 - mActiveSleepTimeUs from activeSleepTimeUs()
2706 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002707 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2708 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002709 - maxPeriod from frame count and sample rate (MIXER only)
2710
2711The parameters that affect these derived values are:
2712 - frame count
2713 - frame size
2714 - sample rate
2715 - device type: A2DP or not
2716 - device latency
2717 - format: PCM or not
2718 - active sleep time
2719 - idle sleep time
2720*/
2721
2722void AudioFlinger::PlaybackThread::cacheParameters_l()
2723{
Andy Hung25c2dac2014-02-27 14:56:00 -08002724 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002725 mActiveSleepTimeUs = activeSleepTimeUs();
2726 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002727
2728 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2729 // truncating audio when going to standby.
2730 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2731 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2732 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2733 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2734 }
2735 }
Eric Laurent81784c32012-11-19 14:55:58 -08002736}
2737
Eric Laurent13084622016-05-17 10:51:49 -07002738bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002739{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002740 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002741 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002742 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002743 size_t size = mTracks.size();
2744 for (size_t i = 0; i < size; i++) {
2745 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002746 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002747 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002748 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002749 }
2750 }
Eric Laurent13084622016-05-17 10:51:49 -07002751 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002752}
2753
Haynes Mathew George05317d22016-05-03 16:34:26 -07002754void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2755{
2756 Mutex::Autolock _l(mLock);
2757 invalidateTracks_l(streamType);
2758}
2759
Eric Laurent81784c32012-11-19 14:55:58 -08002760status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2761{
Glenn Kastend848eb42016-03-08 13:42:11 -08002762 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002763 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2764 status_t result = EffectBufferHalInterface::mirror(
2765 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2766 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2767 &halInBuffer);
2768 if (result != OK) return result;
2769 halOutBuffer = halInBuffer;
2770 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002771
2772 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002773 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002774 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002775 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002776 if (mType != DIRECT) {
2777 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002778 status_t result = EffectBufferHalInterface::allocate(
2779 numSamples * sizeof(int16_t),
2780 &halInBuffer);
2781 if (result != OK) return result;
2782 buffer = halInBuffer->audioBuffer()->s16;
2783 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2784 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002785 }
2786
2787 // Attach all tracks with same session ID to this chain.
2788 for (size_t i = 0; i < mTracks.size(); ++i) {
2789 sp<Track> track = mTracks[i];
2790 if (session == track->sessionId()) {
2791 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2792 buffer);
2793 track->setMainBuffer(buffer);
2794 chain->incTrackCnt();
2795 }
2796 }
2797
2798 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002799 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002800 if (session == track->sessionId()) {
2801 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2802 chain->incActiveTrackCnt();
2803 }
2804 }
2805 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002806 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002807 chain->setInBuffer(halInBuffer);
2808 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002809 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002810 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2812 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002813 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002814 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002815 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002816 // Effect chain for other sessions are inserted at beginning of effect
2817 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002818 // sessions is not important.
2819 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2820 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2821 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002822 size_t size = mEffectChains.size();
2823 size_t i = 0;
2824 for (i = 0; i < size; i++) {
2825 if (mEffectChains[i]->sessionId() < session) {
2826 break;
2827 }
2828 }
2829 mEffectChains.insertAt(chain, i);
2830 checkSuspendOnAddEffectChain_l(chain);
2831
2832 return NO_ERROR;
2833}
2834
2835size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2836{
Glenn Kastend848eb42016-03-08 13:42:11 -08002837 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002838
2839 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2840
2841 for (size_t i = 0; i < mEffectChains.size(); i++) {
2842 if (chain == mEffectChains[i]) {
2843 mEffectChains.removeAt(i);
2844 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002845 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002846 if (session == track->sessionId()) {
2847 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2848 chain.get(), session);
2849 chain->decActiveTrackCnt();
2850 }
2851 }
2852
2853 // detach all tracks with same session ID from this chain
2854 for (size_t i = 0; i < mTracks.size(); ++i) {
2855 sp<Track> track = mTracks[i];
2856 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002857 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002858 chain->decTrackCnt();
2859 }
2860 }
2861 break;
2862 }
2863 }
2864 return mEffectChains.size();
2865}
2866
2867status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002868 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002869{
2870 Mutex::Autolock _l(mLock);
2871 return attachAuxEffect_l(track, EffectId);
2872}
2873
2874status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002875 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002876{
2877 status_t status = NO_ERROR;
2878
2879 if (EffectId == 0) {
2880 track->setAuxBuffer(0, NULL);
2881 } else {
2882 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2883 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2884 if (effect != 0) {
2885 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2886 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2887 } else {
2888 status = INVALID_OPERATION;
2889 }
2890 } else {
2891 status = BAD_VALUE;
2892 }
2893 }
2894 return status;
2895}
2896
2897void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2898{
2899 for (size_t i = 0; i < mTracks.size(); ++i) {
2900 sp<Track> track = mTracks[i];
2901 if (track->auxEffectId() == effectId) {
2902 attachAuxEffect_l(track, 0);
2903 }
2904 }
2905}
2906
2907bool AudioFlinger::PlaybackThread::threadLoop()
2908{
2909 Vector< sp<Track> > tracksToRemove;
2910
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002911 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002912 nsecs_t lastWriteFinished = -1; // time last server write completed
2913 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002914
2915 // MIXER
2916 nsecs_t lastWarning = 0;
2917
2918 // DUPLICATING
2919 // FIXME could this be made local to while loop?
2920 writeFrames = 0;
2921
2922 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002923 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002924
2925 if (mType == MIXER) {
2926 sleepTimeShift = 0;
2927 }
2928
2929 CpuStats cpuStats;
2930 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2931
2932 acquireWakeLock();
2933
Glenn Kasten9e58b552013-01-18 15:09:48 -08002934 // mNBLogWriter->log can only be called while thread mutex mLock is held.
2935 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2936 // and then that string will be logged at the next convenient opportunity.
2937 const char *logString = NULL;
2938
Eric Laurent664539d2013-09-23 18:24:31 -07002939 checkSilentMode_l();
2940
Eric Laurent81784c32012-11-19 14:55:58 -08002941 while (!exitPending())
2942 {
2943 cpuStats.sample(myName);
2944
2945 Vector< sp<EffectChain> > effectChains;
2946
Eric Laurent81784c32012-11-19 14:55:58 -08002947 { // scope for mLock
2948
2949 Mutex::Autolock _l(mLock);
2950
Eric Laurent021cf962014-05-13 10:18:14 -07002951 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002952
Glenn Kasten9e58b552013-01-18 15:09:48 -08002953 if (logString != NULL) {
2954 mNBLogWriter->logTimestamp();
2955 mNBLogWriter->log(logString);
2956 logString = NULL;
2957 }
2958
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002959 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002960 // and associate with the sink frames written out. We need
2961 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002962 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002963 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002964 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002965 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002966 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002967 ExtendedTimestamp timestamp; // use private copy to fetch
2968 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002969
2970 // We keep track of the last valid kernel position in case we are in underrun
2971 // and the normal mixer period is the same as the fast mixer period, or there
2972 // is some error from the HAL.
2973 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2974 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2975 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
2976 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
2977 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
2978
2979 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2980 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
2981 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
2982 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07002983 }
2984
2985 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
2986 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07002987 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07002988 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07002989 }
2990
Andy Hung818e7a32016-02-16 18:08:07 -08002991 // copy over kernel info
2992 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07002993 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
2994 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08002995 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
2996 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08002997 }
2998 // mFramesWritten for non-offloaded tracks are contiguous
2999 // even after standby() is called. This is useful for the track frame
3000 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003001 bool serverLocationUpdate = false;
3002 if (mFramesWritten != lastFramesWritten) {
3003 serverLocationUpdate = true;
3004 lastFramesWritten = mFramesWritten;
3005 }
3006 // Only update timestamps if there is a meaningful change.
3007 // Either the kernel timestamp must be valid or we have written something.
3008 if (kernelLocationUpdate || serverLocationUpdate) {
3009 if (serverLocationUpdate) {
3010 // use the time before we called the HAL write - it is a bit more accurate
3011 // to when the server last read data than the current time here.
3012 //
3013 // If we haven't written anything, mLastWriteTime will be -1
3014 // and we use systemTime().
3015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3016 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3017 ? systemTime() : mLastWriteTime;
3018 }
Andy Hungdae27702016-10-31 14:01:16 -07003019
3020 for (const sp<Track> &t : mActiveTracks) {
3021 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003022 t->updateTrackFrameInfo(
3023 t->mAudioTrackServerProxy->framesReleased(),
3024 mFramesWritten,
3025 mTimestamp);
3026 }
Andy Hunge10393e2015-06-12 13:59:33 -07003027 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003028 }
3029
Eric Laurent81784c32012-11-19 14:55:58 -08003030 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003031 if (mSignalPending) {
3032 // A signal was raised while we were unlocked
3033 mSignalPending = false;
3034 } else if (waitingAsyncCallback_l()) {
3035 if (exitPending()) {
3036 break;
3037 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003038 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003039 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003040 releaseWakeLock_l();
3041 released = true;
3042 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003043 ALOGV("wait async completion");
3044 mWaitWorkCV.wait(mLock);
3045 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003046 if (released) {
3047 acquireWakeLock_l();
3048 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003049 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3050 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003051
3052 continue;
3053 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003054 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055 isSuspended()) {
3056 // put audio hardware into standby after short delay
3057 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003058
3059 threadLoop_standby();
3060
3061 mStandby = true;
3062 }
3063
3064 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3065 // we're about to wait, flush the binder command buffer
3066 IPCThreadState::self()->flushCommands();
3067
3068 clearOutputTracks();
3069
3070 if (exitPending()) {
3071 break;
3072 }
3073
3074 releaseWakeLock_l();
3075 // wait until we have something to do...
3076 ALOGV("%s going to sleep", myName.string());
3077 mWaitWorkCV.wait(mLock);
3078 ALOGV("%s waking up", myName.string());
3079 acquireWakeLock_l();
3080
3081 mMixerStatus = MIXER_IDLE;
3082 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3083 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003084 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003085 checkSilentMode_l();
3086
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003087 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3088 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003089 if (mType == MIXER) {
3090 sleepTimeShift = 0;
3091 }
3092
3093 continue;
3094 }
3095 }
Eric Laurent81784c32012-11-19 14:55:58 -08003096 // mMixerStatusIgnoringFastTracks is also updated internally
3097 mMixerStatus = prepareTracks_l(&tracksToRemove);
3098
Andy Hungdae27702016-10-31 14:01:16 -07003099 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003100
Eric Laurent81784c32012-11-19 14:55:58 -08003101 // prevent any changes in effect chain list and in each effect chain
3102 // during mixing and effect process as the audio buffers could be deleted
3103 // or modified if an effect is created or deleted
3104 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003105 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003106
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107 if (mBytesRemaining == 0) {
3108 mCurrentWriteLength = 0;
3109 if (mMixerStatus == MIXER_TRACKS_READY) {
3110 // threadLoop_mix() sets mCurrentWriteLength
3111 threadLoop_mix();
3112 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3113 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003114 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115 // must be written to HAL
3116 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003117 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003118 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119 }
3120 }
Andy Hung98ef9782014-03-04 14:46:50 -08003121 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003122 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003123 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3124 // or mSinkBuffer (if there are no effects).
3125 //
3126 // This is done pre-effects computation; if effects change to
3127 // support higher precision, this needs to move.
3128 //
3129 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003130 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003131 if (mMixerBufferValid) {
3132 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3133 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3134
Andy Hung2ddee192015-12-18 17:34:44 -08003135 // mono blend occurs for mixer threads only (not direct or offloaded)
3136 // and is handled here if we're going directly to the sink.
3137 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003138 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3139 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003140 }
3141
Andy Hung98ef9782014-03-04 14:46:50 -08003142 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3143 mNormalFrameCount * mChannelCount);
3144 }
3145
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146 mBytesRemaining = mCurrentWriteLength;
3147 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003148 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3149 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3150 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3151 mBytesWritten += mBytesRemaining;
3152 mFramesWritten += framesRemaining;
3153 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003154 mBytesRemaining = 0;
3155 }
Eric Laurent81784c32012-11-19 14:55:58 -08003156
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003158 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003159 for (size_t i = 0; i < effectChains.size(); i ++) {
3160 effectChains[i]->process_l();
3161 }
Eric Laurent81784c32012-11-19 14:55:58 -08003162 }
3163 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003164 // Process effect chains for offloaded thread even if no audio
3165 // was read from audio track: process only updates effect state
3166 // and thus does have to be synchronized with audio writes but may have
3167 // to be called while waiting for async write callback
3168 if (mType == OFFLOAD) {
3169 for (size_t i = 0; i < effectChains.size(); i ++) {
3170 effectChains[i]->process_l();
3171 }
3172 }
Eric Laurent81784c32012-11-19 14:55:58 -08003173
Andy Hung98ef9782014-03-04 14:46:50 -08003174 // Only if the Effects buffer is enabled and there is data in the
3175 // Effects buffer (buffer valid), we need to
3176 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003177 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003178 if (mEffectBufferValid) {
3179 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003180
3181 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003182 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3183 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003184 }
3185
Andy Hung98ef9782014-03-04 14:46:50 -08003186 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3187 mNormalFrameCount * mChannelCount);
3188 }
3189
Eric Laurent81784c32012-11-19 14:55:58 -08003190 // enable changes in effect chain
3191 unlockEffectChains(effectChains);
3192
Eric Laurentbfb1b832013-01-07 09:53:42 -08003193 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003194 // mSleepTimeUs == 0 means we must write to audio hardware
3195 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003196 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003197 // We save lastWriteFinished here, as previousLastWriteFinished,
3198 // for throttling. On thread start, previousLastWriteFinished will be
3199 // set to -1, which properly results in no throttling after the first write.
3200 nsecs_t previousLastWriteFinished = lastWriteFinished;
3201 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003202 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003203 // FIXME rewrite to reduce number of system calls
3204 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003205 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003206 lastWriteFinished = systemTime();
3207 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003208 if (ret < 0) {
3209 mBytesRemaining = 0;
3210 } else {
3211 mBytesWritten += ret;
3212 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003213 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003214 }
3215 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3216 (mMixerStatus == MIXER_DRAIN_ALL)) {
3217 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003218 }
Andy Hung08fb1742015-05-31 23:22:10 -07003219 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003220 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003221 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003222 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003223 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003224 ATRACE_NAME("underrun");
3225 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003226 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003227 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003228 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003229 }
Andy Hung08fb1742015-05-31 23:22:10 -07003230
3231 if (mThreadThrottle
3232 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3233 && ret > 0) { // we wrote something
3234 // Limit MixerThread data processing to no more than twice the
3235 // expected processing rate.
3236 //
3237 // This helps prevent underruns with NuPlayer and other applications
3238 // which may set up buffers that are close to the minimum size, or use
3239 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3240 //
3241 // The throttle smooths out sudden large data drains from the device,
3242 // e.g. when it comes out of standby, which often causes problems with
3243 // (1) mixer threads without a fast mixer (which has its own warm-up)
3244 // (2) minimum buffer sized tracks (even if the track is full,
3245 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003246 //
3247 // Total time spent in last processing cycle equals time spent in
3248 // 1. threadLoop_write, as well as time spent in
3249 // 2. threadLoop_mix (significant for heavy mixing, especially
3250 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003251
Andy Hung69488c42016-05-16 18:43:33 -07003252 // it's OK if deltaMs is an overestimate.
3253 const int32_t deltaMs =
3254 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003255 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3256 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3257 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003258 // notify of throttle start on verbose log
3259 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3260 "mixer(%p) throttle begin:"
3261 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003262 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003263 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003264 // Throttle must be attributed to the previous mixer loop's write time
3265 // to allow back-to-back throttling.
3266 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003267 } else {
3268 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3269 if (diff > 0) {
3270 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003271 // but prevent spamming for bluetooth
3272 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3273 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003274 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3275 }
Andy Hung08fb1742015-05-31 23:22:10 -07003276 }
3277 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 }
Eric Laurent81784c32012-11-19 14:55:58 -08003279
Eric Laurentbfb1b832013-01-07 09:53:42 -08003280 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003281 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003282 Mutex::Autolock _l(mLock);
3283 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3284 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003285 }
Glenn Kastene7754022014-10-31 12:11:26 -07003286 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003287 }
Eric Laurent81784c32012-11-19 14:55:58 -08003288 }
3289
3290 // Finally let go of removed track(s), without the lock held
3291 // since we can't guarantee the destructors won't acquire that
3292 // same lock. This will also mutate and push a new fast mixer state.
3293 threadLoop_removeTracks(tracksToRemove);
3294 tracksToRemove.clear();
3295
3296 // FIXME I don't understand the need for this here;
3297 // it was in the original code but maybe the
3298 // assignment in saveOutputTracks() makes this unnecessary?
3299 clearOutputTracks();
3300
3301 // Effect chains will be actually deleted here if they were removed from
3302 // mEffectChains list during mixing or effects processing
3303 effectChains.clear();
3304
3305 // FIXME Note that the above .clear() is no longer necessary since effectChains
3306 // is now local to this block, but will keep it for now (at least until merge done).
3307 }
3308
Eric Laurentbfb1b832013-01-07 09:53:42 -08003309 threadLoop_exit();
3310
Eric Laurentcf817a22014-08-04 20:36:31 -07003311 if (!mStandby) {
3312 threadLoop_standby();
3313 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003314 }
3315
3316 releaseWakeLock();
3317
3318 ALOGV("Thread %p type %d exiting", this, mType);
3319 return false;
3320}
3321
Eric Laurentbfb1b832013-01-07 09:53:42 -08003322// removeTracks_l() must be called with ThreadBase::mLock held
3323void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3324{
3325 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003326 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003327 for (size_t i=0 ; i<count ; i++) {
3328 const sp<Track>& track = tracksToRemove.itemAt(i);
3329 mActiveTracks.remove(track);
3330 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3331 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3332 if (chain != 0) {
3333 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3334 track->sessionId());
3335 chain->decActiveTrackCnt();
3336 }
3337 if (track->isTerminated()) {
3338 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003339 } else { // inactive but not terminated
3340 char buffer[256];
3341 track->dump(buffer, ARRAY_SIZE(buffer), false /* active */);
3342 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003343 }
3344 }
3345 }
3346
3347}
Eric Laurent81784c32012-11-19 14:55:58 -08003348
Eric Laurentaccc1472013-09-20 09:36:34 -07003349status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3350{
3351 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003352 ExtendedTimestamp ets;
3353 status_t status = mNormalSink->getTimestamp(ets);
3354 if (status == NO_ERROR) {
3355 status = ets.getBestTimestamp(&timestamp);
3356 }
3357 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003358 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003359 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003360 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003361 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003362 timestamp.mPosition = (uint32_t)position64;
3363 return NO_ERROR;
3364 }
3365 }
3366 return INVALID_OPERATION;
3367}
Eric Laurent1c333e22014-05-20 10:48:17 -07003368
Eric Laurent054d9d32015-04-24 08:48:48 -07003369status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3370 audio_patch_handle_t *handle)
3371{
Andy Hungf60abce2016-08-26 11:37:54 -07003372 status_t status;
3373 if (property_get_bool("af.patch_park", false /* default_value */)) {
3374 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3375 // or if HAL does not properly lock against access.
3376 AutoPark<FastMixer> park(mFastMixer);
3377 status = PlaybackThread::createAudioPatch_l(patch, handle);
3378 } else {
3379 status = PlaybackThread::createAudioPatch_l(patch, handle);
3380 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003381 return status;
3382}
3383
Eric Laurent1c333e22014-05-20 10:48:17 -07003384status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3385 audio_patch_handle_t *handle)
3386{
3387 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003388
3389 // store new device and send to effects
3390 audio_devices_t type = AUDIO_DEVICE_NONE;
3391 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3392 type |= patch->sinks[i].ext.device.type;
3393 }
3394
3395#ifdef ADD_BATTERY_DATA
3396 // when changing the audio output device, call addBatteryData to notify
3397 // the change
3398 if (mOutDevice != type) {
3399 uint32_t params = 0;
3400 // check whether speaker is on
3401 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3402 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003403 }
3404
Eric Laurent054d9d32015-04-24 08:48:48 -07003405 audio_devices_t deviceWithoutSpeaker
3406 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3407 // check if any other device (except speaker) is on
3408 if (type & deviceWithoutSpeaker) {
3409 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3410 }
3411
3412 if (params != 0) {
3413 addBatteryData(params);
3414 }
3415 }
3416#endif
3417
3418 for (size_t i = 0; i < mEffectChains.size(); i++) {
3419 mEffectChains[i]->setDevice_l(type);
3420 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003421
3422 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3423 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3424 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003425 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003426 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003427
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003428 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003429 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3430 status = hwDevice->createAudioPatch(patch->num_sources,
3431 patch->sources,
3432 patch->num_sinks,
3433 patch->sinks,
3434 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003435 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003436 char *address;
3437 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3438 //FIXME: we only support address on first sink with HAL version < 3.0
3439 address = audio_device_address_to_parameter(
3440 patch->sinks[0].ext.device.type,
3441 patch->sinks[0].ext.device.address);
3442 } else {
3443 address = (char *)calloc(1, 1);
3444 }
3445 AudioParameter param = AudioParameter(String8(address));
3446 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003447 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003448 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003449 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003450 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003451 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003452 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003453 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3454 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003455 return status;
3456}
3457
Eric Laurent054d9d32015-04-24 08:48:48 -07003458status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3459{
Andy Hungf60abce2016-08-26 11:37:54 -07003460 status_t status;
3461 if (property_get_bool("af.patch_park", false /* default_value */)) {
3462 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3463 // or if HAL does not properly lock against access.
3464 AutoPark<FastMixer> park(mFastMixer);
3465 status = PlaybackThread::releaseAudioPatch_l(handle);
3466 } else {
3467 status = PlaybackThread::releaseAudioPatch_l(handle);
3468 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003469 return status;
3470}
3471
Eric Laurent1c333e22014-05-20 10:48:17 -07003472status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3473{
3474 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003475
3476 mOutDevice = AUDIO_DEVICE_NONE;
3477
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003478 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003479 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3480 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003481 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003482 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003483 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003484 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003485 }
3486 return status;
3487}
3488
Eric Laurent83b88082014-06-20 18:31:16 -07003489void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3490{
3491 Mutex::Autolock _l(mLock);
3492 mTracks.add(track);
3493}
3494
3495void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3496{
3497 Mutex::Autolock _l(mLock);
3498 destroyTrack_l(track);
3499}
3500
3501void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3502{
3503 ThreadBase::getAudioPortConfig(config);
3504 config->role = AUDIO_PORT_ROLE_SOURCE;
3505 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3506 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3507}
3508
Eric Laurent81784c32012-11-19 14:55:58 -08003509// ----------------------------------------------------------------------------
3510
3511AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003512 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3513 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003514 // mAudioMixer below
3515 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003516 mFastMixerFutex(0),
3517 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003518 // mOutputSink below
3519 // mPipeSink below
3520 // mNormalSink below
3521{
3522 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003523 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3524 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003525 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3526 mNormalFrameCount);
3527 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3528
Andy Hungfbfc3952015-01-15 13:33:51 -08003529 if (type == DUPLICATING) {
3530 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3531 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3532 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3533 return;
3534 }
Eric Laurent81784c32012-11-19 14:55:58 -08003535 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003536 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003537 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003538 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003539#if !LOG_NDEBUG
3540 ssize_t index =
3541#else
3542 (void)
3543#endif
3544 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003545 ALOG_ASSERT(index == 0);
3546
3547 // initialize fast mixer depending on configuration
3548 bool initFastMixer;
3549 switch (kUseFastMixer) {
3550 case FastMixer_Never:
3551 initFastMixer = false;
3552 break;
3553 case FastMixer_Always:
3554 initFastMixer = true;
3555 break;
3556 case FastMixer_Static:
3557 case FastMixer_Dynamic:
3558 initFastMixer = mFrameCount < mNormalFrameCount;
3559 break;
3560 }
3561 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003562 audio_format_t fastMixerFormat;
3563 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3564 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3565 } else {
3566 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3567 }
3568 if (mFormat != fastMixerFormat) {
3569 // change our Sink format to accept our intermediate precision
3570 mFormat = fastMixerFormat;
3571 free(mSinkBuffer);
3572 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3573 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3574 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3575 }
Eric Laurent81784c32012-11-19 14:55:58 -08003576
3577 // create a MonoPipe to connect our submix to FastMixer
3578 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003579#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003580 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003581#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003582 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003583 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003584 format.mFormat = fastMixerFormat;
3585 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3586
Eric Laurent81784c32012-11-19 14:55:58 -08003587 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3588 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3589 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3590 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3591 const NBAIO_Format offers[1] = {format};
3592 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003593#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003594 ssize_t index =
3595#else
3596 (void)
3597#endif
3598 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003599 ALOG_ASSERT(index == 0);
3600 monoPipe->setAvgFrames((mScreenState & 1) ?
3601 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3602 mPipeSink = monoPipe;
3603
Glenn Kasten46909e72013-02-26 09:20:22 -08003604#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003605 if (mTeeSinkOutputEnabled) {
3606 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003607 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3608 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003609 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003610 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003611 ALOG_ASSERT(index == 0);
3612 mTeeSink = teeSink;
3613 PipeReader *teeSource = new PipeReader(*teeSink);
3614 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003615 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003616 ALOG_ASSERT(index == 0);
3617 mTeeSource = teeSource;
3618 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003619#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003620
3621 // create fast mixer and configure it initially with just one fast track for our submix
3622 mFastMixer = new FastMixer();
3623 FastMixerStateQueue *sq = mFastMixer->sq();
3624#ifdef STATE_QUEUE_DUMP
3625 sq->setObserverDump(&mStateQueueObserverDump);
3626 sq->setMutatorDump(&mStateQueueMutatorDump);
3627#endif
3628 FastMixerState *state = sq->begin();
3629 FastTrack *fastTrack = &state->mFastTracks[0];
3630 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3631 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3632 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003633 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3634 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003635 fastTrack->mGeneration++;
3636 state->mFastTracksGen++;
3637 state->mTrackMask = 1;
3638 // fast mixer will use the HAL output sink
3639 state->mOutputSink = mOutputSink.get();
3640 state->mOutputSinkGen++;
3641 state->mFrameCount = mFrameCount;
3642 state->mCommand = FastMixerState::COLD_IDLE;
3643 // already done in constructor initialization list
3644 //mFastMixerFutex = 0;
3645 state->mColdFutexAddr = &mFastMixerFutex;
3646 state->mColdGen++;
3647 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003648#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003649 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003650#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003651 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3652 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003653 sq->end();
3654 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3655
3656 // start the fast mixer
3657 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3658 pid_t tid = mFastMixer->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003659 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003660 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003661
3662#ifdef AUDIO_WATCHDOG
3663 // create and start the watchdog
3664 mAudioWatchdog = new AudioWatchdog();
3665 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3666 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3667 tid = mAudioWatchdog->getTid();
Eric Laurent72e3f392015-05-20 14:43:50 -07003668 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003669#endif
3670
Eric Laurent81784c32012-11-19 14:55:58 -08003671 }
3672
3673 switch (kUseFastMixer) {
3674 case FastMixer_Never:
3675 case FastMixer_Dynamic:
3676 mNormalSink = mOutputSink;
3677 break;
3678 case FastMixer_Always:
3679 mNormalSink = mPipeSink;
3680 break;
3681 case FastMixer_Static:
3682 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3683 break;
3684 }
3685}
3686
3687AudioFlinger::MixerThread::~MixerThread()
3688{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003689 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003690 FastMixerStateQueue *sq = mFastMixer->sq();
3691 FastMixerState *state = sq->begin();
3692 if (state->mCommand == FastMixerState::COLD_IDLE) {
3693 int32_t old = android_atomic_inc(&mFastMixerFutex);
3694 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003695 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003696 }
3697 }
3698 state->mCommand = FastMixerState::EXIT;
3699 sq->end();
3700 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3701 mFastMixer->join();
3702 // Though the fast mixer thread has exited, it's state queue is still valid.
3703 // We'll use that extract the final state which contains one remaining fast track
3704 // corresponding to our sub-mix.
3705 state = sq->begin();
3706 ALOG_ASSERT(state->mTrackMask == 1);
3707 FastTrack *fastTrack = &state->mFastTracks[0];
3708 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3709 delete fastTrack->mBufferProvider;
3710 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003711 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003712#ifdef AUDIO_WATCHDOG
3713 if (mAudioWatchdog != 0) {
3714 mAudioWatchdog->requestExit();
3715 mAudioWatchdog->requestExitAndWait();
3716 mAudioWatchdog.clear();
3717 }
3718#endif
3719 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003720 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003721 delete mAudioMixer;
3722}
3723
3724
3725uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3726{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003727 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003728 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3729 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3730 }
3731 return latency;
3732}
3733
3734
3735void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3736{
3737 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3738}
3739
Eric Laurentbfb1b832013-01-07 09:53:42 -08003740ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003741{
3742 // FIXME we should only do one push per cycle; confirm this is true
3743 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003744 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003745 FastMixerStateQueue *sq = mFastMixer->sq();
3746 FastMixerState *state = sq->begin();
3747 if (state->mCommand != FastMixerState::MIX_WRITE &&
3748 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3749 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003750
3751 // FIXME workaround for first HAL write being CPU bound on some devices
3752 ATRACE_BEGIN("write");
3753 mOutput->write((char *)mSinkBuffer, 0);
3754 ATRACE_END();
3755
Eric Laurent81784c32012-11-19 14:55:58 -08003756 int32_t old = android_atomic_inc(&mFastMixerFutex);
3757 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003758 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003759 }
3760#ifdef AUDIO_WATCHDOG
3761 if (mAudioWatchdog != 0) {
3762 mAudioWatchdog->resume();
3763 }
3764#endif
3765 }
3766 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003767#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003768 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003769 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003770#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003771 sq->end();
3772 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3773 if (kUseFastMixer == FastMixer_Dynamic) {
3774 mNormalSink = mPipeSink;
3775 }
3776 } else {
3777 sq->end(false /*didModify*/);
3778 }
3779 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003780 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003781}
3782
3783void AudioFlinger::MixerThread::threadLoop_standby()
3784{
3785 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003786 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003787 FastMixerStateQueue *sq = mFastMixer->sq();
3788 FastMixerState *state = sq->begin();
3789 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003790 // Report any frames trapped in the Monopipe
3791 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3792 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3793 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3794 "monoPipeWritten:%lld monoPipeLeft:%lld",
3795 (long long)mFramesWritten, (long long)mSuspendedFrames,
3796 (long long)mPipeSink->framesWritten(), pipeFrames);
3797 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3798
Eric Laurent81784c32012-11-19 14:55:58 -08003799 state->mCommand = FastMixerState::COLD_IDLE;
3800 state->mColdFutexAddr = &mFastMixerFutex;
3801 state->mColdGen++;
3802 mFastMixerFutex = 0;
3803 sq->end();
3804 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3805 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3806 if (kUseFastMixer == FastMixer_Dynamic) {
3807 mNormalSink = mOutputSink;
3808 }
3809#ifdef AUDIO_WATCHDOG
3810 if (mAudioWatchdog != 0) {
3811 mAudioWatchdog->pause();
3812 }
3813#endif
3814 } else {
3815 sq->end(false /*didModify*/);
3816 }
3817 }
3818 PlaybackThread::threadLoop_standby();
3819}
3820
Eric Laurentbfb1b832013-01-07 09:53:42 -08003821bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3822{
3823 return false;
3824}
3825
3826bool AudioFlinger::PlaybackThread::shouldStandby_l()
3827{
3828 return !mStandby;
3829}
3830
3831bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3832{
3833 Mutex::Autolock _l(mLock);
3834 return waitingAsyncCallback_l();
3835}
3836
Eric Laurent81784c32012-11-19 14:55:58 -08003837// shared by MIXER and DIRECT, overridden by DUPLICATING
3838void AudioFlinger::PlaybackThread::threadLoop_standby()
3839{
3840 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003841 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003842 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003843 // discard any pending drain or write ack by incrementing sequence
3844 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3845 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003846 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003847 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3848 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003849 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003850 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003851}
3852
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003853void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3854{
3855 ALOGV("signal playback thread");
3856 broadcast_l();
3857}
3858
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003859void AudioFlinger::PlaybackThread::onAsyncError()
3860{
3861 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3862 invalidateTracks((audio_stream_type_t)i);
3863 }
3864}
3865
Eric Laurent81784c32012-11-19 14:55:58 -08003866void AudioFlinger::MixerThread::threadLoop_mix()
3867{
Eric Laurent81784c32012-11-19 14:55:58 -08003868 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003869 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003870 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003871 // increase sleep time progressively when application underrun condition clears.
3872 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3873 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3874 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003875 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003876 sleepTimeShift--;
3877 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003878 mSleepTimeUs = 0;
3879 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003880 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003881
Eric Laurent81784c32012-11-19 14:55:58 -08003882}
3883
3884void AudioFlinger::MixerThread::threadLoop_sleepTime()
3885{
3886 // If no tracks are ready, sleep once for the duration of an output
3887 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003888 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003889 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003890 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3891 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3892 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003893 }
3894 // reduce sleep time in case of consecutive application underruns to avoid
3895 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3896 // duration we would end up writing less data than needed by the audio HAL if
3897 // the condition persists.
3898 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3899 sleepTimeShift++;
3900 }
3901 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003902 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003903 }
3904 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003905 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3906 // before effects processing or output.
3907 if (mMixerBufferValid) {
3908 memset(mMixerBuffer, 0, mMixerBufferSize);
3909 } else {
3910 memset(mSinkBuffer, 0, mSinkBufferSize);
3911 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003912 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003913 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3914 "anticipated start");
3915 }
3916 // TODO add standby time extension fct of effect tail
3917}
3918
3919// prepareTracks_l() must be called with ThreadBase::mLock held
3920AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3921 Vector< sp<Track> > *tracksToRemove)
3922{
3923
3924 mixer_state mixerStatus = MIXER_IDLE;
3925 // find out which tracks need to be processed
3926 size_t count = mActiveTracks.size();
3927 size_t mixedTracks = 0;
3928 size_t tracksWithEffect = 0;
3929 // counts only _active_ fast tracks
3930 size_t fastTracks = 0;
3931 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
3932
3933 float masterVolume = mMasterVolume;
3934 bool masterMute = mMasterMute;
3935
3936 if (masterMute) {
3937 masterVolume = 0;
3938 }
3939 // Delegate master volume control to effect in output mix effect chain if needed
3940 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
3941 if (chain != 0) {
3942 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
3943 chain->setVolume_l(&v, &v);
3944 masterVolume = (float)((v + (1 << 23)) >> 24);
3945 chain.clear();
3946 }
3947
3948 // prepare a new state to push
3949 FastMixerStateQueue *sq = NULL;
3950 FastMixerState *state = NULL;
3951 bool didModify = false;
3952 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003953 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003954 sq = mFastMixer->sq();
3955 state = sq->begin();
3956 }
3957
Andy Hung69aed5f2014-02-25 17:24:40 -08003958 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08003959 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08003960
Eric Laurent81784c32012-11-19 14:55:58 -08003961 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07003962 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003963
3964 // this const just means the local variable doesn't change
3965 Track* const track = t.get();
3966
3967 // process fast tracks
3968 if (track->isFastTrack()) {
3969
3970 // It's theoretically possible (though unlikely) for a fast track to be created
3971 // and then removed within the same normal mix cycle. This is not a problem, as
3972 // the track never becomes active so it's fast mixer slot is never touched.
3973 // The converse, of removing an (active) track and then creating a new track
3974 // at the identical fast mixer slot within the same normal mix cycle,
3975 // is impossible because the slot isn't marked available until the end of each cycle.
3976 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003977 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003978 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
3979 FastTrack *fastTrack = &state->mFastTracks[j];
3980
3981 // Determine whether the track is currently in underrun condition,
3982 // and whether it had a recent underrun.
3983 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
3984 FastTrackUnderruns underruns = ftDump->mUnderruns;
3985 uint32_t recentFull = (underruns.mBitFields.mFull -
3986 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
3987 uint32_t recentPartial = (underruns.mBitFields.mPartial -
3988 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
3989 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
3990 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
3991 uint32_t recentUnderruns = recentPartial + recentEmpty;
3992 track->mObservedUnderruns = underruns;
3993 // don't count underruns that occur while stopping or pausing
3994 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07003995 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
3996 recentUnderruns > 0) {
3997 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
3998 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08003999 } else {
4000 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004001 }
4002
4003 // This is similar to the state machine for normal tracks,
4004 // with a few modifications for fast tracks.
4005 bool isActive = true;
4006 switch (track->mState) {
4007 case TrackBase::STOPPING_1:
4008 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004009 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004010 track->mState = TrackBase::STOPPING_2;
4011 }
4012 break;
4013 case TrackBase::PAUSING:
4014 // ramp down is not yet implemented
4015 track->setPaused();
4016 break;
4017 case TrackBase::RESUMING:
4018 // ramp up is not yet implemented
4019 track->mState = TrackBase::ACTIVE;
4020 break;
4021 case TrackBase::ACTIVE:
4022 if (recentFull > 0 || recentPartial > 0) {
4023 // track has provided at least some frames recently: reset retry count
4024 track->mRetryCount = kMaxTrackRetries;
4025 }
4026 if (recentUnderruns == 0) {
4027 // no recent underruns: stay active
4028 break;
4029 }
4030 // there has recently been an underrun of some kind
4031 if (track->sharedBuffer() == 0) {
4032 // were any of the recent underruns "empty" (no frames available)?
4033 if (recentEmpty == 0) {
4034 // no, then ignore the partial underruns as they are allowed indefinitely
4035 break;
4036 }
4037 // there has recently been an "empty" underrun: decrement the retry counter
4038 if (--(track->mRetryCount) > 0) {
4039 break;
4040 }
4041 // indicate to client process that the track was disabled because of underrun;
4042 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004043 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004044 // remove from active list, but state remains ACTIVE [confusing but true]
4045 isActive = false;
4046 break;
4047 }
4048 // fall through
4049 case TrackBase::STOPPING_2:
4050 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004051 case TrackBase::STOPPED:
4052 case TrackBase::FLUSHED: // flush() while active
4053 // Check for presentation complete if track is inactive
4054 // We have consumed all the buffers of this track.
4055 // This would be incomplete if we auto-paused on underrun
4056 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004057 uint32_t latency = 0;
4058 status_t result = mOutput->stream->getLatency(&latency);
4059 ALOGE_IF(result != OK,
4060 "Error when retrieving output stream latency: %d", result);
4061 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004062 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004063 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4064 // track stays in active list until presentation is complete
4065 break;
4066 }
4067 }
4068 if (track->isStopping_2()) {
4069 track->mState = TrackBase::STOPPED;
4070 }
4071 if (track->isStopped()) {
4072 // Can't reset directly, as fast mixer is still polling this track
4073 // track->reset();
4074 // So instead mark this track as needing to be reset after push with ack
4075 resetMask |= 1 << i;
4076 }
4077 isActive = false;
4078 break;
4079 case TrackBase::IDLE:
4080 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004081 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004082 }
4083
4084 if (isActive) {
4085 // was it previously inactive?
4086 if (!(state->mTrackMask & (1 << j))) {
4087 ExtendedAudioBufferProvider *eabp = track;
4088 VolumeProvider *vp = track;
4089 fastTrack->mBufferProvider = eabp;
4090 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004091 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004092 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004093 fastTrack->mGeneration++;
4094 state->mTrackMask |= 1 << j;
4095 didModify = true;
4096 // no acknowledgement required for newly active tracks
4097 }
4098 // cache the combined master volume and stream type volume for fast mixer; this
4099 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Glenn Kastene4756fe2012-11-29 13:38:14 -08004100 track->mCachedVolume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurent81784c32012-11-19 14:55:58 -08004101 ++fastTracks;
4102 } else {
4103 // was it previously active?
4104 if (state->mTrackMask & (1 << j)) {
4105 fastTrack->mBufferProvider = NULL;
4106 fastTrack->mGeneration++;
4107 state->mTrackMask &= ~(1 << j);
4108 didModify = true;
4109 // If any fast tracks were removed, we must wait for acknowledgement
4110 // because we're about to decrement the last sp<> on those tracks.
4111 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4112 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004113 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4114 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4115 j, track->mState, state->mTrackMask, recentUnderruns,
4116 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004117 }
4118 tracksToRemove->add(track);
4119 // Avoids a misleading display in dumpsys
4120 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4121 }
4122 continue;
4123 }
4124
4125 { // local variable scope to avoid goto warning
4126
4127 audio_track_cblk_t* cblk = track->cblk();
4128
4129 // The first time a track is added we wait
4130 // for all its buffers to be filled before processing it
4131 int name = track->name();
4132 // make sure that we have enough frames to mix one full buffer.
4133 // enforce this condition only once to enable draining the buffer in case the client
4134 // app does not call stop() and relies on underrun to stop:
4135 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4136 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004137 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004138 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004139 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004140
4141 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004142 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004143 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4144 // add frames already consumed but not yet released by the resampler
4145 // because mAudioTrackServerProxy->framesReady() will include these frames
4146 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4147
Eric Laurent81784c32012-11-19 14:55:58 -08004148 uint32_t minFrames = 1;
4149 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4150 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004151 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004152 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004153
4154 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004155 if (ATRACE_ENABLED()) {
4156 // I wish we had formatted trace names
4157 char traceName[16];
4158 strcpy(traceName, "nRdy");
4159 int name = track->name();
4160 if (AudioMixer::TRACK0 <= name &&
4161 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4162 name -= AudioMixer::TRACK0;
4163 traceName[4] = (name / 10) + '0';
4164 traceName[5] = (name % 10) + '0';
4165 } else {
4166 traceName[4] = '?';
4167 traceName[5] = '?';
4168 }
4169 traceName[6] = '\0';
4170 ATRACE_INT(traceName, framesReady);
4171 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004172 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004173 !track->isPaused() && !track->isTerminated())
4174 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004175 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004176
4177 mixedTracks++;
4178
Andy Hung69aed5f2014-02-25 17:24:40 -08004179 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4180 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004181 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004182 if (track->mainBuffer() != mSinkBuffer &&
4183 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004184 if (mEffectBufferEnabled) {
4185 mEffectBufferValid = true; // Later can set directly.
4186 }
Eric Laurent81784c32012-11-19 14:55:58 -08004187 chain = getEffectChain_l(track->sessionId());
4188 // Delegate volume control to effect in track effect chain if needed
4189 if (chain != 0) {
4190 tracksWithEffect++;
4191 } else {
4192 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4193 "session %d",
4194 name, track->sessionId());
4195 }
4196 }
4197
4198
4199 int param = AudioMixer::VOLUME;
4200 if (track->mFillingUpStatus == Track::FS_FILLED) {
4201 // no ramp for the first volume setting
4202 track->mFillingUpStatus = Track::FS_ACTIVE;
4203 if (track->mState == TrackBase::RESUMING) {
4204 track->mState = TrackBase::ACTIVE;
4205 param = AudioMixer::RAMP_VOLUME;
4206 }
4207 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004208 // FIXME should not make a decision based on mServer
4209 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004210 // If the track is stopped before the first frame was mixed,
4211 // do not apply ramp
4212 param = AudioMixer::RAMP_VOLUME;
4213 }
4214
4215 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004216 uint32_t vl, vr; // in U8.24 integer format
4217 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004218 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004219 vl = vr = 0;
4220 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004221 if (track->isPausing()) {
4222 track->setPaused();
4223 }
4224 } else {
4225
4226 // read original volumes with volume control
4227 float typeVolume = mStreamTypes[track->streamType()].volume;
4228 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004229 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004230 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004231 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4232 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004233 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004234 if (vlf > GAIN_FLOAT_UNITY) {
4235 ALOGV("Track left volume out of range: %.3g", vlf);
4236 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004237 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004238 if (vrf > GAIN_FLOAT_UNITY) {
4239 ALOGV("Track right volume out of range: %.3g", vrf);
4240 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004241 }
4242 // now apply the master volume and stream type volume
Andy Hung6be49402014-05-30 10:42:03 -07004243 vlf *= v;
4244 vrf *= v;
Eric Laurent81784c32012-11-19 14:55:58 -08004245 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004246 // then derive vl and vr as U8.24 versions for the effect chain
4247 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4248 vl = (uint32_t) (scaleto8_24 * vlf);
4249 vr = (uint32_t) (scaleto8_24 * vrf);
4250 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004251 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004252 // send level comes from shared memory and so may be corrupt
4253 if (sendLevel > MAX_GAIN_INT) {
4254 ALOGV("Track send level out of range: %04X", sendLevel);
4255 sendLevel = MAX_GAIN_INT;
4256 }
Andy Hung6be49402014-05-30 10:42:03 -07004257 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4258 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004259 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004260
Eric Laurent81784c32012-11-19 14:55:58 -08004261 // Delegate volume control to effect in track effect chain if needed
4262 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4263 // Do not ramp volume if volume is controlled by effect
4264 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004265 // Update remaining floating point volume levels
4266 vlf = (float)vl / (1 << 24);
4267 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004268 track->mHasVolumeController = true;
4269 } else {
4270 // force no volume ramp when volume controller was just disabled or removed
4271 // from effect chain to avoid volume spike
4272 if (track->mHasVolumeController) {
4273 param = AudioMixer::VOLUME;
4274 }
4275 track->mHasVolumeController = false;
4276 }
4277
Eric Laurent81784c32012-11-19 14:55:58 -08004278 // XXX: these things DON'T need to be done each time
4279 mAudioMixer->setBufferProvider(name, track);
4280 mAudioMixer->enable(name);
4281
Andy Hung6be49402014-05-30 10:42:03 -07004282 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4283 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4284 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004285 mAudioMixer->setParameter(
4286 name,
4287 AudioMixer::TRACK,
4288 AudioMixer::FORMAT, (void *)track->format());
4289 mAudioMixer->setParameter(
4290 name,
4291 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004292 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004293 mAudioMixer->setParameter(
4294 name,
4295 AudioMixer::TRACK,
4296 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004297 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004298 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004299 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004300 if (reqSampleRate == 0) {
4301 reqSampleRate = mSampleRate;
4302 } else if (reqSampleRate > maxSampleRate) {
4303 reqSampleRate = maxSampleRate;
4304 }
Eric Laurent81784c32012-11-19 14:55:58 -08004305 mAudioMixer->setParameter(
4306 name,
4307 AudioMixer::RESAMPLE,
4308 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004309 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004310
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004311 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004312 mAudioMixer->setParameter(
4313 name,
4314 AudioMixer::TIMESTRETCH,
4315 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004316 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004317
Andy Hung69aed5f2014-02-25 17:24:40 -08004318 /*
4319 * Select the appropriate output buffer for the track.
4320 *
Andy Hung98ef9782014-03-04 14:46:50 -08004321 * Tracks with effects go into their own effects chain buffer
4322 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004323 *
4324 * Other tracks can use mMixerBuffer for higher precision
4325 * channel accumulation. If this buffer is enabled
4326 * (mMixerBufferEnabled true), then selected tracks will accumulate
4327 * into it.
4328 *
4329 */
4330 if (mMixerBufferEnabled
4331 && (track->mainBuffer() == mSinkBuffer
4332 || track->mainBuffer() == mMixerBuffer)) {
4333 mAudioMixer->setParameter(
4334 name,
4335 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004336 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004337 mAudioMixer->setParameter(
4338 name,
4339 AudioMixer::TRACK,
4340 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4341 // TODO: override track->mainBuffer()?
4342 mMixerBufferValid = true;
4343 } else {
4344 mAudioMixer->setParameter(
4345 name,
4346 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004347 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004348 mAudioMixer->setParameter(
4349 name,
4350 AudioMixer::TRACK,
4351 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4352 }
Eric Laurent81784c32012-11-19 14:55:58 -08004353 mAudioMixer->setParameter(
4354 name,
4355 AudioMixer::TRACK,
4356 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4357
4358 // reset retry count
4359 track->mRetryCount = kMaxTrackRetries;
4360
4361 // If one track is ready, set the mixer ready if:
4362 // - the mixer was not ready during previous round OR
4363 // - no other track is not ready
4364 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4365 mixerStatus != MIXER_TRACKS_ENABLED) {
4366 mixerStatus = MIXER_TRACKS_READY;
4367 }
4368 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004369 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004370 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4371 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004372 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004373 } else {
4374 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004375 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004376
Eric Laurent81784c32012-11-19 14:55:58 -08004377 // clear effect chain input buffer if an active track underruns to avoid sending
4378 // previous audio buffer again to effects
4379 chain = getEffectChain_l(track->sessionId());
4380 if (chain != 0) {
4381 chain->clearInputBuffer();
4382 }
4383
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004384 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004385 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4386 track->isStopped() || track->isPaused()) {
4387 // We have consumed all the buffers of this track.
4388 // Remove it from the list of active tracks.
4389 // TODO: use actual buffer filling status instead of latency when available from
4390 // audio HAL
4391 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004392 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004393 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4394 if (track->isStopped()) {
4395 track->reset();
4396 }
4397 tracksToRemove->add(track);
4398 }
4399 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004400 // No buffers for this track. Give it a few chances to
4401 // fill a buffer, then remove it from active list.
4402 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004403 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004404 tracksToRemove->add(track);
4405 // indicate to client process that the track was disabled because of underrun;
4406 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004407 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004408 // If one track is not ready, mark the mixer also not ready if:
4409 // - the mixer was ready during previous round OR
4410 // - no other track is ready
4411 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4412 mixerStatus != MIXER_TRACKS_READY) {
4413 mixerStatus = MIXER_TRACKS_ENABLED;
4414 }
4415 }
4416 mAudioMixer->disable(name);
4417 }
4418
4419 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004420
4421 }
4422
4423 // Push the new FastMixer state if necessary
4424 bool pauseAudioWatchdog = false;
4425 if (didModify) {
4426 state->mFastTracksGen++;
4427 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4428 if (kUseFastMixer == FastMixer_Dynamic &&
4429 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4430 state->mCommand = FastMixerState::COLD_IDLE;
4431 state->mColdFutexAddr = &mFastMixerFutex;
4432 state->mColdGen++;
4433 mFastMixerFutex = 0;
4434 if (kUseFastMixer == FastMixer_Dynamic) {
4435 mNormalSink = mOutputSink;
4436 }
4437 // If we go into cold idle, need to wait for acknowledgement
4438 // so that fast mixer stops doing I/O.
4439 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4440 pauseAudioWatchdog = true;
4441 }
Eric Laurent81784c32012-11-19 14:55:58 -08004442 }
4443 if (sq != NULL) {
4444 sq->end(didModify);
4445 sq->push(block);
4446 }
4447#ifdef AUDIO_WATCHDOG
4448 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4449 mAudioWatchdog->pause();
4450 }
4451#endif
4452
4453 // Now perform the deferred reset on fast tracks that have stopped
4454 while (resetMask != 0) {
4455 size_t i = __builtin_ctz(resetMask);
4456 ALOG_ASSERT(i < count);
4457 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004458 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004459 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4460 track->reset();
4461 }
4462
4463 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004464 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004465
Eric Laurent97d547d2014-09-02 14:45:53 -07004466 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4467 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004468 }
4469
4470 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004471 // as long as there are effects we should clear the effects buffer, to avoid
4472 // passing a non-clean buffer to the effect chain
4473 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004474 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004475 // sink or mix buffer must be cleared if all tracks are connected to an
4476 // effect chain as in this case the mixer will not write to the sink or mix buffer
4477 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004478 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4479 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004480 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004481 if (mMixerBufferValid) {
4482 memset(mMixerBuffer, 0, mMixerBufferSize);
4483 // TODO: In testing, mSinkBuffer below need not be cleared because
4484 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4485 // after mixing.
4486 //
4487 // To enforce this guarantee:
4488 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4489 // (mixedTracks == 0 && fastTracks > 0))
4490 // must imply MIXER_TRACKS_READY.
4491 // Later, we may clear buffers regardless, and skip much of this logic.
4492 }
Andy Hung98ef9782014-03-04 14:46:50 -08004493 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004494 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004495 }
4496
4497 // if any fast tracks, then status is ready
4498 mMixerStatusIgnoringFastTracks = mixerStatus;
4499 if (fastTracks > 0) {
4500 mixerStatus = MIXER_TRACKS_READY;
4501 }
4502 return mixerStatus;
4503}
4504
Eric Laurentad7dd962016-09-22 12:38:37 -07004505// trackCountForUid_l() must be called with ThreadBase::mLock held
4506uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4507{
4508 uint32_t trackCount = 0;
4509 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004510 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004511 trackCount++;
4512 }
4513 }
4514 return trackCount;
4515}
4516
Eric Laurent81784c32012-11-19 14:55:58 -08004517// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004518int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004519 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004520{
Eric Laurentad7dd962016-09-22 12:38:37 -07004521 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4522 return -1;
4523 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004524 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004525}
4526
4527// deleteTrackName_l() must be called with ThreadBase::mLock held
4528void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4529{
4530 ALOGV("remove track (%d) and delete from mixer", name);
4531 mAudioMixer->deleteTrackName(name);
4532}
4533
Eric Laurent10351942014-05-08 18:49:52 -07004534// checkForNewParameter_l() must be called with ThreadBase::mLock held
4535bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4536 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004537{
Eric Laurent81784c32012-11-19 14:55:58 -08004538 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004539 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004540
Eric Laurent10351942014-05-08 18:49:52 -07004541 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004542
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004543 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004544
Eric Laurent10351942014-05-08 18:49:52 -07004545 AudioParameter param = AudioParameter(keyValuePair);
4546 int value;
4547 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4548 reconfig = true;
4549 }
4550 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004551 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004552 status = BAD_VALUE;
4553 } else {
4554 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004555 reconfig = true;
4556 }
Eric Laurent10351942014-05-08 18:49:52 -07004557 }
4558 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004559 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004560 status = BAD_VALUE;
4561 } else {
4562 // no need to save value, since it's constant
4563 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004564 }
Eric Laurent10351942014-05-08 18:49:52 -07004565 }
4566 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4567 // do not accept frame count changes if tracks are open as the track buffer
4568 // size depends on frame count and correct behavior would not be guaranteed
4569 // if frame count is changed after track creation
4570 if (!mTracks.isEmpty()) {
4571 status = INVALID_OPERATION;
4572 } else {
4573 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004574 }
Eric Laurent10351942014-05-08 18:49:52 -07004575 }
4576 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004577#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004578 // when changing the audio output device, call addBatteryData to notify
4579 // the change
4580 if (mOutDevice != value) {
4581 uint32_t params = 0;
4582 // check whether speaker is on
4583 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4584 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004585 }
Eric Laurent10351942014-05-08 18:49:52 -07004586
4587 audio_devices_t deviceWithoutSpeaker
4588 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4589 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004590 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004591 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4592 }
4593
4594 if (params != 0) {
4595 addBatteryData(params);
4596 }
4597 }
Eric Laurent81784c32012-11-19 14:55:58 -08004598#endif
4599
Eric Laurent10351942014-05-08 18:49:52 -07004600 // forward device change to effects that have requested to be
4601 // aware of attached audio device.
4602 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004603 a2dpDeviceChanged =
4604 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004605 mOutDevice = value;
4606 for (size_t i = 0; i < mEffectChains.size(); i++) {
4607 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004608 }
4609 }
Eric Laurent10351942014-05-08 18:49:52 -07004610 }
Eric Laurent81784c32012-11-19 14:55:58 -08004611
Eric Laurent10351942014-05-08 18:49:52 -07004612 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004613 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004614 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004615 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004616 mStandby = true;
4617 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004618 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004619 }
Eric Laurent10351942014-05-08 18:49:52 -07004620 if (status == NO_ERROR && reconfig) {
4621 readOutputParameters_l();
4622 delete mAudioMixer;
4623 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4624 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004625 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004626 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004627 if (name < 0) {
4628 break;
4629 }
4630 mTracks[i]->mName = name;
4631 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004632 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004633 }
Eric Laurent81784c32012-11-19 14:55:58 -08004634 }
4635
Eric Laurent42537be2016-01-08 17:16:42 -08004636 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004637}
4638
4639
4640void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4641{
Eric Laurent81784c32012-11-19 14:55:58 -08004642 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004643 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004644 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004645 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004646
4647 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
Glenn Kasten2f90c512015-12-02 11:40:09 -08004648 // while we are dumping it. It may be inconsistent, but it won't mutate!
4649 // This is a large object so we place it on the heap.
4650 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4651 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4652 copy->dump(fd);
4653 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004654
4655#ifdef STATE_QUEUE_DUMP
4656 // Similar for state queue
4657 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4658 observerCopy.dump(fd);
4659 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4660 mutatorCopy.dump(fd);
4661#endif
4662
Glenn Kasten46909e72013-02-26 09:20:22 -08004663#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004664 // Write the tee output to a .wav file
4665 dumpTee(fd, mTeeSource, mId);
Glenn Kasten46909e72013-02-26 09:20:22 -08004666#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004667
4668#ifdef AUDIO_WATCHDOG
4669 if (mAudioWatchdog != 0) {
4670 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4671 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4672 wdCopy.dump(fd);
4673 }
4674#endif
4675}
4676
4677uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4678{
4679 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4680}
4681
4682uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4683{
4684 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4685}
4686
4687void AudioFlinger::MixerThread::cacheParameters_l()
4688{
4689 PlaybackThread::cacheParameters_l();
4690
4691 // FIXME: Relaxed timing because of a certain device that can't meet latency
4692 // Should be reduced to 2x after the vendor fixes the driver issue
4693 // increase threshold again due to low power audio mode. The way this warning
4694 // threshold is calculated and its usefulness should be reconsidered anyway.
4695 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4696}
4697
4698// ----------------------------------------------------------------------------
4699
4700AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004701 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4702 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004703 // mLeftVolFloat, mRightVolFloat
4704{
4705}
4706
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4708 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004709 ThreadBase::type_t type, bool systemReady)
4710 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004711 // mLeftVolFloat, mRightVolFloat
4712{
4713}
4714
Eric Laurent81784c32012-11-19 14:55:58 -08004715AudioFlinger::DirectOutputThread::~DirectOutputThread()
4716{
4717}
4718
Eric Laurent5850c4c2016-11-10 13:04:31 -08004719void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004720{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004721 float left, right;
4722
4723 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4724 left = right = 0;
4725 } else {
4726 float typeVolume = mStreamTypes[track->streamType()].volume;
4727 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004728 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004729 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4730 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4731 if (left > GAIN_FLOAT_UNITY) {
4732 left = GAIN_FLOAT_UNITY;
4733 }
4734 left *= v;
4735 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4736 if (right > GAIN_FLOAT_UNITY) {
4737 right = GAIN_FLOAT_UNITY;
4738 }
4739 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004740 }
4741
4742 if (lastTrack) {
4743 if (left != mLeftVolFloat || right != mRightVolFloat) {
4744 mLeftVolFloat = left;
4745 mRightVolFloat = right;
4746
4747 // Convert volumes from float to 8.24
4748 uint32_t vl = (uint32_t)(left * (1 << 24));
4749 uint32_t vr = (uint32_t)(right * (1 << 24));
4750
4751 // Delegate volume control to effect in track effect chain if needed
4752 // only one effect chain can be present on DirectOutputThread, so if
4753 // there is one, the track is connected to it
4754 if (!mEffectChains.isEmpty()) {
4755 mEffectChains[0]->setVolume_l(&vl, &vr);
4756 left = (float)vl / (1 << 24);
4757 right = (float)vr / (1 << 24);
4758 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004759 status_t result = mOutput->stream->setVolume(left, right);
4760 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004761 }
4762 }
4763}
4764
Phil Burk43b4dcc2015-06-09 16:53:44 -07004765void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4766{
4767 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004768 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004769
Eric Laurent0f0631e2015-07-06 18:01:25 -07004770 if (previousTrack != 0 && latestTrack != 0) {
4771 if (mType == DIRECT) {
4772 if (previousTrack.get() != latestTrack.get()) {
4773 mFlushPending = true;
4774 }
4775 } else /* mType == OFFLOAD */ {
4776 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4777 mFlushPending = true;
4778 }
4779 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004780 }
4781 PlaybackThread::onAddNewTrack_l();
4782}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004783
Eric Laurent81784c32012-11-19 14:55:58 -08004784AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4785 Vector< sp<Track> > *tracksToRemove
4786)
4787{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004788 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004789 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004790 bool doHwPause = false;
4791 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004792
4793 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004794 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004795 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004796 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004797 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004798 continue;
4799 }
4800
Eric Laurent5850c4c2016-11-10 13:04:31 -08004801 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004802#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004803 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004804#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004805 // Only consider last track started for volume and mixer state control.
4806 // In theory an older track could underrun and restart after the new one starts
4807 // but as we only care about the transition phase between two tracks on a
4808 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004809 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004810 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004811
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004812 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004813 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004814 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004815 doHwPause = true;
4816 mHwPaused = true;
4817 }
4818 tracksToRemove->add(track);
4819 } else if (track->isFlushPending()) {
4820 track->flushAck();
4821 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004822 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004823 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004824 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004825 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004826 if (last) {
4827 mLeftVolFloat = mRightVolFloat = -1.0;
4828 if (mHwPaused) {
4829 doHwResume = true;
4830 mHwPaused = false;
4831 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004832 }
4833 }
4834
Eric Laurent81784c32012-11-19 14:55:58 -08004835 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004836 // for all its buffers to be filled before processing it.
4837 // Allow draining the buffer in case the client
4838 // app does not call stop() and relies on underrun to stop:
4839 // hence the test on (track->mRetryCount > 1).
4840 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004841 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004842 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004843 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004844 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004845 minFrames = mNormalFrameCount;
4846 } else {
4847 minFrames = 1;
4848 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849
Eric Laurentab5cdba2014-06-09 17:22:27 -07004850 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4851 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004852 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004853 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004854
4855 if (track->mFillingUpStatus == Track::FS_FILLED) {
4856 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004857 if (last) {
4858 // make sure processVolume_l() will apply new volume even if 0
4859 mLeftVolFloat = mRightVolFloat = -1.0;
4860 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004861 if (!mHwSupportsPause) {
4862 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004863 }
4864 }
4865
4866 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 processVolume_l(track, last);
4868 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004869 sp<Track> previousTrack = mPreviousTrack.promote();
4870 if (previousTrack != 0) {
4871 if (track != previousTrack.get()) {
4872 // Flush any data still being written from last track
4873 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004874 // Invalidate previous track to force a seek when resuming.
4875 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004876 }
4877 }
4878 mPreviousTrack = track;
4879
Eric Laurentd595b7c2013-04-03 17:27:56 -07004880 // reset retry count
4881 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004882 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004883 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004884 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004885 doHwResume = true;
4886 mHwPaused = false;
4887 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004888 }
Eric Laurent81784c32012-11-19 14:55:58 -08004889 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004890 // clear effect chain input buffer if the last active track started underruns
4891 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07004892 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08004893 mEffectChains[0]->clearInputBuffer();
4894 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004895 if (track->isStopping_1()) {
4896 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07004897 if (last && mHwPaused) {
4898 doHwResume = true;
4899 mHwPaused = false;
4900 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07004901 }
4902 if ((track->sharedBuffer() != 0) || track->isStopped() ||
4903 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004904 // We have consumed all the buffers of this track.
4905 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07004906 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08004907 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004908 audioHALFrames = (latency_l() * mSampleRate) / 1000;
4909 } else {
4910 audioHALFrames = 0;
4911 }
4912
Andy Hung818e7a32016-02-16 18:08:07 -08004913 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07004914 if (mStandby || !last ||
4915 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07004916 if (track->isStopping_2()) {
4917 track->mState = TrackBase::STOPPED;
4918 }
Eric Laurent81784c32012-11-19 14:55:58 -08004919 if (track->isStopped()) {
4920 track->reset();
4921 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004922 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08004923 }
4924 } else {
4925 // No buffers for this track. Give it a few chances to
4926 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07004927 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08004928 if (--(track->mRetryCount) <= 0) {
4929 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07004930 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08004931 // indicate to client process that the track was disabled because of underrun;
4932 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004933 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004934 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07004935 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
4936 "minFrames = %u, mFormat = %#x",
4937 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08004938 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07004939 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004940 doHwPause = true;
4941 mHwPaused = true;
4942 }
Eric Laurent81784c32012-11-19 14:55:58 -08004943 }
4944 }
4945 }
4946 }
4947
Eric Laurentd1f69b02014-12-15 14:33:13 -08004948 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07004949 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004950 for (size_t i = 0; i < mTracks.size(); i++) {
4951 if (mTracks[i]->isFlushPending()) {
4952 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004953 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004954 }
4955 }
4956 }
4957
4958 // make sure the pause/flush/resume sequence is executed in the right order.
4959 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
4960 // before flush and then resume HW. This can happen in case of pause/flush/resume
4961 // if resume is received before pause is executed.
4962 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07004963 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004964 status_t result = mOutput->stream->pause();
4965 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004966 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004967 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004968 flushHw_l();
4969 }
4970 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004971 status_t result = mOutput->stream->resume();
4972 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08004973 }
Eric Laurent81784c32012-11-19 14:55:58 -08004974 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004975 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004976
4977 return mixerStatus;
4978}
4979
4980void AudioFlinger::DirectOutputThread::threadLoop_mix()
4981{
Eric Laurent81784c32012-11-19 14:55:58 -08004982 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08004983 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004984 // output audio to hardware
4985 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07004986 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08004987 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08004988 status_t status = mActiveTrack->getNextBuffer(&buffer);
4989 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08004990 // no need to pad with 0 for compressed audio
4991 if (audio_has_proportional_frames(mFormat)) {
4992 memset(curBuf, 0, frameCount * mFrameSize);
4993 }
Eric Laurent81784c32012-11-19 14:55:58 -08004994 break;
4995 }
4996 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
4997 frameCount -= buffer.frameCount;
4998 curBuf += buffer.frameCount * mFrameSize;
4999 mActiveTrack->releaseBuffer(&buffer);
5000 }
Andy Hung2098f272014-02-27 14:00:06 -08005001 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005002 mSleepTimeUs = 0;
5003 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005004 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005005}
5006
5007void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5008{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005009 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005010 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005011 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005012 return;
5013 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005014 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005015 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005016 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005017 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005018 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005019 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005020 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005021 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005022 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005023 }
5024}
5025
Eric Laurentd1f69b02014-12-15 14:33:13 -08005026void AudioFlinger::DirectOutputThread::threadLoop_exit()
5027{
5028 {
5029 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005030 for (size_t i = 0; i < mTracks.size(); i++) {
5031 if (mTracks[i]->isFlushPending()) {
5032 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005033 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005034 }
5035 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005036 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005037 flushHw_l();
5038 }
5039 }
5040 PlaybackThread::threadLoop_exit();
5041}
5042
5043// must be called with thread mutex locked
5044bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5045{
5046 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005047 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005048
vivek mehta9cd7ad12016-03-17 00:18:29 -07005049 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5050 return !mStandby;
5051 }
5052
Eric Laurentd1f69b02014-12-15 14:33:13 -08005053 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5054 // after a timeout and we will enter standby then.
5055 if (mTracks.size() > 0) {
5056 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005057 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5058 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059 }
5060
Eric Laurent5cff4032015-05-26 13:49:58 -07005061 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062}
5063
Eric Laurent81784c32012-11-19 14:55:58 -08005064// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005065int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005066 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005067{
Eric Laurentad7dd962016-09-22 12:38:37 -07005068 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5069 return -1;
5070 }
Eric Laurent81784c32012-11-19 14:55:58 -08005071 return 0;
5072}
5073
5074// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005075void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005076{
5077}
5078
Eric Laurent10351942014-05-08 18:49:52 -07005079// checkForNewParameter_l() must be called with ThreadBase::mLock held
5080bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5081 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005082{
5083 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005084 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005085
Eric Laurent10351942014-05-08 18:49:52 -07005086 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005087
Eric Laurent10351942014-05-08 18:49:52 -07005088 AudioParameter param = AudioParameter(keyValuePair);
5089 int value;
5090 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5091 // forward device change to effects that have requested to be
5092 // aware of attached audio device.
5093 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005094 a2dpDeviceChanged =
5095 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005096 mOutDevice = value;
5097 for (size_t i = 0; i < mEffectChains.size(); i++) {
5098 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005099 }
5100 }
Eric Laurent81784c32012-11-19 14:55:58 -08005101 }
Eric Laurent10351942014-05-08 18:49:52 -07005102 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5103 // do not accept frame count changes if tracks are open as the track buffer
5104 // size depends on frame count and correct behavior would not be garantied
5105 // if frame count is changed after track creation
5106 if (!mTracks.isEmpty()) {
5107 status = INVALID_OPERATION;
5108 } else {
5109 reconfig = true;
5110 }
5111 }
5112 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005113 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005114 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005115 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005116 mStandby = true;
5117 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005118 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005119 }
5120 if (status == NO_ERROR && reconfig) {
5121 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005122 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005123 }
5124 }
5125
Eric Laurent42537be2016-01-08 17:16:42 -08005126 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005127}
5128
5129uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5130{
5131 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005132 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005133 time = PlaybackThread::activeSleepTimeUs();
5134 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005135 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005136 }
5137 return time;
5138}
5139
5140uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5141{
5142 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005143 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005144 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5145 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005146 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005147 }
5148 return time;
5149}
5150
5151uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5152{
5153 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005154 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005155 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5156 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005157 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005158 }
5159 return time;
5160}
5161
5162void AudioFlinger::DirectOutputThread::cacheParameters_l()
5163{
5164 PlaybackThread::cacheParameters_l();
5165
5166 // use shorter standby delay as on normal output to release
5167 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005168 // no delay on outputs with HW A/V sync
5169 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005170 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005171 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005172 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005173 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005174 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005175 }
Eric Laurent81784c32012-11-19 14:55:58 -08005176}
5177
Eric Laurente659ef42014-09-29 13:06:46 -07005178void AudioFlinger::DirectOutputThread::flushHw_l()
5179{
Phil Burk062e67a2015-02-11 13:40:50 -08005180 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005181 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005182 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005183}
5184
Eric Laurent81784c32012-11-19 14:55:58 -08005185// ----------------------------------------------------------------------------
5186
Eric Laurentbfb1b832013-01-07 09:53:42 -08005187AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005188 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005189 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005190 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005191 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005192 mDrainSequence(0),
5193 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005194{
5195}
5196
5197AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5198{
5199}
5200
5201void AudioFlinger::AsyncCallbackThread::onFirstRef()
5202{
5203 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5204}
5205
5206bool AudioFlinger::AsyncCallbackThread::threadLoop()
5207{
5208 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005209 uint32_t writeAckSequence;
5210 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005211 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212
5213 {
5214 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005215 while (!((mWriteAckSequence & 1) ||
5216 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005217 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005218 exitPending())) {
5219 mWaitWorkCV.wait(mLock);
5220 }
5221
Eric Laurentbfb1b832013-01-07 09:53:42 -08005222 if (exitPending()) {
5223 break;
5224 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005225 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5226 mWriteAckSequence, mDrainSequence);
5227 writeAckSequence = mWriteAckSequence;
5228 mWriteAckSequence &= ~1;
5229 drainSequence = mDrainSequence;
5230 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005231 asyncError = mAsyncError;
5232 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005233 }
5234 {
Eric Laurent4de95592013-09-26 15:28:21 -07005235 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5236 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005237 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005238 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005239 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005240 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005241 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005242 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005243 if (asyncError) {
5244 playbackThread->onAsyncError();
5245 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005246 }
5247 }
5248 }
5249 return false;
5250}
5251
5252void AudioFlinger::AsyncCallbackThread::exit()
5253{
5254 ALOGV("AsyncCallbackThread::exit");
5255 Mutex::Autolock _l(mLock);
5256 requestExit();
5257 mWaitWorkCV.broadcast();
5258}
5259
Eric Laurent3b4529e2013-09-05 18:09:19 -07005260void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005261{
5262 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005263 // bit 0 is cleared
5264 mWriteAckSequence = sequence << 1;
5265}
5266
5267void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5268{
5269 Mutex::Autolock _l(mLock);
5270 // ignore unexpected callbacks
5271 if (mWriteAckSequence & 2) {
5272 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005273 mWaitWorkCV.signal();
5274 }
5275}
5276
Eric Laurent3b4529e2013-09-05 18:09:19 -07005277void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005278{
5279 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005280 // bit 0 is cleared
5281 mDrainSequence = sequence << 1;
5282}
5283
5284void AudioFlinger::AsyncCallbackThread::resetDraining()
5285{
5286 Mutex::Autolock _l(mLock);
5287 // ignore unexpected callbacks
5288 if (mDrainSequence & 2) {
5289 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 mWaitWorkCV.signal();
5291 }
5292}
5293
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005294void AudioFlinger::AsyncCallbackThread::setAsyncError()
5295{
5296 Mutex::Autolock _l(mLock);
5297 mAsyncError = true;
5298 mWaitWorkCV.signal();
5299}
5300
Eric Laurentbfb1b832013-01-07 09:53:42 -08005301
5302// ----------------------------------------------------------------------------
5303AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005304 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5305 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005306 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5307 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308{
Eric Laurentfd477972013-10-25 18:10:40 -07005309 //FIXME: mStandby should be set to true by ThreadBase constructor
5310 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005311 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005312}
5313
Eric Laurentbfb1b832013-01-07 09:53:42 -08005314void AudioFlinger::OffloadThread::threadLoop_exit()
5315{
5316 if (mFlushPending || mHwPaused) {
5317 // If a flush is pending or track was paused, just discard buffered data
5318 flushHw_l();
5319 } else {
5320 mMixerStatus = MIXER_DRAIN_ALL;
5321 threadLoop_drain();
5322 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005323 if (mUseAsyncWrite) {
5324 ALOG_ASSERT(mCallbackThread != 0);
5325 mCallbackThread->exit();
5326 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005327 PlaybackThread::threadLoop_exit();
5328}
5329
5330AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5331 Vector< sp<Track> > *tracksToRemove
5332)
5333{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334 size_t count = mActiveTracks.size();
5335
5336 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005337 bool doHwPause = false;
5338 bool doHwResume = false;
5339
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005340 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005341
Eric Laurentbfb1b832013-01-07 09:53:42 -08005342 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005343 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005344 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005345#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005347#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005348 // Only consider last track started for volume and mixer state control.
5349 // In theory an older track could underrun and restart after the new one starts
5350 // but as we only care about the transition phase between two tracks on a
5351 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005352 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005353 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005354
Haynes Mathew George7844f672014-01-15 12:32:55 -08005355 if (track->isInvalid()) {
5356 ALOGW("An invalidated track shouldn't be in active list");
5357 tracksToRemove->add(track);
5358 continue;
5359 }
5360
5361 if (track->mState == TrackBase::IDLE) {
5362 ALOGW("An idle track shouldn't be in active list");
5363 continue;
5364 }
5365
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 if (track->isPausing()) {
5367 track->setPaused();
5368 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005369 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005370 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005371 mHwPaused = true;
5372 }
5373 // If we were part way through writing the mixbuffer to
5374 // the HAL we must save this until we resume
5375 // BUG - this will be wrong if a different track is made active,
5376 // in that case we want to discard the pending data in the
5377 // mixbuffer and tell the client to present it again when the
5378 // track is resumed
5379 mPausedWriteLength = mCurrentWriteLength;
5380 mPausedBytesRemaining = mBytesRemaining;
5381 mBytesRemaining = 0; // stop writing
5382 }
5383 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005384 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005385 if (track->isStopping_1()) {
5386 track->mRetryCount = kMaxTrackStopRetriesOffload;
5387 } else {
5388 track->mRetryCount = kMaxTrackRetriesOffload;
5389 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005390 track->flushAck();
5391 if (last) {
5392 mFlushPending = true;
5393 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005394 } else if (track->isResumePending()){
5395 track->resumeAck();
5396 if (last) {
5397 if (mPausedBytesRemaining) {
5398 // Need to continue write that was interrupted
5399 mCurrentWriteLength = mPausedWriteLength;
5400 mBytesRemaining = mPausedBytesRemaining;
5401 mPausedBytesRemaining = 0;
5402 }
5403 if (mHwPaused) {
5404 doHwResume = true;
5405 mHwPaused = false;
5406 // threadLoop_mix() will handle the case that we need to
5407 // resume an interrupted write
5408 }
5409 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005410 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005411
Eric Laurent3df841a2016-07-15 15:15:40 -07005412 mLeftVolFloat = mRightVolFloat = -1.0;
5413
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005414 // Do not handle new data in this iteration even if track->framesReady()
5415 mixerStatus = MIXER_TRACKS_ENABLED;
5416 }
5417 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005418 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005419 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420 if (track->mFillingUpStatus == Track::FS_FILLED) {
5421 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005422 if (last) {
5423 // make sure processVolume_l() will apply new volume even if 0
5424 mLeftVolFloat = mRightVolFloat = -1.0;
5425 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426 }
5427
5428 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005429 sp<Track> previousTrack = mPreviousTrack.promote();
5430 if (previousTrack != 0) {
5431 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005432 // Flush any data still being written from last track
5433 mBytesRemaining = 0;
5434 if (mPausedBytesRemaining) {
5435 // Last track was paused so we also need to flush saved
5436 // mixbuffer state and invalidate track so that it will
5437 // re-submit that unwritten data when it is next resumed
5438 mPausedBytesRemaining = 0;
5439 // Invalidate is a bit drastic - would be more efficient
5440 // to have a flag to tell client that some of the
5441 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005442 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005443 }
5444 // flush data already sent to the DSP if changing audio session as audio
5445 // comes from a different source. Also invalidate previous track to force a
5446 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005447 if (previousTrack->sessionId() != track->sessionId()) {
5448 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005449 }
5450 }
5451 }
5452 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005453 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005454 if (track->isStopping_1()) {
5455 track->mRetryCount = kMaxTrackStopRetriesOffload;
5456 } else {
5457 track->mRetryCount = kMaxTrackRetriesOffload;
5458 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005459 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 mixerStatus = MIXER_TRACKS_READY;
5461 }
5462 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005463 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005464 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005465 if (--(track->mRetryCount) <= 0) {
5466 // Hardware buffer can hold a large amount of audio so we must
5467 // wait for all current track's data to drain before we say
5468 // that the track is stopped.
5469 if (mBytesRemaining == 0) {
5470 // Only start draining when all data in mixbuffer
5471 // has been written
5472 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5473 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5474 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5475 if (last && !mStandby) {
5476 // do not modify drain sequence if we are already draining. This happens
5477 // when resuming from pause after drain.
5478 if ((mDrainSequence & 1) == 0) {
5479 mSleepTimeUs = 0;
5480 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5481 mixerStatus = MIXER_DRAIN_TRACK;
5482 mDrainSequence += 2;
5483 }
5484 if (mHwPaused) {
5485 // It is possible to move from PAUSED to STOPPING_1 without
5486 // a resume so we must ensure hardware is running
5487 doHwResume = true;
5488 mHwPaused = false;
5489 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005490 }
5491 }
Eric Laurente93cc032016-05-05 10:15:10 -07005492 } else if (last) {
5493 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5494 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 }
5496 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005497 // Drain has completed or we are in standby, signal presentation complete
5498 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005499 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005500 uint32_t latency = 0;
5501 status_t result = mOutput->stream->getLatency(&latency);
5502 ALOGE_IF(result != OK,
5503 "Error when retrieving output stream latency: %d", result);
5504 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005505 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005506 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 track->presentationComplete(framesWritten, audioHALFrames);
5508 track->reset();
5509 tracksToRemove->add(track);
5510 }
5511 } else {
5512 // No buffers for this track. Give it a few chances to
5513 // fill a buffer, then remove it from active list.
5514 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005515 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005516 uint64_t position = 0;
5517 struct timespec unused;
5518 // The running check restarts the retry counter at least once.
5519 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5520 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5521 running = true;
5522 mOffloadUnderrunPosition = position;
5523 }
5524 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005525 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5526 (long long)position, (long long)mOffloadUnderrunPosition);
5527 }
5528 if (running) { // still running, give us more time.
5529 track->mRetryCount = kMaxTrackRetriesOffload;
5530 } else {
5531 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5532 track->name());
5533 tracksToRemove->add(track);
5534 // indicate to client process that the track was disabled because of underrun;
5535 // it will then automatically call start() when data is available
5536 track->disable();
5537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005538 } else if (last){
5539 mixerStatus = MIXER_TRACKS_ENABLED;
5540 }
5541 }
5542 }
5543 // compute volume for this track
5544 processVolume_l(track, last);
5545 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005546
Eric Laurentea0fade2013-10-04 16:23:48 -07005547 // make sure the pause/flush/resume sequence is executed in the right order.
5548 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5549 // before flush and then resume HW. This can happen in case of pause/flush/resume
5550 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005551 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005552 status_t result = mOutput->stream->pause();
5553 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005554 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005555 if (mFlushPending) {
5556 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005557 }
Eric Laurentfd477972013-10-25 18:10:40 -07005558 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005559 status_t result = mOutput->stream->resume();
5560 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005561 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005562
Eric Laurentbfb1b832013-01-07 09:53:42 -08005563 // remove all the tracks that need to be...
5564 removeTracks_l(*tracksToRemove);
5565
5566 return mixerStatus;
5567}
5568
Eric Laurentbfb1b832013-01-07 09:53:42 -08005569// must be called with thread mutex locked
5570bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5571{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005572 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5573 mWriteAckSequence, mDrainSequence);
5574 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 return true;
5576 }
5577 return false;
5578}
5579
Eric Laurentbfb1b832013-01-07 09:53:42 -08005580bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5581{
5582 Mutex::Autolock _l(mLock);
5583 return waitingAsyncCallback_l();
5584}
5585
5586void AudioFlinger::OffloadThread::flushHw_l()
5587{
Eric Laurente659ef42014-09-29 13:06:46 -07005588 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005589 // Flush anything still waiting in the mixbuffer
5590 mCurrentWriteLength = 0;
5591 mBytesRemaining = 0;
5592 mPausedWriteLength = 0;
5593 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005594 // reset bytes written count to reflect that DSP buffers are empty after flush.
5595 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005596 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005597
Eric Laurentbfb1b832013-01-07 09:53:42 -08005598 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005599 // discard any pending drain or write ack by incrementing sequence
5600 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5601 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005602 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005603 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5604 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005605 }
5606}
5607
Haynes Mathew George05317d22016-05-03 16:34:26 -07005608void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5609{
5610 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005611 if (PlaybackThread::invalidateTracks_l(streamType)) {
5612 mFlushPending = true;
5613 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005614}
5615
Eric Laurentbfb1b832013-01-07 09:53:42 -08005616// ----------------------------------------------------------------------------
5617
Eric Laurent81784c32012-11-19 14:55:58 -08005618AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005619 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005620 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005621 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005622 mWaitTimeMs(UINT_MAX)
5623{
5624 addOutputTrack(mainThread);
5625}
5626
5627AudioFlinger::DuplicatingThread::~DuplicatingThread()
5628{
5629 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5630 mOutputTracks[i]->destroy();
5631 }
5632}
5633
5634void AudioFlinger::DuplicatingThread::threadLoop_mix()
5635{
5636 // mix buffers...
5637 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005638 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005639 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005640 if (mMixerBufferValid) {
5641 memset(mMixerBuffer, 0, mMixerBufferSize);
5642 } else {
5643 memset(mSinkBuffer, 0, mSinkBufferSize);
5644 }
Eric Laurent81784c32012-11-19 14:55:58 -08005645 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005646 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005647 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005648 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005649 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005650}
5651
5652void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5653{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005654 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005655 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005656 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005657 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005658 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005659 }
5660 } else if (mBytesWritten != 0) {
5661 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5662 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005663 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005664 } else {
5665 // flush remaining overflow buffers in output tracks
5666 writeFrames = 0;
5667 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005668 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005669 }
5670}
5671
Eric Laurentbfb1b832013-01-07 09:53:42 -08005672ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005673{
5674 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005675 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005676 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005677 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005678 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005679}
5680
5681void AudioFlinger::DuplicatingThread::threadLoop_standby()
5682{
5683 // DuplicatingThread implements standby by stopping all tracks
5684 for (size_t i = 0; i < outputTracks.size(); i++) {
5685 outputTracks[i]->stop();
5686 }
5687}
5688
5689void AudioFlinger::DuplicatingThread::saveOutputTracks()
5690{
5691 outputTracks = mOutputTracks;
5692}
5693
5694void AudioFlinger::DuplicatingThread::clearOutputTracks()
5695{
5696 outputTracks.clear();
5697}
5698
5699void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5700{
5701 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005702 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5703 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5704 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5705 const size_t frameCount =
5706 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5707 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5708 // from different OutputTracks and their associated MixerThreads (e.g. one may
5709 // nearly empty and the other may be dropping data).
5710
5711 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005712 this,
5713 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005714 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005715 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005716 frameCount,
5717 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005718 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5719 if (status != NO_ERROR) {
5720 ALOGE("addOutputTrack() initCheck failed %d", status);
5721 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005722 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005723 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5724 mOutputTracks.add(outputTrack);
5725 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5726 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005727}
5728
5729void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5730{
5731 Mutex::Autolock _l(mLock);
5732 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5733 if (mOutputTracks[i]->thread() == thread) {
5734 mOutputTracks[i]->destroy();
5735 mOutputTracks.removeAt(i);
5736 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005737 if (thread->getOutput() == mOutput) {
5738 mOutput = NULL;
5739 }
Eric Laurent81784c32012-11-19 14:55:58 -08005740 return;
5741 }
5742 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005743 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005744}
5745
5746// caller must hold mLock
5747void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5748{
5749 mWaitTimeMs = UINT_MAX;
5750 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5751 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5752 if (strong != 0) {
5753 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5754 if (waitTimeMs < mWaitTimeMs) {
5755 mWaitTimeMs = waitTimeMs;
5756 }
5757 }
5758 }
5759}
5760
5761
5762bool AudioFlinger::DuplicatingThread::outputsReady(
5763 const SortedVector< sp<OutputTrack> > &outputTracks)
5764{
5765 for (size_t i = 0; i < outputTracks.size(); i++) {
5766 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5767 if (thread == 0) {
5768 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5769 outputTracks[i].get());
5770 return false;
5771 }
5772 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5773 // see note at standby() declaration
5774 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5775 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5776 thread.get());
5777 return false;
5778 }
5779 }
5780 return true;
5781}
5782
5783uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5784{
5785 return (mWaitTimeMs * 1000) / 2;
5786}
5787
5788void AudioFlinger::DuplicatingThread::cacheParameters_l()
5789{
5790 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5791 updateWaitTime_l();
5792
5793 MixerThread::cacheParameters_l();
5794}
5795
5796// ----------------------------------------------------------------------------
5797// Record
5798// ----------------------------------------------------------------------------
5799
5800AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5801 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005802 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005803 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005804 audio_devices_t inDevice,
5805 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005806#ifdef TEE_SINK
5807 , const sp<NBAIO_Sink>& teeSink
5808#endif
5809 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005810 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005811 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005812 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005813 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005814#ifdef TEE_SINK
5815 , mTeeSink(teeSink)
5816#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005817 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5818 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005819 // mFastCapture below
5820 , mFastCaptureFutex(0)
5821 // mInputSource
5822 // mPipeSink
5823 // mPipeSource
5824 , mPipeFramesP2(0)
5825 // mPipeMemory
5826 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005827 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005828{
Glenn Kastend7dca052015-03-05 16:05:54 -08005829 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5830 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005831
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005832 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005833
5834 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005835 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005836 size_t numCounterOffers = 0;
5837 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005838#if !LOG_NDEBUG
5839 ssize_t index =
5840#else
5841 (void)
5842#endif
5843 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005844 ALOG_ASSERT(index == 0);
5845
5846 // initialize fast capture depending on configuration
5847 bool initFastCapture;
5848 switch (kUseFastCapture) {
5849 case FastCapture_Never:
5850 initFastCapture = false;
5851 break;
5852 case FastCapture_Always:
5853 initFastCapture = true;
5854 break;
5855 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005856 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005857 break;
5858 // case FastCapture_Dynamic:
5859 }
5860
5861 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005862 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005863 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005864 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5865 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005866 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
5867 void *pipeBuffer;
5868 const sp<MemoryDealer> roHeap(readOnlyHeap());
5869 sp<IMemory> pipeMemory;
5870 if ((roHeap == 0) ||
5871 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
5872 (pipeBuffer = pipeMemory->pointer()) == NULL) {
5873 ALOGE("not enough memory for pipe buffer size=%zu", pipeSize);
5874 goto failed;
5875 }
5876 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
5877 memset(pipeBuffer, 0, pipeSize);
5878 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
5879 const NBAIO_Format offers[1] = {format};
5880 size_t numCounterOffers = 0;
5881 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
5882 ALOG_ASSERT(index == 0);
5883 mPipeSink = pipe;
5884 PipeReader *pipeReader = new PipeReader(*pipe);
5885 numCounterOffers = 0;
5886 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
5887 ALOG_ASSERT(index == 0);
5888 mPipeSource = pipeReader;
5889 mPipeFramesP2 = pipeFramesP2;
5890 mPipeMemory = pipeMemory;
5891
5892 // create fast capture
5893 mFastCapture = new FastCapture();
5894 FastCaptureStateQueue *sq = mFastCapture->sq();
5895#ifdef STATE_QUEUE_DUMP
5896 // FIXME
5897#endif
5898 FastCaptureState *state = sq->begin();
5899 state->mCblk = NULL;
5900 state->mInputSource = mInputSource.get();
5901 state->mInputSourceGen++;
5902 state->mPipeSink = pipe;
5903 state->mPipeSinkGen++;
5904 state->mFrameCount = mFrameCount;
5905 state->mCommand = FastCaptureState::COLD_IDLE;
5906 // already done in constructor initialization list
5907 //mFastCaptureFutex = 0;
5908 state->mColdFutexAddr = &mFastCaptureFutex;
5909 state->mColdGen++;
5910 state->mDumpState = &mFastCaptureDumpState;
5911#ifdef TEE_SINK
5912 // FIXME
5913#endif
5914 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
5915 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
5916 sq->end();
5917 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5918
5919 // start the fast capture
5920 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
5921 pid_t tid = mFastCapture->getTid();
Glenn Kasten8379b722016-03-18 14:54:17 -07005922 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005923 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005924#ifdef AUDIO_WATCHDOG
5925 // FIXME
5926#endif
5927
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005928 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005929 }
5930failed: ;
5931
5932 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08005933}
5934
Eric Laurent81784c32012-11-19 14:55:58 -08005935AudioFlinger::RecordThread::~RecordThread()
5936{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005937 if (mFastCapture != 0) {
5938 FastCaptureStateQueue *sq = mFastCapture->sq();
5939 FastCaptureState *state = sq->begin();
5940 if (state->mCommand == FastCaptureState::COLD_IDLE) {
5941 int32_t old = android_atomic_inc(&mFastCaptureFutex);
5942 if (old == -1) {
5943 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
5944 }
5945 }
5946 state->mCommand = FastCaptureState::EXIT;
5947 sq->end();
5948 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
5949 mFastCapture->join();
5950 mFastCapture.clear();
5951 }
5952 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07005953 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07005954 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08005955}
5956
5957void AudioFlinger::RecordThread::onFirstRef()
5958{
Glenn Kastend7dca052015-03-05 16:05:54 -08005959 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08005960}
5961
Eric Laurent81784c32012-11-19 14:55:58 -08005962bool AudioFlinger::RecordThread::threadLoop()
5963{
Eric Laurent81784c32012-11-19 14:55:58 -08005964 nsecs_t lastWarning = 0;
5965
5966 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08005967
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005968reacquire_wakelock:
5969 sp<RecordTrack> activeTrack;
5970 {
5971 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07005972 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005973 }
5974
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005975 // used to request a deferred sleep, to be executed later while mutex is unlocked
5976 uint32_t sleepUs = 0;
5977
5978 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07005979 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07005980 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07005981
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08005982 // activeTracks accumulates a copy of a subset of mActiveTracks
5983 Vector< sp<RecordTrack> > activeTracks;
5984
Glenn Kasten735f45f2014-08-18 15:51:59 -07005985 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005986 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07005987
Glenn Kasten735f45f2014-08-18 15:51:59 -07005988 // reference to a fast track which is about to be removed
5989 sp<RecordTrack> fastTrackToRemove;
5990
Eric Laurent81784c32012-11-19 14:55:58 -08005991 { // scope for mLock
5992 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08005993
Eric Laurent021cf962014-05-13 10:18:14 -07005994 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08005995
Eric Laurent000a4192014-01-29 15:17:32 -08005996 // check exitPending here because checkForNewParameters_l() and
5997 // checkForNewParameters_l() can temporarily release mLock
5998 if (exitPending()) {
5999 break;
6000 }
6001
Eric Laurent5c25d562016-07-13 17:17:45 -07006002 // sleep with mutex unlocked
6003 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006004 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006005 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6006 ATRACE_END();
6007 sleepUs = 0;
6008 continue;
6009 }
6010
Glenn Kasten2b806402013-11-20 16:37:38 -08006011 // if no active track(s), then standby and release wakelock
6012 size_t size = mActiveTracks.size();
6013 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006014 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006015 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006016 releaseWakeLock_l();
6017 ALOGV("RecordThread: loop stopping");
6018 // go to sleep
6019 mWaitWorkCV.wait(mLock);
6020 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006021 goto reacquire_wakelock;
6022 }
6023
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006024 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006025 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006026 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006027
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006028 activeTrack = mActiveTracks[i];
6029 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006030 if (activeTrack->isFastTrack()) {
6031 ALOG_ASSERT(fastTrackToRemove == 0);
6032 fastTrackToRemove = activeTrack;
6033 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006034 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006035 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006036 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006037 continue;
6038 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006039
6040 TrackBase::track_state activeTrackState = activeTrack->mState;
6041 switch (activeTrackState) {
6042
6043 case TrackBase::PAUSING:
6044 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006045 doBroadcast = true;
6046 size--;
6047 continue;
6048
6049 case TrackBase::STARTING_1:
6050 sleepUs = 10000;
6051 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006052 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006053 continue;
6054
6055 case TrackBase::STARTING_2:
6056 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006057 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006058 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006059 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006060 break;
6061
6062 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006063 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006064 break;
6065
6066 case TrackBase::IDLE:
6067 i++;
6068 continue;
6069
6070 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006071 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006072 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006073
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006074 activeTracks.add(activeTrack);
6075 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006076
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006077 if (activeTrack->isFastTrack()) {
6078 ALOG_ASSERT(!mFastTrackAvail);
6079 ALOG_ASSERT(fastTrack == 0);
6080 fastTrack = activeTrack;
6081 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006082 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006083
Andy Hungdae27702016-10-31 14:01:16 -07006084 mActiveTracks.updatePowerState(this);
6085
Eric Laurent5c25d562016-07-13 17:17:45 -07006086 if (allStopped) {
6087 standbyIfNotAlreadyInStandby();
6088 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006089 if (doBroadcast) {
6090 mStartStopCond.broadcast();
6091 }
6092
6093 // sleep if there are no active tracks to process
6094 if (activeTracks.size() == 0) {
6095 if (sleepUs == 0) {
6096 sleepUs = kRecordThreadSleepUs;
6097 }
6098 continue;
6099 }
6100 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006101
Eric Laurent81784c32012-11-19 14:55:58 -08006102 lockEffectChains_l(effectChains);
6103 }
6104
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006105 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006106
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006107 size_t size = effectChains.size();
6108 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006109 // thread mutex is not locked, but effect chain is locked
6110 effectChains[i]->process_l();
6111 }
6112
Glenn Kasten735f45f2014-08-18 15:51:59 -07006113 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006114 if (mFastCapture != 0) {
6115 FastCaptureStateQueue *sq = mFastCapture->sq();
6116 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006117 bool didModify = false;
6118 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006119 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6120 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6121 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6122 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6123 if (old == -1) {
6124 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6125 }
6126 }
6127 state->mCommand = FastCaptureState::READ_WRITE;
6128#if 0 // FIXME
6129 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006130 FastThreadDumpState::kSamplingNforLowRamDevice :
6131 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006133 didModify = true;
6134 }
6135 audio_track_cblk_t *cblkOld = state->mCblk;
6136 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6137 if (cblkNew != cblkOld) {
6138 state->mCblk = cblkNew;
6139 // block until acked if removing a fast track
6140 if (cblkOld != NULL) {
6141 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6142 }
6143 didModify = true;
6144 }
6145 sq->end(didModify);
6146 if (didModify) {
6147 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006148#if 0
6149 if (kUseFastCapture == FastCapture_Dynamic) {
6150 mNormalSource = mPipeSource;
6151 }
6152#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006153 }
6154 }
6155
Glenn Kasten735f45f2014-08-18 15:51:59 -07006156 // now run the fast track destructor with thread mutex unlocked
6157 fastTrackToRemove.clear();
6158
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006159 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6160 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6161 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6162 // If destination is non-contiguous, first read past the nominal end of buffer, then
6163 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006164
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006166 ssize_t framesRead;
6167
6168 // If an NBAIO source is present, use it to read the normal capture's data
6169 if (mPipeSource != 0) {
6170 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006171 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006172 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006173 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006174 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6175 // buffer size or at least for 20ms.
6176 size_t sleepFrames = max(
6177 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6178 if (framesRead <= (ssize_t) sleepFrames) {
6179 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6180 }
6181 if (framesRead < 0) {
6182 status_t status = (status_t) framesRead;
6183 switch (status) {
6184 case OVERRUN:
6185 ALOGW("overrun on read from pipe");
6186 framesRead = 0;
6187 break;
6188 case NEGOTIATE:
6189 ALOGE("re-negotiation is needed");
6190 framesRead = -1; // Will cause an attempt to recover.
6191 break;
6192 default:
6193 ALOGE("unknown error %d on read from pipe", status);
6194 break;
6195 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006196 }
6197 // otherwise use the HAL / AudioStreamIn directly
6198 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006199 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006200 size_t bytesRead;
6201 status_t result = mInput->stream->read(
6202 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006203 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006204 if (result < 0) {
6205 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006206 } else {
6207 framesRead = bytesRead / mFrameSize;
6208 }
6209 }
6210
Andy Hung3f0c9022016-01-15 17:49:46 -08006211 // Update server timestamp with server stats
6212 // systemTime() is optional if the hardware supports timestamps.
6213 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6214 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6215
6216 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006217 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006218 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006219 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006220 if (ret == NO_ERROR) {
6221 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6222 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6223 // Note: In general record buffers should tend to be empty in
6224 // a properly running pipeline.
6225 //
6226 // Also, it is not advantageous to call get_presentation_position during the read
6227 // as the read obtains a lock, preventing the timestamp call from executing.
6228 }
6229 }
6230 // Use this to track timestamp information
6231 // ALOGD("%s", mTimestamp.toString().c_str());
6232
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006233 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006234 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006235 // Force input into standby so that it tries to recover at next read attempt
6236 inputStandBy();
6237 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006238 }
6239 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006240 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006241 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006243
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006244 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006245 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006246 }
6247 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006248 {
6249 size_t part1 = mRsmpInFramesP2 - rear;
6250 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006251 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006252 (framesRead - part1) * mFrameSize);
6253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006254 }
6255 rear = mRsmpInRear += framesRead;
6256
6257 size = activeTracks.size();
6258 // loop over each active track
6259 for (size_t i = 0; i < size; i++) {
6260 activeTrack = activeTracks[i];
6261
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006262 // skip fast tracks, as those are handled directly by FastCapture
6263 if (activeTrack->isFastTrack()) {
6264 continue;
6265 }
6266
Andy Hung73c02e42015-03-29 01:13:58 -07006267 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006268 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006270 enum {
6271 OVERRUN_UNKNOWN,
6272 OVERRUN_TRUE,
6273 OVERRUN_FALSE
6274 } overrun = OVERRUN_UNKNOWN;
6275
6276 // loop over getNextBuffer to handle circular sink
6277 for (;;) {
6278
6279 activeTrack->mSink.frameCount = ~0;
6280 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6281 size_t framesOut = activeTrack->mSink.frameCount;
6282 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6283
Andy Hung73c02e42015-03-29 01:13:58 -07006284 // check available frames and handle overrun conditions
6285 // if the record track isn't draining fast enough.
6286 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006287 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006288 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6289 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006290 overrun = OVERRUN_TRUE;
6291 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006292 if (framesOut == 0 || framesIn == 0) {
6293 break;
6294 }
6295
Andy Hung6770c6f2015-04-07 13:43:36 -07006296 // Don't allow framesOut to be larger than what is possible with resampling
6297 // from framesIn.
6298 // This isn't strictly necessary but helps limit buffer resizing in
6299 // RecordBufferConverter. TODO: remove when no longer needed.
6300 framesOut = min(framesOut,
6301 destinationFramesPossible(
6302 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006303 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6304 framesOut = activeTrack->mRecordBufferConverter->convert(
6305 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006306
6307 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6308 overrun = OVERRUN_FALSE;
6309 }
6310
6311 if (activeTrack->mFramesToDrop == 0) {
6312 if (framesOut > 0) {
6313 activeTrack->mSink.frameCount = framesOut;
6314 activeTrack->releaseBuffer(&activeTrack->mSink);
6315 }
6316 } else {
6317 // FIXME could do a partial drop of framesOut
6318 if (activeTrack->mFramesToDrop > 0) {
6319 activeTrack->mFramesToDrop -= framesOut;
6320 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006321 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006322 }
6323 } else {
6324 activeTrack->mFramesToDrop += framesOut;
6325 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6326 activeTrack->mSyncStartEvent->isCancelled()) {
6327 ALOGW("Synced record %s, session %d, trigger session %d",
6328 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6329 activeTrack->sessionId(),
6330 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006331 activeTrack->mSyncStartEvent->triggerSession() :
6332 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006333 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 }
6335 }
6336 }
6337
6338 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006339 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006340 }
6341 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006342
6343 switch (overrun) {
6344 case OVERRUN_TRUE:
6345 // client isn't retrieving buffers fast enough
6346 if (!activeTrack->setOverflow()) {
6347 nsecs_t now = systemTime();
6348 // FIXME should lastWarning per track?
6349 if ((now - lastWarning) > kWarningThrottleNs) {
6350 ALOGW("RecordThread: buffer overflow");
6351 lastWarning = now;
6352 }
6353 }
6354 break;
6355 case OVERRUN_FALSE:
6356 activeTrack->clearOverflow();
6357 break;
6358 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006359 break;
6360 }
6361
Andy Hung3f0c9022016-01-15 17:49:46 -08006362 // update frame information and push timestamp out
6363 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006364 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006365 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6366 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006367 }
6368
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006369unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006370 // enable changes in effect chain
6371 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006372 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006373 }
6374
Glenn Kasten93e471f2013-08-19 08:40:07 -07006375 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006376
6377 {
6378 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006379 for (size_t i = 0; i < mTracks.size(); i++) {
6380 sp<RecordTrack> track = mTracks[i];
6381 track->invalidate();
6382 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006383 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006384 mStartStopCond.broadcast();
6385 }
6386
6387 releaseWakeLock();
6388
6389 ALOGV("RecordThread %p exiting", this);
6390 return false;
6391}
6392
Glenn Kasten93e471f2013-08-19 08:40:07 -07006393void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006394{
6395 if (!mStandby) {
6396 inputStandBy();
6397 mStandby = true;
6398 }
6399}
6400
6401void AudioFlinger::RecordThread::inputStandBy()
6402{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006403 // Idle the fast capture if it's currently running
6404 if (mFastCapture != 0) {
6405 FastCaptureStateQueue *sq = mFastCapture->sq();
6406 FastCaptureState *state = sq->begin();
6407 if (!(state->mCommand & FastCaptureState::IDLE)) {
6408 state->mCommand = FastCaptureState::COLD_IDLE;
6409 state->mColdFutexAddr = &mFastCaptureFutex;
6410 state->mColdGen++;
6411 mFastCaptureFutex = 0;
6412 sq->end();
6413 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6414 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6415#if 0
6416 if (kUseFastCapture == FastCapture_Dynamic) {
6417 // FIXME
6418 }
6419#endif
6420#ifdef AUDIO_WATCHDOG
6421 // FIXME
6422#endif
6423 } else {
6424 sq->end(false /*didModify*/);
6425 }
6426 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006427 status_t result = mInput->stream->standby();
6428 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006429
6430 // If going into standby, flush the pipe source.
6431 if (mPipeSource.get() != nullptr) {
6432 const ssize_t flushed = mPipeSource->flush();
6433 if (flushed > 0) {
6434 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6435 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6436 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6437 }
6438 }
Eric Laurent81784c32012-11-19 14:55:58 -08006439}
6440
Glenn Kasten05997e22014-03-13 15:08:33 -07006441// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006442sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006443 const sp<AudioFlinger::Client>& client,
6444 uint32_t sampleRate,
6445 audio_format_t format,
6446 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006447 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006448 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006449 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006450 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006451 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006452 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006453 status_t *status,
6454 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006455{
Glenn Kasten74935e42013-12-19 08:56:45 -08006456 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006457 sp<RecordTrack> track;
6458 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006459 audio_input_flags_t inputFlags = mInput->flags;
6460
6461 // special case for FAST flag considered OK if fast capture is present
6462 if (hasFastCapture()) {
6463 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6464 }
6465
6466 // Check if requested flags are compatible with output stream flags
6467 if ((*flags & inputFlags) != *flags) {
6468 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6469 " input flags (%08x)",
6470 *flags, inputFlags);
6471 *flags = (audio_input_flags_t)(*flags & inputFlags);
6472 }
Eric Laurent81784c32012-11-19 14:55:58 -08006473
Glenn Kasten90e58b12013-07-31 16:16:02 -07006474 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006475 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006476 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006477 // we formerly checked for a callback handler (non-0 tid),
6478 // but that is no longer required for TRANSFER_OBTAIN mode
6479 //
Glenn Kasten74105912014-07-03 12:28:53 -07006480 // frame count is not specified, or is exactly the pipe depth
6481 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006482 // PCM data
6483 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006484 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006485 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006486 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006487 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006488 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006489 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006490 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006491 hasFastCapture() &&
6492 // there are sufficient fast track slots available
6493 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006494 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006495 // check compatibility with audio effects.
6496 Mutex::Autolock _l(mLock);
6497 // Do not accept FAST flag if the session has software effects
6498 sp<EffectChain> chain = getEffectChain_l(sessionId);
6499 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006500 audio_input_flags_t old = *flags;
6501 chain->checkInputFlagCompatibility(flags);
6502 if (old != *flags) {
6503 ALOGV("AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6504 (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006505 }
6506 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006507 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07006508 "AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6509 frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006510 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006511 ALOGV("AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
Glenn Kasten74105912014-07-03 12:28:53 -07006512 "format=%#x isLinear=%d channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006513 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Glenn Kasten74105912014-07-03 12:28:53 -07006514 frameCount, mFrameCount, mPipeFramesP2,
6515 format, audio_is_linear_pcm(format), channelMask, sampleRate, mSampleRate,
6516 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006517 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006518 }
6519 }
6520
6521 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006522 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006523 // fast track: frame count is exactly the pipe depth
6524 frameCount = mPipeFramesP2;
6525 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6526 *notificationFrames = mFrameCount;
6527 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006528 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6529 // or 20 ms if there is a fast capture
6530 // TODO This could be a roundupRatio inline, and const
6531 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6532 * sampleRate + mSampleRate - 1) / mSampleRate;
6533 // minimum number of notification periods is at least kMinNotifications,
6534 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6535 static const size_t kMinNotifications = 3;
6536 static const uint32_t kMinMs = 30;
6537 // TODO This could be a roundupRatio inline
6538 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6539 // TODO This could be a roundupRatio inline
6540 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6541 maxNotificationFrames;
6542 const size_t minFrameCount = maxNotificationFrames *
6543 max(kMinNotifications, minNotificationsByMs);
6544 frameCount = max(frameCount, minFrameCount);
6545 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6546 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006547 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006548 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006549 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006550
Glenn Kasten15e57982013-09-24 11:52:37 -07006551 lStatus = initCheck();
6552 if (lStatus != NO_ERROR) {
6553 ALOGE("createRecordTrack_l() audio driver not initialized");
6554 goto Exit;
6555 }
Eric Laurent81784c32012-11-19 14:55:58 -08006556
6557 { // scope for mLock
6558 Mutex::Autolock _l(mLock);
6559
6560 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006561 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006562 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006563
Glenn Kasten03003332013-08-06 15:40:54 -07006564 lStatus = track->initCheck();
6565 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006566 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006567 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006568 goto Exit;
6569 }
6570 mTracks.add(track);
6571
6572 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6573 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6574 mAudioFlinger->btNrecIsOff();
6575 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6576 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006577
Eric Laurent05067782016-06-01 18:27:28 -07006578 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006579 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6580 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6581 // so ask activity manager to do this on our behalf
6582 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp);
6583 }
Eric Laurent81784c32012-11-19 14:55:58 -08006584 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006585
Eric Laurent81784c32012-11-19 14:55:58 -08006586 lStatus = NO_ERROR;
6587
6588Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006589 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006590 return track;
6591}
6592
6593status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6594 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006595 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006596{
6597 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6598 sp<ThreadBase> strongMe = this;
6599 status_t status = NO_ERROR;
6600
6601 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006602 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006603 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006604 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006605 triggerSession,
6606 recordTrack->sessionId(),
6607 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006609 // Sync event can be cancelled by the trigger session if the track is not in a
6610 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006611 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006612 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006613 } else {
6614 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006615 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006616 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006617 }
6618 }
6619
6620 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006621 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006622 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006623 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6624 if (recordTrack->mState == TrackBase::PAUSING) {
6625 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006626 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006627 } else {
6628 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006629 }
6630 return status;
6631 }
6632
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006633 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6634 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6635 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006636 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006637 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006638 status_t status = NO_ERROR;
6639 if (recordTrack->isExternalTrack()) {
6640 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006641 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006642 mLock.lock();
6643 // FIXME should verify that recordTrack is still in mActiveTracks
6644 if (status != NO_ERROR) {
6645 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006646 recordTrack->clearSyncStartEvent();
6647 ALOGV("RecordThread::start error %d", status);
6648 return status;
6649 }
Eric Laurent81784c32012-11-19 14:55:58 -08006650 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006651 // Catch up with current buffer indices if thread is already running.
6652 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6653 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6654 // see previously buffered data before it called start(), but with greater risk of overrun.
6655
Andy Hung73c02e42015-03-29 01:13:58 -07006656 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006657 // clear any converter state as new data will be discontinuous
6658 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006659 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006660 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006661 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006662 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006663 ALOGV("Record failed to start");
6664 status = BAD_VALUE;
6665 goto startError;
6666 }
Eric Laurent81784c32012-11-19 14:55:58 -08006667 return status;
6668 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006669
Eric Laurent81784c32012-11-19 14:55:58 -08006670startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006671 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006672 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006673 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006674 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006675 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006676 return status;
6677}
6678
Eric Laurent81784c32012-11-19 14:55:58 -08006679void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6680{
6681 sp<SyncEvent> strongEvent = event.promote();
6682
6683 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006684 sp<RefBase> ptr = strongEvent->cookie().promote();
6685 if (ptr != 0) {
6686 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6687 recordTrack->handleSyncStartEvent(strongEvent);
6688 }
Eric Laurent81784c32012-11-19 14:55:58 -08006689 }
6690}
6691
Glenn Kastena8356f62013-07-25 14:37:52 -07006692bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006693 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006694 AutoMutex _l(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006695 if (mActiveTracks.indexOf(recordTrack) != 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006696 return false;
6697 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006698 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006699 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006700 // signal thread to stop
6701 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006702 // do not wait for mStartStopCond if exiting
6703 if (exitPending()) {
6704 return true;
6705 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006706 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006707 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006708 // if we have been restarted, recordTrack is in mActiveTracks here
6709 if (exitPending() || mActiveTracks.indexOf(recordTrack) != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006710 ALOGV("Record stopped OK");
6711 return true;
6712 }
6713 return false;
6714}
6715
Glenn Kasten0f11b512014-01-31 16:18:54 -08006716bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006717{
6718 return false;
6719}
6720
Glenn Kasten0f11b512014-01-31 16:18:54 -08006721status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006722{
6723#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6724 if (!isValidSyncEvent(event)) {
6725 return BAD_VALUE;
6726 }
6727
Glenn Kastend848eb42016-03-08 13:42:11 -08006728 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006729 status_t ret = NAME_NOT_FOUND;
6730
6731 Mutex::Autolock _l(mLock);
6732
6733 for (size_t i = 0; i < mTracks.size(); i++) {
6734 sp<RecordTrack> track = mTracks[i];
6735 if (eventSession == track->sessionId()) {
6736 (void) track->setSyncEvent(event);
6737 ret = NO_ERROR;
6738 }
6739 }
6740 return ret;
6741#else
6742 return BAD_VALUE;
6743#endif
6744}
6745
6746// destroyTrack_l() must be called with ThreadBase::mLock held
6747void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6748{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006749 track->terminate();
6750 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006751 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006752 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006753 removeTrack_l(track);
6754 }
6755}
6756
6757void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6758{
6759 mTracks.remove(track);
6760 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006761 if (track->isFastTrack()) {
6762 ALOG_ASSERT(!mFastTrackAvail);
6763 mFastTrackAvail = true;
6764 }
Eric Laurent81784c32012-11-19 14:55:58 -08006765}
6766
6767void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6768{
6769 dumpInternals(fd, args);
6770 dumpTracks(fd, args);
6771 dumpEffectChains(fd, args);
6772}
6773
6774void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6775{
Elliott Hughes87cebad2014-05-22 10:14:43 -07006776 dprintf(fd, "\nInput thread %p:\n", this);
Eric Laurent81784c32012-11-19 14:55:58 -08006777
Glenn Kasten44182c22015-03-05 17:12:23 -08006778 dumpBase(fd, args);
6779
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006780 AudioStreamIn *input = mInput;
6781 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6782 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6783 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006784 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006785 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006786 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006787 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006788 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006789
Glenn Kasten2f90c512015-12-02 11:40:09 -08006790 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6791 // while we are dumping it. It may be inconsistent, but it won't mutate!
6792 // This is a large object so we place it on the heap.
6793 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6794 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6795 copy->dump(fd);
6796 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006797}
6798
Glenn Kasten0f11b512014-01-31 16:18:54 -08006799void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006800{
6801 const size_t SIZE = 256;
6802 char buffer[SIZE];
6803 String8 result;
6804
Marco Nelissenb2208842014-02-07 14:00:50 -08006805 size_t numtracks = mTracks.size();
6806 size_t numactive = mActiveTracks.size();
6807 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006808 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006809 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006810 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006811 RecordTrack::appendDumpHeader(result);
6812 for (size_t i = 0; i < numtracks ; ++i) {
6813 sp<RecordTrack> track = mTracks[i];
6814 if (track != 0) {
6815 bool active = mActiveTracks.indexOf(track) >= 0;
6816 if (active) {
6817 numactiveseen++;
6818 }
6819 track->dump(buffer, SIZE, active);
6820 result.append(buffer);
6821 }
Eric Laurent81784c32012-11-19 14:55:58 -08006822 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006823 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006824 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006825 }
6826
Marco Nelissenb2208842014-02-07 14:00:50 -08006827 if (numactiveseen != numactive) {
6828 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6829 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006830 result.append(buffer);
6831 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006832 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006833 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006834 if (mTracks.indexOf(track) < 0) {
6835 track->dump(buffer, SIZE, true);
6836 result.append(buffer);
6837 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006838 }
Eric Laurent81784c32012-11-19 14:55:58 -08006839
6840 }
6841 write(fd, result.string(), result.size());
6842}
6843
Andy Hung73c02e42015-03-29 01:13:58 -07006844
6845void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6846{
6847 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6848 RecordThread *recordThread = (RecordThread *) threadBase.get();
6849 mRsmpInFront = recordThread->mRsmpInRear;
6850 mRsmpInUnrel = 0;
6851}
6852
6853void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6854 size_t *framesAvailable, bool *hasOverrun)
6855{
6856 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6857 RecordThread *recordThread = (RecordThread *) threadBase.get();
6858 const int32_t rear = recordThread->mRsmpInRear;
6859 const int32_t front = mRsmpInFront;
6860 const ssize_t filled = rear - front;
6861
6862 size_t framesIn;
6863 bool overrun = false;
6864 if (filled < 0) {
6865 // should not happen, but treat like a massive overrun and re-sync
6866 framesIn = 0;
6867 mRsmpInFront = rear;
6868 overrun = true;
6869 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6870 framesIn = (size_t) filled;
6871 } else {
6872 // client is not keeping up with server, but give it latest data
6873 framesIn = recordThread->mRsmpInFrames;
6874 mRsmpInFront = /* front = */ rear - framesIn;
6875 overrun = true;
6876 }
6877 if (framesAvailable != NULL) {
6878 *framesAvailable = framesIn;
6879 }
6880 if (hasOverrun != NULL) {
6881 *hasOverrun = overrun;
6882 }
6883}
6884
Eric Laurent81784c32012-11-19 14:55:58 -08006885// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006886status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08006887 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006888{
Andy Hung73c02e42015-03-29 01:13:58 -07006889 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006890 if (threadBase == 0) {
6891 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006892 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006893 return NOT_ENOUGH_DATA;
6894 }
6895 RecordThread *recordThread = (RecordThread *) threadBase.get();
6896 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07006897 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07006898 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006899 // FIXME should not be P2 (don't want to increase latency)
6900 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08006901 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07006902 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006903 front &= recordThread->mRsmpInFramesP2 - 1;
6904 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07006905 if (part1 > (size_t) filled) {
6906 part1 = filled;
6907 }
6908 size_t ask = buffer->frameCount;
6909 ALOG_ASSERT(ask > 0);
6910 if (part1 > ask) {
6911 part1 = ask;
6912 }
6913 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07006914 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07006915 buffer->raw = NULL;
6916 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07006917 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07006918 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08006919 }
6920
Andy Hung57446612015-04-19 23:56:46 -07006921 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07006922 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07006923 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08006924 return NO_ERROR;
6925}
6926
6927// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006928void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
6929 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08006930{
Glenn Kasten85948432013-08-19 12:09:05 -07006931 size_t stepCount = buffer->frameCount;
6932 if (stepCount == 0) {
6933 return;
6934 }
Andy Hung73c02e42015-03-29 01:13:58 -07006935 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
6936 mRsmpInUnrel -= stepCount;
6937 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07006938 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08006939 buffer->frameCount = 0;
6940}
6941
Andy Hung97a893e2015-03-29 01:03:07 -07006942
Eric Laurent10351942014-05-08 18:49:52 -07006943bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
6944 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006945{
6946 bool reconfig = false;
6947
Eric Laurent10351942014-05-08 18:49:52 -07006948 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006949
Eric Laurent10351942014-05-08 18:49:52 -07006950 audio_format_t reqFormat = mFormat;
6951 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07006952 // 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 -07006953 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
6954
6955 AudioParameter param = AudioParameter(keyValuePair);
6956 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07006957
6958 // scope for AutoPark extends to end of method
6959 AutoPark<FastCapture> park(mFastCapture);
6960
Eric Laurent10351942014-05-08 18:49:52 -07006961 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
6962 // channel count change can be requested. Do we mandate the first client defines the
6963 // HAL sampling rate and channel count or do we allow changes on the fly?
6964 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6965 samplingRate = value;
6966 reconfig = true;
6967 }
6968 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07006969 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07006970 status = BAD_VALUE;
6971 } else {
6972 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08006973 reconfig = true;
6974 }
Eric Laurent10351942014-05-08 18:49:52 -07006975 }
6976 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
6977 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07006978 if (!audio_is_input_channel(mask) ||
6979 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07006980 status = BAD_VALUE;
6981 } else {
6982 channelMask = mask;
6983 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006984 }
Eric Laurent10351942014-05-08 18:49:52 -07006985 }
6986 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6987 // do not accept frame count changes if tracks are open as the track buffer
6988 // size depends on frame count and correct behavior would not be guaranteed
6989 // if frame count is changed after track creation
6990 if (mActiveTracks.size() > 0) {
6991 status = INVALID_OPERATION;
6992 } else {
6993 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006994 }
Eric Laurent10351942014-05-08 18:49:52 -07006995 }
6996 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
6997 // forward device change to effects that have requested to be
6998 // aware of attached audio device.
6999 for (size_t i = 0; i < mEffectChains.size(); i++) {
7000 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007001 }
Eric Laurent81784c32012-11-19 14:55:58 -08007002
Eric Laurent10351942014-05-08 18:49:52 -07007003 // store input device and output device but do not forward output device to audio HAL.
7004 // Note that status is ignored by the caller for output device
7005 // (see AudioFlinger::setParameters()
7006 if (audio_is_output_devices(value)) {
7007 mOutDevice = value;
7008 status = BAD_VALUE;
7009 } else {
7010 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007011 if (value != AUDIO_DEVICE_NONE) {
7012 mPrevInDevice = value;
7013 }
Eric Laurent10351942014-05-08 18:49:52 -07007014 // disable AEC and NS if the device is a BT SCO headset supporting those
7015 // pre processings
7016 if (mTracks.size() > 0) {
7017 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7018 mAudioFlinger->btNrecIsOff();
7019 for (size_t i = 0; i < mTracks.size(); i++) {
7020 sp<RecordTrack> track = mTracks[i];
7021 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7022 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007023 }
7024 }
7025 }
Eric Laurent10351942014-05-08 18:49:52 -07007026 }
7027 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7028 mAudioSource != (audio_source_t)value) {
7029 // forward device change to effects that have requested to be
7030 // aware of attached audio device.
7031 for (size_t i = 0; i < mEffectChains.size(); i++) {
7032 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007033 }
Eric Laurent10351942014-05-08 18:49:52 -07007034 mAudioSource = (audio_source_t)value;
7035 }
Glenn Kastene198c362013-08-13 09:13:36 -07007036
Eric Laurent10351942014-05-08 18:49:52 -07007037 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007038 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007039 if (status == INVALID_OPERATION) {
7040 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007041 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007042 }
7043 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007044 if (status == BAD_VALUE) {
7045 uint32_t sRate;
7046 audio_channel_mask_t channelMask;
7047 audio_format_t format;
7048 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7049 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7050 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7051 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7052 status = NO_ERROR;
7053 }
Eric Laurent81784c32012-11-19 14:55:58 -08007054 }
Eric Laurent10351942014-05-08 18:49:52 -07007055 if (status == NO_ERROR) {
7056 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007057 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007058 }
7059 }
Eric Laurent81784c32012-11-19 14:55:58 -08007060 }
Eric Laurent10351942014-05-08 18:49:52 -07007061
Eric Laurent81784c32012-11-19 14:55:58 -08007062 return reconfig;
7063}
7064
7065String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7066{
Eric Laurent81784c32012-11-19 14:55:58 -08007067 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007068 if (initCheck() == NO_ERROR) {
7069 String8 out_s8;
7070 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7071 return out_s8;
7072 }
Eric Laurent81784c32012-11-19 14:55:58 -08007073 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007074 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007075}
7076
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007077void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007078 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7079
7080 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007081
7082 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007083 case AUDIO_INPUT_OPENED:
7084 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007085 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007086 desc->mChannelMask = mChannelMask;
7087 desc->mSamplingRate = mSampleRate;
7088 desc->mFormat = mFormat;
7089 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007090 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007091 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007092 break;
7093
Eric Laurent73e26b62015-04-27 16:55:58 -07007094 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007095 default:
7096 break;
7097 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007098 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007099}
7100
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007101void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007102{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007103 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7104 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007105 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007106 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007107 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007108 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7109 result = mInput->stream->getFrameSize(&mFrameSize);
7110 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7111 result = mInput->stream->getBufferSize(&mBufferSize);
7112 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007113 mFrameCount = mBufferSize / mFrameSize;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007114 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007115 // 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 -07007116 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007117 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007118 // A larger value should allow more old data to be read after a track calls start(),
7119 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007120 //
7121 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007122 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007123 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007124 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007125 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007126
7127 // TODO optimize audio capture buffer sizes ...
7128 // Here we calculate the size of the sliding buffer used as a source
7129 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7130 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7131 // be better to have it derived from the pipe depth in the long term.
7132 // The current value is higher than necessary. However it should not add to latency.
7133
Glenn Kasten85948432013-08-19 12:09:05 -07007134 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007135 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7136 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
7137 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize); // if posix_memalign fails, will segv here.
Eric Laurent81784c32012-11-19 14:55:58 -08007138
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007139 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7140 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007141}
7142
Glenn Kasten5f972c02014-01-13 09:59:31 -08007143uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007144{
7145 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007146 uint32_t result;
7147 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7148 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007149 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007150 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007151}
7152
Eric Laurent4c415062016-06-17 16:14:16 -07007153// hasAudioSession_l() must be called with ThreadBase::mLock held
7154uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007155{
Eric Laurent81784c32012-11-19 14:55:58 -08007156 uint32_t result = 0;
7157 if (getEffectChain_l(sessionId) != 0) {
7158 result = EFFECT_SESSION;
7159 }
7160
7161 for (size_t i = 0; i < mTracks.size(); ++i) {
7162 if (sessionId == mTracks[i]->sessionId()) {
7163 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007164 if (mTracks[i]->isFastTrack()) {
7165 result |= FAST_SESSION;
7166 }
Eric Laurent81784c32012-11-19 14:55:58 -08007167 break;
7168 }
7169 }
7170
7171 return result;
7172}
7173
Glenn Kastend848eb42016-03-08 13:42:11 -08007174KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007175{
Glenn Kastend848eb42016-03-08 13:42:11 -08007176 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007177 Mutex::Autolock _l(mLock);
7178 for (size_t j = 0; j < mTracks.size(); ++j) {
7179 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007180 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007181 if (ids.indexOfKey(sessionId) < 0) {
7182 ids.add(sessionId, true);
7183 }
7184 }
7185 return ids;
7186}
7187
7188AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7189{
7190 Mutex::Autolock _l(mLock);
7191 AudioStreamIn *input = mInput;
7192 mInput = NULL;
7193 return input;
7194}
7195
7196// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007197sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007198{
7199 if (mInput == NULL) {
7200 return NULL;
7201 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007202 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007203}
7204
7205status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7206{
7207 // only one chain per input thread
7208 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007209 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007210 return INVALID_OPERATION;
7211 }
7212 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007213 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007214 chain->setInBuffer(NULL);
7215 chain->setOutBuffer(NULL);
7216
7217 checkSuspendOnAddEffectChain_l(chain);
7218
Eric Laurent1b928682014-10-02 19:41:47 -07007219 // make sure enabled pre processing effects state is communicated to the HAL as we
7220 // just moved them to a new input stream.
7221 chain->syncHalEffectsState();
7222
Eric Laurent81784c32012-11-19 14:55:58 -08007223 mEffectChains.add(chain);
7224
7225 return NO_ERROR;
7226}
7227
7228size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7229{
7230 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7231 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007232 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007233 chain.get(), mEffectChains.size(), this);
7234 if (mEffectChains.size() == 1) {
7235 mEffectChains.removeAt(0);
7236 }
7237 return 0;
7238}
7239
Eric Laurent1c333e22014-05-20 10:48:17 -07007240status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7241 audio_patch_handle_t *handle)
7242{
7243 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007244
7245 // store new device and send to effects
7246 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007247 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007248 for (size_t i = 0; i < mEffectChains.size(); i++) {
7249 mEffectChains[i]->setDevice_l(mInDevice);
7250 }
7251
7252 // disable AEC and NS if the device is a BT SCO headset supporting those
7253 // pre processings
7254 if (mTracks.size() > 0) {
7255 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7256 mAudioFlinger->btNrecIsOff();
7257 for (size_t i = 0; i < mTracks.size(); i++) {
7258 sp<RecordTrack> track = mTracks[i];
7259 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7260 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7261 }
7262 }
7263
7264 // store new source and send to effects
7265 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7266 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007267 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007268 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007269 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007270 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007271
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007272 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007273 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7274 status = hwDevice->createAudioPatch(patch->num_sources,
7275 patch->sources,
7276 patch->num_sinks,
7277 patch->sinks,
7278 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007279 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007280 char *address;
7281 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7282 address = audio_device_address_to_parameter(
7283 patch->sources[0].ext.device.type,
7284 patch->sources[0].ext.device.address);
7285 } else {
7286 address = (char *)calloc(1, 1);
7287 }
7288 AudioParameter param = AudioParameter(String8(address));
7289 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007290 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007291 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007292 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007293 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007294 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007295 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007296 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007297
Eric Laurente8726fe2015-06-26 09:39:24 -07007298 if (mInDevice != mPrevInDevice) {
7299 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7300 mPrevInDevice = mInDevice;
7301 }
Eric Laurent296fb132015-05-01 11:38:42 -07007302
Eric Laurent1c333e22014-05-20 10:48:17 -07007303 return status;
7304}
7305
7306status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7307{
7308 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007309
7310 mInDevice = AUDIO_DEVICE_NONE;
7311
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007312 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007313 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7314 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007315 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007316 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007317 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007318 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007319 }
7320 return status;
7321}
7322
Eric Laurent83b88082014-06-20 18:31:16 -07007323void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7324{
7325 Mutex::Autolock _l(mLock);
7326 mTracks.add(record);
7327}
7328
7329void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7330{
7331 Mutex::Autolock _l(mLock);
7332 destroyTrack_l(record);
7333}
7334
7335void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7336{
7337 ThreadBase::getAudioPortConfig(config);
7338 config->role = AUDIO_PORT_ROLE_SINK;
7339 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7340 config->ext.mix.usecase.source = mAudioSource;
7341}
Eric Laurent1c333e22014-05-20 10:48:17 -07007342
Glenn Kasten63238ef2015-03-02 15:50:29 -08007343} // namespace android