blob: e80fb7356382248792c3f1da0d6afd1d491afdf9 [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>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.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
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten691b02a2017-10-03 10:12:20 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x4000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800446 case MMAP:
447 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800534 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Mikhail Naganov83f04272017-02-07 10:45:09 -0800615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700616{
617 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
623 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700700 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
701 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700705 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 CreateAudioPatchConfigEventData *data =
707 (CreateAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t newDevice = getDevice();
710 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
711 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
712 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 } break;
714 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 ReleaseAudioPatchConfigEventData *data =
717 (ReleaseAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t newDevice = getDevice();
720 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
721 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
722 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 default:
Eric Laurent10351942014-05-08 18:49:52 -0700725 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
729 Mutex::Autolock _l(event->mLock);
730 if (event->mWaitStatus) {
731 event->mWaitStatus = false;
732 event->mCond.signal();
733 }
734 }
735 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
736 }
737
738 if (configChanged) {
739 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Marco Nelissenb2208842014-02-07 14:00:50 -0800743String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
744 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700745 const audio_channel_representation_t representation =
746 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700789 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800810 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
811 this, mThreadName, getTid(), type(), threadTypeToString(type()));
812
Eric Laurent81784c32012-11-19 14:55:58 -0800813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800815 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700823 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700828 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Andy Hung293558a2017-03-21 12:19:20 -0700840 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
842 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 if (locked) {
846 mLock.unlock();
847 }
848}
849
850void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000857 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800858 write(fd, buffer, strlen(buffer));
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800861 sp<EffectChain> chain = mEffectChains[i];
862 if (chain != 0) {
863 chain->dump(fd, args);
864 }
865 }
866}
867
Andy Hungdae27702016-10-31 14:01:16 -0700868void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800869{
870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700871 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872}
873
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874String16 AudioFlinger::ThreadBase::getWakeLockTag()
875{
876 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 case MIXER:
878 return String16("AudioMix");
879 case DIRECT:
880 return String16("AudioDirectOut");
881 case DUPLICATING:
882 return String16("AudioDup");
883 case RECORD:
884 return String16("AudioIn");
885 case OFFLOAD:
886 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800887 case MMAP:
888 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Andy Hungdae27702016-10-31 14:01:16 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700900 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
901 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700904 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (status == NO_ERROR) {
907 mWakeLockToken = binder;
908 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Wei Jia3f273d12015-11-24 09:06:49 -0800911
Andy Hung3f0c9022016-01-15 17:49:46 -0800912 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800913 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
914 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800915}
916
917void AudioFlinger::ThreadBase::releaseWakeLock()
918{
919 Mutex::Autolock _l(mLock);
920 releaseWakeLock_l();
921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock_l()
924{
Andy Hung3f0c9022016-01-15 17:49:46 -0800925 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800934}
935
936void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700937 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938 // use checkService() to avoid blocking if power service is not up yet
939 sp<IBinder> binder =
940 defaultServiceManager()->checkService(String16("power"));
941 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800942 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 } else {
944 mPowerManager = interface_cast<IPowerManager>(binder);
945 binder->linkToDeath(mDeathRecipient);
946 }
947 }
948}
949
Andy Hungd01b0f12016-11-07 16:10:30 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700952
953#if !LOG_NDEBUG
954 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800955 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700956 s << uid << " ";
957 }
958 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
959#endif
960
Andy Hung438e7572015-12-14 15:51:17 -0800961 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
962 if (mSystemReady) {
963 ALOGE("no wake lock to update, but system ready!");
964 } else {
965 ALOGW("no wake lock to update, system not ready yet");
966 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 return;
968 }
969 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800970 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
971 status_t status = mPowerManager->updateWakeLockUids(
972 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
973 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800974 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 }
976}
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978void AudioFlinger::ThreadBase::clearPowerManager()
979{
980 Mutex::Autolock _l(mLock);
981 releaseWakeLock_l();
982 mPowerManager.clear();
983}
984
Glenn Kasten0f11b512014-01-31 16:18:54 -0800985void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 sp<ThreadBase> thread = mThread.promote();
988 if (thread != 0) {
989 thread->clearPowerManager();
990 }
991 ALOGW("power manager service died !!!");
992}
993
Eric Laurent81784c32012-11-19 14:55:58 -0800994void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800995 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001020 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001035 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001104 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
Eric Laurent4c415062016-06-17 16:14:16 -07001123// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1124status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1125 const effect_descriptor_t *desc, audio_session_t sessionId)
1126{
1127 // No global effect sessions on record threads
1128 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1129 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1130 desc->name, mThreadName);
1131 return BAD_VALUE;
1132 }
1133 // only pre processing effects on record thread
1134 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1135 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001139
1140 // always allow effects without processing load or latency
1141 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1142 return NO_ERROR;
1143 }
1144
Eric Laurent4c415062016-06-17 16:14:16 -07001145 audio_input_flags_t flags = mInput->flags;
1146 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1147 if (flags & AUDIO_INPUT_FLAG_RAW) {
1148 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1153 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
1161// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1162status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1163 const effect_descriptor_t *desc, audio_session_t sessionId)
1164{
1165 // no preprocessing on playback threads
1166 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1167 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1168 " thread %s", desc->name, mThreadName);
1169 return BAD_VALUE;
1170 }
1171
Eric Laurent3e4de772017-07-16 16:55:08 -07001172 // always allow effects without processing load or latency
1173 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1174 return NO_ERROR;
1175 }
1176
Eric Laurent4c415062016-06-17 16:14:16 -07001177 switch (mType) {
1178 case MIXER: {
1179 // Reject any effect on mixer multichannel sinks.
1180 // TODO: fix both format and multichannel issues with effects.
1181 if (mChannelCount != FCC_2) {
1182 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1183 " thread %s", desc->name, mChannelCount, mThreadName);
1184 return BAD_VALUE;
1185 }
1186 audio_output_flags_t flags = mOutput->flags;
1187 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1188 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1189 // global effects are applied only to non fast tracks if they are SW
1190 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1191 break;
1192 }
1193 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1194 // only post processing on output stage session
1195 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1196 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1197 " on output stage session", desc->name);
1198 return BAD_VALUE;
1199 }
1200 } else {
1201 // no restriction on effects applied on non fast tracks
1202 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1203 break;
1204 }
1205 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001270 status_t *status,
1271 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
1273 sp<EffectModule> effect;
1274 sp<EffectHandle> handle;
1275 status_t lStatus;
1276 sp<EffectChain> chain;
1277 bool chainCreated = false;
1278 bool effectCreated = false;
1279 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001280 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001281
1282 lStatus = initCheck();
1283 if (lStatus != NO_ERROR) {
1284 ALOGW("createEffect_l() Audio driver not initialized.");
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1289
1290 { // scope for mLock
1291 Mutex::Autolock _l(mLock);
1292
Eric Laurent4c415062016-06-17 16:14:16 -07001293 lStatus = checkEffectCompatibility_l(desc, sessionId);
1294 if (lStatus != NO_ERROR) {
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // check for existing effect chain with the requested audio session
1299 chain = getEffectChain_l(sessionId);
1300 if (chain == 0) {
1301 // create a new chain for this session
1302 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1303 chain = new EffectChain(this, sessionId);
1304 addEffectChain_l(chain);
1305 chain->setStrategy(getStrategyForSession_l(sessionId));
1306 chainCreated = true;
1307 } else {
1308 effect = chain->getEffectFromDesc_l(desc);
1309 }
1310
1311 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1312
1313 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001315 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001316 lStatus = AudioSystem::registerEffect(
1317 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectRegistered = true;
1322 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectCreated = true;
1328
1329 effect->setDevice(mOutDevice);
1330 effect->setDevice(mInDevice);
1331 effect->setMode(mAudioFlinger->getMode());
1332 effect->setAudioSource(mAudioSource);
1333 }
1334 // create effect handle and connect it to effect module
1335 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001336 lStatus = handle->initCheck();
1337 if (lStatus == OK) {
1338 lStatus = effect->addHandle(handle.get());
1339 }
Eric Laurent81784c32012-11-19 14:55:58 -08001340 if (enabled != NULL) {
1341 *enabled = (int)effect->isEnabled();
1342 }
1343 }
1344
1345Exit:
1346 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1347 Mutex::Autolock _l(mLock);
1348 if (effectCreated) {
1349 chain->removeEffect_l(effect);
1350 }
1351 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001352 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001353 }
1354 if (chainCreated) {
1355 removeEffectChain_l(chain);
1356 }
1357 handle.clear();
1358 }
1359
Glenn Kasten9156ef32013-08-06 15:39:08 -07001360 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 return handle;
1362}
1363
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001364void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1365 bool unpinIfLast)
1366{
1367 bool remove = false;
1368 sp<EffectModule> effect;
1369 {
1370 Mutex::Autolock _l(mLock);
1371
1372 effect = handle->effect().promote();
1373 if (effect == 0) {
1374 return;
1375 }
1376 // restore suspended effects if the disconnected handle was enabled and the last one.
1377 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1378 if (remove) {
1379 removeEffect_l(effect, true);
1380 }
1381 }
1382 if (remove) {
1383 mAudioFlinger->updateOrphanEffectChains(effect);
1384 AudioSystem::unregisterEffect(effect->id());
1385 if (handle->enabled()) {
1386 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1387 }
1388 }
1389}
1390
Glenn Kastend848eb42016-03-08 13:42:11 -08001391sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1392 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001393{
1394 Mutex::Autolock _l(mLock);
1395 return getEffect_l(sessionId, effectId);
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1403}
1404
1405// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1406// PlaybackThread::mLock held
1407status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1408{
1409 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 bool chainCreated = false;
1413
Eric Laurent5baf2af2013-09-12 17:37:00 -07001414 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1415 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1416 this, effect->desc().name, effect->desc().flags);
1417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 if (chain == 0) {
1419 // create a new chain for this session
1420 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1421 chain = new EffectChain(this, sessionId);
1422 addEffectChain_l(chain);
1423 chain->setStrategy(getStrategyForSession_l(sessionId));
1424 chainCreated = true;
1425 }
1426 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1427
1428 if (chain->getEffectFromId_l(effect->id()) != 0) {
1429 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1430 this, effect->desc().name, chain.get());
1431 return BAD_VALUE;
1432 }
1433
Eric Laurent5baf2af2013-09-12 17:37:00 -07001434 effect->setOffloaded(mType == OFFLOAD, mId);
1435
Eric Laurent81784c32012-11-19 14:55:58 -08001436 status_t status = chain->addEffect_l(effect);
1437 if (status != NO_ERROR) {
1438 if (chainCreated) {
1439 removeEffectChain_l(chain);
1440 }
1441 return status;
1442 }
1443
1444 effect->setDevice(mOutDevice);
1445 effect->setDevice(mInDevice);
1446 effect->setMode(mAudioFlinger->getMode());
1447 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001448
Eric Laurent81784c32012-11-19 14:55:58 -08001449 return NO_ERROR;
1450}
1451
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001454 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t desc = effect->desc();
1456 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1457 detachAuxEffect_l(effect->id());
1458 }
1459
1460 sp<EffectChain> chain = effect->chain().promote();
1461 if (chain != 0) {
1462 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001463 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001464 removeEffectChain_l(chain);
1465 }
1466 } else {
1467 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1468 }
1469}
1470
1471void AudioFlinger::ThreadBase::lockEffectChains_l(
1472 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1473{
1474 effectChains = mEffectChains;
1475 for (size_t i = 0; i < mEffectChains.size(); i++) {
1476 mEffectChains[i]->lock();
1477 }
1478}
1479
1480void AudioFlinger::ThreadBase::unlockEffectChains(
1481 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1482{
1483 for (size_t i = 0; i < effectChains.size(); i++) {
1484 effectChains[i]->unlock();
1485 }
1486}
1487
Glenn Kastend848eb42016-03-08 13:42:11 -08001488sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 Mutex::Autolock _l(mLock);
1491 return getEffectChain_l(sessionId);
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1495 const
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 size_t size = mEffectChains.size();
1498 for (size_t i = 0; i < size; i++) {
1499 if (mEffectChains[i]->sessionId() == sessionId) {
1500 return mEffectChains[i];
1501 }
1502 }
1503 return 0;
1504}
1505
1506void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1507{
1508 Mutex::Autolock _l(mLock);
1509 size_t size = mEffectChains.size();
1510 for (size_t i = 0; i < size; i++) {
1511 mEffectChains[i]->setMode_l(mode);
1512 }
1513}
1514
Eric Laurent83b88082014-06-20 18:31:16 -07001515void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1516{
1517 config->type = AUDIO_PORT_TYPE_MIX;
1518 config->ext.mix.handle = mId;
1519 config->sample_rate = mSampleRate;
1520 config->format = mFormat;
1521 config->channel_mask = mChannelMask;
1522 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1523 AUDIO_PORT_CONFIG_FORMAT;
1524}
1525
Eric Laurent72e3f392015-05-20 14:43:50 -07001526void AudioFlinger::ThreadBase::systemReady()
1527{
1528 Mutex::Autolock _l(mLock);
1529 if (mSystemReady) {
1530 return;
1531 }
1532 mSystemReady = true;
1533
1534 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1535 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1536 }
1537 mPendingConfigEvents.clear();
1538}
1539
Andy Hungdae27702016-10-31 14:01:16 -07001540template <typename T>
1541ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1542 ssize_t index = mActiveTracks.indexOf(track);
1543 if (index >= 0) {
1544 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1545 return index;
1546 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001547 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001548 mActiveTracksGeneration++;
1549 mLatestActiveTrack = track;
1550 ++mBatteryCounter[track->uid()].second;
1551 return mActiveTracks.add(track);
1552}
1553
1554template <typename T>
1555ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1556 ssize_t index = mActiveTracks.remove(track);
1557 if (index < 0) {
1558 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1559 return index;
1560 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001561 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001562 mActiveTracksGeneration++;
1563 --mBatteryCounter[track->uid()].second;
1564 // mLatestActiveTrack is not cleared even if is the same as track.
1565 return index;
1566}
1567
1568template <typename T>
1569void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1570 for (const sp<T> &track : mActiveTracks) {
1571 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001572 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001573 }
1574 mLastActiveTracksGeneration = mActiveTracksGeneration;
1575 mActiveTracks.clear();
1576 mLatestActiveTrack.clear();
1577 mBatteryCounter.clear();
1578}
1579
1580template <typename T>
1581void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1582 sp<ThreadBase> thread, bool force) {
1583 // Updates ActiveTracks client uids to the thread wakelock.
1584 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1585 thread->updateWakeLockUids_l(getWakeLockUids());
1586 mLastActiveTracksGeneration = mActiveTracksGeneration;
1587 }
1588
1589 // Updates BatteryNotifier uids
1590 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1591 const uid_t uid = it->first;
1592 ssize_t &previous = it->second.first;
1593 ssize_t &current = it->second.second;
1594 if (current > 0) {
1595 if (previous == 0) {
1596 BatteryNotifier::getInstance().noteStartAudio(uid);
1597 }
1598 previous = current;
1599 ++it;
1600 } else if (current == 0) {
1601 if (previous > 0) {
1602 BatteryNotifier::getInstance().noteStopAudio(uid);
1603 }
1604 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1605 } else /* (current < 0) */ {
1606 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1607 }
1608 }
1609}
Eric Laurent83b88082014-06-20 18:31:16 -07001610
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001611template <typename T>
1612void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1613 const char *funcName, const sp<T> &track) const {
1614 if (mLocalLog != nullptr) {
1615 String8 result;
1616 track->appendDump(result, false /* active */);
1617 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1618 }
1619}
1620
Eric Laurent6acd1d42017-01-04 14:23:29 -08001621void AudioFlinger::ThreadBase::broadcast_l()
1622{
1623 // Thread could be blocked waiting for async
1624 // so signal it to handle state changes immediately
1625 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1626 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1627 mSignalPending = true;
1628 mWaitWorkCV.broadcast();
1629}
1630
Eric Laurent81784c32012-11-19 14:55:58 -08001631// ----------------------------------------------------------------------------
1632// Playback
1633// ----------------------------------------------------------------------------
1634
1635AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1636 AudioStreamOut* output,
1637 audio_io_handle_t id,
1638 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001639 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001640 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001641 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001642 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001643 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001644 mMixerBuffer(NULL),
1645 mMixerBufferSize(0),
1646 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1647 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001648 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001649 mEffectBuffer(NULL),
1650 mEffectBufferSize(0),
1651 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1652 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001653 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001654 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001655 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001656 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // mStreamTypes[] initialized in constructor body
1658 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001659 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mMixerStatus(MIXER_IDLE),
1661 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001662 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 mBytesRemaining(0),
1664 mCurrentWriteLength(0),
1665 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001666 mWriteAckSequence(0),
1667 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001668 mScreenState(AudioFlinger::mScreenState),
1669 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001670 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001671 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1672 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001673{
Glenn Kastend7dca052015-03-05 16:05:54 -08001674 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1675 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001676
1677 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1678 // it would be safer to explicitly pass initial masterVolume/masterMute as
1679 // parameter.
1680 //
1681 // If the HAL we are using has support for master volume or master mute,
1682 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1683 // and the mute set to false).
1684 mMasterVolume = audioFlinger->masterVolume_l();
1685 mMasterMute = audioFlinger->masterMute_l();
1686 if (mOutput && mOutput->audioHwDev) {
1687 if (mOutput->audioHwDev->canSetMasterVolume()) {
1688 mMasterVolume = 1.0;
1689 }
1690
1691 if (mOutput->audioHwDev->canSetMasterMute()) {
1692 mMasterMute = false;
1693 }
1694 }
1695
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001696 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001697
Eric Laurent223fd5c2014-11-11 13:43:36 -08001698 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001699 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001700 stream = (audio_stream_type_t) (stream + 1)) {
1701 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1702 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704}
1705
1706AudioFlinger::PlaybackThread::~PlaybackThread()
1707{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001708 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001709 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001710 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001711 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001712}
1713
1714void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1715{
1716 dumpInternals(fd, args);
1717 dumpTracks(fd, args);
1718 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001719 dprintf(fd, " Local log:\n");
1720 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001721}
1722
Glenn Kasten0f11b512014-01-31 16:18:54 -08001723void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001724{
Eric Laurent81784c32012-11-19 14:55:58 -08001725 String8 result;
1726
Marco Nelissenb2208842014-02-07 14:00:50 -08001727 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001728 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1729 const stream_type_t *st = &mStreamTypes[i];
1730 if (i > 0) {
1731 result.appendFormat(", ");
1732 }
1733 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1734 if (st->mute) {
1735 result.append("M");
1736 }
1737 }
1738 result.append("\n");
1739 write(fd, result.string(), result.length());
1740 result.clear();
1741
Eric Laurent81784c32012-11-19 14:55:58 -08001742 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1743 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001744 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001745 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001746
1747 size_t numtracks = mTracks.size();
1748 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001749 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001750 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001751 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001752 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001753 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001754 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001755 Track::appendDumpHeader(result);
1756 for (size_t i = 0; i < numtracks; ++i) {
1757 sp<Track> track = mTracks[i];
1758 if (track != 0) {
1759 bool active = mActiveTracks.indexOf(track) >= 0;
1760 if (active) {
1761 numactiveseen++;
1762 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001763 result.append(prefix);
1764 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001765 }
1766 }
1767 } else {
1768 result.append("\n");
1769 }
1770 if (numactiveseen != numactive) {
1771 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001772 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001773 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001774 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775 Track::appendDumpHeader(result);
1776 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001777 sp<Track> track = mActiveTracks[i];
1778 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001779 result.append(prefix);
1780 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001781 }
1782 }
1783 }
1784
1785 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001786}
1787
1788void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1789{
Glenn Kasten44182c22015-03-05 17:12:23 -08001790 dumpBase(fd, args);
1791
Elliott Hughes87cebad2014-05-22 10:14:43 -07001792 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001793 dprintf(fd, " Last write occurred (msecs): %llu\n",
1794 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001795 dprintf(fd, " Total writes: %d\n", mNumWrites);
1796 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1797 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1798 dprintf(fd, " Suspend count: %d\n", mSuspended);
1799 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1800 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1801 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1802 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001803 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001804 AudioStreamOut *output = mOutput;
1805 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001806 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1807 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001808 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1809 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1810 if (mPipeSink.get() != nullptr) {
1811 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1812 }
1813 if (output != nullptr) {
1814 dprintf(fd, " Hal stream dump:\n");
1815 (void)output->stream->dump(fd);
1816 }
Eric Laurent81784c32012-11-19 14:55:58 -08001817}
1818
1819// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001820
1821void AudioFlinger::PlaybackThread::onFirstRef()
1822{
Glenn Kastend7dca052015-03-05 16:05:54 -08001823 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001824}
1825
1826// ThreadBase virtuals
1827void AudioFlinger::PlaybackThread::preExit()
1828{
1829 ALOGV(" preExit()");
1830 // FIXME this is using hard-coded strings but in the future, this functionality will be
1831 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001832 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1833 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001834}
1835
1836// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1837sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1838 const sp<AudioFlinger::Client>& client,
1839 audio_stream_type_t streamType,
1840 uint32_t sampleRate,
1841 audio_format_t format,
1842 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001843 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001844 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001845 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001846 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001847 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001848 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001849 status_t *status,
1850 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001851{
Glenn Kasten74935e42013-12-19 08:56:45 -08001852 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001853 sp<Track> track;
1854 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001855 audio_output_flags_t outputFlags = mOutput->flags;
1856
1857 // special case for FAST flag considered OK if fast mixer is present
1858 if (hasFastMixer()) {
1859 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1860 }
1861
1862 // Check if requested flags are compatible with output stream flags
1863 if ((*flags & outputFlags) != *flags) {
1864 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1865 *flags, outputFlags);
1866 *flags = (audio_output_flags_t)(*flags & outputFlags);
1867 }
Eric Laurent81784c32012-11-19 14:55:58 -08001868
Eric Laurent81784c32012-11-19 14:55:58 -08001869 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001870 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001871 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001872 // PCM data
1873 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001874 // TODO: extract as a data library function that checks that a computationally
1875 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001876 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001877 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1878 (channelMask == AUDIO_CHANNEL_OUT_MONO
1879 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001880 // hardware sample rate
1881 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001882 // normal mixer has an associated fast mixer
1883 hasFastMixer() &&
1884 // there are sufficient fast track slots available
1885 (mFastTrackAvailMask != 0)
1886 // FIXME test that MixerThread for this fast track has a capable output HAL
1887 // FIXME add a permission test also?
1888 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001889 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1890 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001891 // read the fast track multiplier property the first time it is needed
1892 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1893 if (ok != 0) {
1894 ALOGE("%s pthread_once failed: %d", __func__, ok);
1895 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001896 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001897 }
Eric Laurent4c415062016-06-17 16:14:16 -07001898
1899 // check compatibility with audio effects.
1900 { // scope for mLock
1901 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001902 for (audio_session_t session : {
1903 AUDIO_SESSION_OUTPUT_STAGE,
1904 AUDIO_SESSION_OUTPUT_MIX,
1905 sessionId,
1906 }) {
1907 sp<EffectChain> chain = getEffectChain_l(session);
1908 if (chain.get() != nullptr) {
1909 audio_output_flags_t old = *flags;
1910 chain->checkOutputFlagCompatibility(flags);
1911 if (old != *flags) {
1912 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1913 (int)session, (int)old, (int)*flags);
1914 }
Eric Laurent4c415062016-06-17 16:14:16 -07001915 }
1916 }
1917 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001918 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001919 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1920 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001921 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001922 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1923 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001924 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001925 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001926 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001927 audio_is_linear_pcm(format),
1928 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001929 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001930 }
1931 }
1932 // For normal PCM streaming tracks, update minimum frame count.
1933 // For compatibility with AudioTrack calculation, buffer depth is forced
1934 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1935 // This is probably too conservative, but legacy application code may depend on it.
1936 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001937 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001938 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001939 // this must match AudioTrack.cpp calculateMinFrameCount().
1940 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001941 uint32_t latencyMs = 0;
1942 lStatus = mOutput->stream->getLatency(&latencyMs);
1943 if (lStatus != OK) {
1944 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1945 goto Exit;
1946 }
Eric Laurent81784c32012-11-19 14:55:58 -08001947 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1948 if (minBufCount < 2) {
1949 minBufCount = 2;
1950 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001951 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1952 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001953 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001954 minBufCount * sourceFramesNeededWithTimestretch(
1955 sampleRate, mNormalFrameCount,
1956 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001957 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001958 frameCount = minFrameCount;
1959 }
Eric Laurent81784c32012-11-19 14:55:58 -08001960 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001961 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001962
Glenn Kastenc3df8382014-03-13 15:05:25 -07001963 switch (mType) {
1964
1965 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001966 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001967 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001968 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1969 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001970 sampleRate, format, channelMask, mOutput, mFormat);
1971 lStatus = BAD_VALUE;
1972 goto Exit;
1973 }
1974 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001975 break;
1976
1977 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001978 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001979 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1980 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001981 sampleRate, format, channelMask, mOutput, mFormat);
1982 lStatus = BAD_VALUE;
1983 goto Exit;
1984 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001985 break;
1986
1987 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001988 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001989 ALOGE("createTrack_l() Bad parameter: format %#x \""
1990 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001991 format, mOutput, mFormat);
1992 lStatus = BAD_VALUE;
1993 goto Exit;
1994 }
Andy Hungcd044842014-08-07 11:04:34 -07001995 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001996 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1997 lStatus = BAD_VALUE;
1998 goto Exit;
1999 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002000 break;
2001
Eric Laurent81784c32012-11-19 14:55:58 -08002002 }
2003
2004 lStatus = initCheck();
2005 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002006 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002007 goto Exit;
2008 }
2009
2010 { // scope for mLock
2011 Mutex::Autolock _l(mLock);
2012
2013 // all tracks in same audio session must share the same routing strategy otherwise
2014 // conflicts will happen when tracks are moved from one output to another by audio policy
2015 // manager
2016 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2017 for (size_t i = 0; i < mTracks.size(); ++i) {
2018 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002019 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002020 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2021 if (sessionId == t->sessionId() && strategy != actual) {
2022 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2023 strategy, actual);
2024 lStatus = BAD_VALUE;
2025 goto Exit;
2026 }
2027 }
2028 }
2029
Glenn Kastend79072e2016-01-06 08:41:20 -08002030 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002031 channelMask, frameCount,
2032 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002033 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002034
Glenn Kasten03003332013-08-06 15:40:54 -07002035 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2036 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002037 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002038 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002039 goto Exit;
2040 }
2041 mTracks.add(track);
2042
2043 sp<EffectChain> chain = getEffectChain_l(sessionId);
2044 if (chain != 0) {
2045 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2046 track->setMainBuffer(chain->inBuffer());
2047 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2048 chain->incTrackCnt();
2049 }
2050
Eric Laurent05067782016-06-01 18:27:28 -07002051 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002052 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2053 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2054 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002055 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002056 }
2057 }
2058
2059 lStatus = NO_ERROR;
2060
2061Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002062 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002063 return track;
2064}
2065
2066uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2067{
2068 return latency;
2069}
2070
2071uint32_t AudioFlinger::PlaybackThread::latency() const
2072{
2073 Mutex::Autolock _l(mLock);
2074 return latency_l();
2075}
2076uint32_t AudioFlinger::PlaybackThread::latency_l() const
2077{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002078 uint32_t latency;
2079 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2080 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002081 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002082 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002083}
2084
2085void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2086{
2087 Mutex::Autolock _l(mLock);
2088 // Don't apply master volume in SW if our HAL can do it for us.
2089 if (mOutput && mOutput->audioHwDev &&
2090 mOutput->audioHwDev->canSetMasterVolume()) {
2091 mMasterVolume = 1.0;
2092 } else {
2093 mMasterVolume = value;
2094 }
2095}
2096
2097void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2098{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002099 if (isDuplicating()) {
2100 return;
2101 }
Eric Laurent81784c32012-11-19 14:55:58 -08002102 Mutex::Autolock _l(mLock);
2103 // Don't apply master mute in SW if our HAL can do it for us.
2104 if (mOutput && mOutput->audioHwDev &&
2105 mOutput->audioHwDev->canSetMasterMute()) {
2106 mMasterMute = false;
2107 } else {
2108 mMasterMute = muted;
2109 }
2110}
2111
2112void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2113{
2114 Mutex::Autolock _l(mLock);
2115 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002116 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002117}
2118
2119void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2120{
2121 Mutex::Autolock _l(mLock);
2122 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002123 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002124}
2125
2126float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2127{
2128 Mutex::Autolock _l(mLock);
2129 return mStreamTypes[stream].volume;
2130}
2131
2132// addTrack_l() must be called with ThreadBase::mLock held
2133status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2134{
2135 status_t status = ALREADY_EXISTS;
2136
Eric Laurent81784c32012-11-19 14:55:58 -08002137 if (mActiveTracks.indexOf(track) < 0) {
2138 // the track is newly added, make sure it fills up all its
2139 // buffers before playing. This is to ensure the client will
2140 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002141 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002142 TrackBase::track_state state = track->mState;
2143 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002144 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002145 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 mLock.lock();
2147 // abort track was stopped/paused while we released the lock
2148 if (state != track->mState) {
2149 if (status == NO_ERROR) {
2150 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002151 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002152 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 mLock.lock();
2154 }
2155 return INVALID_OPERATION;
2156 }
2157 // abort if start is rejected by audio policy manager
2158 if (status != NO_ERROR) {
2159 return PERMISSION_DENIED;
2160 }
2161#ifdef ADD_BATTERY_DATA
2162 // to track the speaker usage
2163 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2164#endif
2165 }
2166
Eric Laurent51716182016-02-29 18:00:56 -08002167 // set retry count for buffer fill
2168 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002169 if (track->isStopping_1()) {
2170 track->mRetryCount = kMaxTrackStopRetriesOffload;
2171 } else {
2172 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2173 }
2174 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002175 } else {
2176 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002177 track->mFillingUpStatus =
2178 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002179 }
2180
Eric Laurent81784c32012-11-19 14:55:58 -08002181 track->mResetDone = false;
2182 track->mPresentationCompleteFrames = 0;
2183 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002184 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2185 if (chain != 0) {
2186 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2187 track->sessionId());
2188 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002189 }
2190
2191 status = NO_ERROR;
2192 }
2193
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002194 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002195 return status;
2196}
2197
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002199{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002201 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2203 track->mState = TrackBase::STOPPED;
2204 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002205 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002206 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002208 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002209
2210 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002211}
2212
2213void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2214{
2215 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002216
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002217 String8 result;
2218 track->appendDump(result, false /* active */);
2219 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002220
Eric Laurent81784c32012-11-19 14:55:58 -08002221 mTracks.remove(track);
2222 deleteTrackName_l(track->name());
2223 // redundant as track is about to be destroyed, for dumpsys only
2224 track->mName = -1;
2225 if (track->isFastTrack()) {
2226 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002227 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002228 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2229 mFastTrackAvailMask |= 1 << index;
2230 // redundant as track is about to be destroyed, for dumpsys only
2231 track->mFastIndex = -1;
2232 }
2233 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2234 if (chain != 0) {
2235 chain->decTrackCnt();
2236 }
2237}
2238
2239String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2240{
Eric Laurent81784c32012-11-19 14:55:58 -08002241 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002242 String8 out_s8;
2243 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2244 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002245 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002246 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002247}
2248
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002249void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002250 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2251 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002252
Eric Laurent73e26b62015-04-27 16:55:58 -07002253 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002254
2255 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002256 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002257 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002258 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002259 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002260 desc->mChannelMask = mChannelMask;
2261 desc->mSamplingRate = mSampleRate;
2262 desc->mFormat = mFormat;
2263 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002264 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002265 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002266 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002267 break;
2268
Eric Laurent73e26b62015-04-27 16:55:58 -07002269 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002270 default:
2271 break;
2272 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002273 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002274}
2275
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002276void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002277{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002278 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279}
2280
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002281void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002283 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284}
2285
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002286void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002287{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002288 mCallbackThread->setAsyncError();
2289}
2290
Eric Laurent3b4529e2013-09-05 18:09:19 -07002291void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292{
2293 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002294 // reject out of sequence requests
2295 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2296 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297 mWaitWorkCV.signal();
2298 }
2299}
2300
Eric Laurent3b4529e2013-09-05 18:09:19 -07002301void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002302{
2303 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002304 // reject out of sequence requests
2305 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2306 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002307 mWaitWorkCV.signal();
2308 }
2309}
2310
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002311void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002312{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002313 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002314 mSampleRate = mOutput->getSampleRate();
2315 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002316 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002317 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002318 }
Andy Hung9a592762014-07-21 21:56:01 -07002319 if ((mType == MIXER || mType == DUPLICATING)
2320 && !isValidPcmSinkChannelMask(mChannelMask)) {
2321 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2322 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002323 }
Andy Hunge5412692014-05-16 11:25:07 -07002324 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002325
2326 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002327 status_t result = mOutput->stream->getFormat(&mHALFormat);
2328 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002329 // Get format from the shim, which will be different than the HAL format
2330 // if playing compressed audio over HDMI passthrough.
2331 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002332 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002333 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002334 }
Andy Hung6146c082014-03-18 11:56:15 -07002335 if ((mType == MIXER || mType == DUPLICATING)
2336 && !isValidPcmSinkFormat(mFormat)) {
2337 LOG_FATAL("HAL format %#x not supported for mixed output",
2338 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002339 }
Phil Burk062e67a2015-02-11 13:40:50 -08002340 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002341 result = mOutput->stream->getBufferSize(&mBufferSize);
2342 LOG_ALWAYS_FATAL_IF(result != OK,
2343 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002344 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002345 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002346 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002347 mFrameCount);
2348 }
2349
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002350 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2351 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002352 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002353 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002354 }
2355 }
2356
Eric Laurentd1f69b02014-12-15 14:33:13 -08002357 mHwSupportsPause = false;
2358 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002359 bool supportsPause = false, supportsResume = false;
2360 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2361 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002362 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002363 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002364 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002365 } else if (supportsResume) {
2366 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002367 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002368 }
2369 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002370 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2371 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2372 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002373
Andy Hungfbfc3952015-01-15 13:33:51 -08002374 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2375 // For best precision, we use float instead of the associated output
2376 // device format (typically PCM 16 bit).
2377
2378 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2379 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2380 mBufferSize = mFrameSize * mFrameCount;
2381
2382 // TODO: We currently use the associated output device channel mask and sample rate.
2383 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2384 // (if a valid mask) to avoid premature downmix.
2385 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2386 // instead of the output device sample rate to avoid loss of high frequency information.
2387 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2388 }
2389
Andy Hung09a50072014-02-27 14:30:47 -08002390 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002391 double multiplier = 1.0;
2392 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2393 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002394 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2395 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002396
Eric Laurent81784c32012-11-19 14:55:58 -08002397 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2398 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2399 maxNormalFrameCount = maxNormalFrameCount & ~15;
2400 if (maxNormalFrameCount < minNormalFrameCount) {
2401 maxNormalFrameCount = minNormalFrameCount;
2402 }
2403 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2404 if (multiplier <= 1.0) {
2405 multiplier = 1.0;
2406 } else if (multiplier <= 2.0) {
2407 if (2 * mFrameCount <= maxNormalFrameCount) {
2408 multiplier = 2.0;
2409 } else {
2410 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2411 }
2412 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002413 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002414 }
2415 }
2416 mNormalFrameCount = multiplier * mFrameCount;
2417 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002418 if (mType == MIXER || mType == DUPLICATING) {
2419 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2420 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002421 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002422 mNormalFrameCount);
2423
Andy Hung08fb1742015-05-31 23:22:10 -07002424 // Check if we want to throttle the processing to no more than 2x normal rate
2425 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002426 mThreadThrottleTimeMs = 0;
2427 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002428 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2429
Andy Hung010a1a12014-03-13 13:57:33 -07002430 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2431 // Originally this was int16_t[] array, need to remove legacy implications.
2432 free(mSinkBuffer);
2433 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002434 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2435 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2436 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002437 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002438
Andy Hung69aed5f2014-02-25 17:24:40 -08002439 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2440 // drives the output.
2441 free(mMixerBuffer);
2442 mMixerBuffer = NULL;
2443 if (mMixerBufferEnabled) {
2444 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2445 mMixerBufferSize = mNormalFrameCount * mChannelCount
2446 * audio_bytes_per_sample(mMixerBufferFormat);
2447 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2448 }
Andy Hung98ef9782014-03-04 14:46:50 -08002449 free(mEffectBuffer);
2450 mEffectBuffer = NULL;
2451 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002452 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002453 mEffectBufferSize = mNormalFrameCount * mChannelCount
2454 * audio_bytes_per_sample(mEffectBufferFormat);
2455 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2456 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002457
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // force reconfiguration of effect chains and engines to take new buffer size and audio
2459 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002460 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002461 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2462 // matter.
2463 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2464 Vector< sp<EffectChain> > effectChains = mEffectChains;
2465 for (size_t i = 0; i < effectChains.size(); i ++) {
2466 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2467 }
2468}
2469
2470
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002471status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002472{
2473 if (halFrames == NULL || dspFrames == NULL) {
2474 return BAD_VALUE;
2475 }
2476 Mutex::Autolock _l(mLock);
2477 if (initCheck() != NO_ERROR) {
2478 return INVALID_OPERATION;
2479 }
Andy Hung818e7a32016-02-16 18:08:07 -08002480 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002481 *halFrames = framesWritten;
2482
2483 if (isSuspended()) {
2484 // return an estimation of rendered frames when the output is suspended
2485 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002486 *dspFrames = (uint32_t)
2487 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002488 return NO_ERROR;
2489 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002490 status_t status;
2491 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002492 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002493 *dspFrames = (size_t)frames;
2494 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002495 }
2496}
2497
Eric Laurent4c415062016-06-17 16:14:16 -07002498// hasAudioSession_l() must be called with ThreadBase::mLock held
2499uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002500{
Eric Laurent81784c32012-11-19 14:55:58 -08002501 uint32_t result = 0;
2502 if (getEffectChain_l(sessionId) != 0) {
2503 result = EFFECT_SESSION;
2504 }
2505
2506 for (size_t i = 0; i < mTracks.size(); ++i) {
2507 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002508 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002509 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002510 if (track->isFastTrack()) {
2511 result |= FAST_SESSION;
2512 }
Eric Laurent81784c32012-11-19 14:55:58 -08002513 break;
2514 }
2515 }
2516
2517 return result;
2518}
2519
Glenn Kastend848eb42016-03-08 13:42:11 -08002520uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002521{
2522 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2523 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2524 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2525 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2526 }
2527 for (size_t i = 0; i < mTracks.size(); i++) {
2528 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002529 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002530 return AudioSystem::getStrategyForStream(track->streamType());
2531 }
2532 }
2533 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2534}
2535
2536
Phil Burk062e67a2015-02-11 13:40:50 -08002537AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002538{
2539 Mutex::Autolock _l(mLock);
2540 return mOutput;
2541}
2542
Phil Burk062e67a2015-02-11 13:40:50 -08002543AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002544{
2545 Mutex::Autolock _l(mLock);
2546 AudioStreamOut *output = mOutput;
2547 mOutput = NULL;
2548 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2549 // must push a NULL and wait for ack
2550 mOutputSink.clear();
2551 mPipeSink.clear();
2552 mNormalSink.clear();
2553 return output;
2554}
2555
2556// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002557sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002558{
2559 if (mOutput == NULL) {
2560 return NULL;
2561 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002562 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002563}
2564
2565uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2566{
2567 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2568}
2569
2570status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2571{
2572 if (!isValidSyncEvent(event)) {
2573 return BAD_VALUE;
2574 }
2575
2576 Mutex::Autolock _l(mLock);
2577
2578 for (size_t i = 0; i < mTracks.size(); ++i) {
2579 sp<Track> track = mTracks[i];
2580 if (event->triggerSession() == track->sessionId()) {
2581 (void) track->setSyncEvent(event);
2582 return NO_ERROR;
2583 }
2584 }
2585
2586 return NAME_NOT_FOUND;
2587}
2588
2589bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2590{
2591 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2592}
2593
2594void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2595 const Vector< sp<Track> >& tracksToRemove)
2596{
2597 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002598 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002599 for (size_t i = 0 ; i < count ; i++) {
2600 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002601 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002602 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002603 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002604#ifdef ADD_BATTERY_DATA
2605 // to track the speaker usage
2606 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2607#endif
2608 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002609 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002610 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002611 }
Eric Laurent81784c32012-11-19 14:55:58 -08002612 }
2613 }
2614 }
Eric Laurent81784c32012-11-19 14:55:58 -08002615}
2616
2617void AudioFlinger::PlaybackThread::checkSilentMode_l()
2618{
2619 if (!mMasterMute) {
2620 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002621 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2622 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2623 return;
2624 }
Eric Laurent81784c32012-11-19 14:55:58 -08002625 if (property_get("ro.audio.silent", value, "0") > 0) {
2626 char *endptr;
2627 unsigned long ul = strtoul(value, &endptr, 0);
2628 if (*endptr == '\0' && ul != 0) {
2629 ALOGD("Silence is golden");
2630 // The setprop command will not allow a property to be changed after
2631 // the first time it is set, so we don't have to worry about un-muting.
2632 setMasterMute_l(true);
2633 }
2634 }
2635 }
2636}
2637
2638// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002640{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002641 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002642 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002644 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002645
2646 // If an NBAIO sink is present, use it to write the normal mixer's submix
2647 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002648
Andy Hung010a1a12014-03-13 13:57:33 -07002649 const size_t count = mBytesRemaining / mFrameSize;
2650
Simon Wilson2d590962012-11-29 15:18:50 -08002651 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002652 // update the setpoint when AudioFlinger::mScreenState changes
2653 uint32_t screenState = AudioFlinger::mScreenState;
2654 if (screenState != mScreenState) {
2655 mScreenState = screenState;
2656 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2657 if (pipe != NULL) {
2658 pipe->setAvgFrames((mScreenState & 1) ?
2659 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2660 }
2661 }
Andy Hung010a1a12014-03-13 13:57:33 -07002662 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002663 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002664 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002665 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002666 } else {
2667 bytesWritten = framesWritten;
2668 }
2669 // otherwise use the HAL / AudioStreamOut directly
2670 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002672
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002674 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2675 mWriteAckSequence += 2;
2676 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002678 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002680 // FIXME We should have an implementation of timestamps for direct output threads.
2681 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002682 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002683
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 if (mUseAsyncWrite &&
2685 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2686 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002687 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002689 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002690 }
Eric Laurent81784c32012-11-19 14:55:58 -08002691 }
2692
Eric Laurent81784c32012-11-19 14:55:58 -08002693 mNumWrites++;
2694 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002695 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002696 return bytesWritten;
2697}
2698
2699void AudioFlinger::PlaybackThread::threadLoop_drain()
2700{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002701 bool supportsDrain = false;
2702 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2704 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002705 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2706 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002708 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002710 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002711 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002712 }
2713}
2714
2715void AudioFlinger::PlaybackThread::threadLoop_exit()
2716{
Eric Laurent275e8e92014-11-30 15:14:47 -08002717 {
2718 Mutex::Autolock _l(mLock);
2719 for (size_t i = 0; i < mTracks.size(); i++) {
2720 sp<Track> track = mTracks[i];
2721 track->invalidate();
2722 }
Andy Hungdae27702016-10-31 14:01:16 -07002723 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2724 // After we exit there are no more track changes sent to BatteryNotifier
2725 // because that requires an active threadLoop.
2726 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2727 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002728 }
Eric Laurent81784c32012-11-19 14:55:58 -08002729}
2730
2731/*
2732The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002733 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002734 - mActiveSleepTimeUs from activeSleepTimeUs()
2735 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002736 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2737 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002738 - maxPeriod from frame count and sample rate (MIXER only)
2739
2740The parameters that affect these derived values are:
2741 - frame count
2742 - frame size
2743 - sample rate
2744 - device type: A2DP or not
2745 - device latency
2746 - format: PCM or not
2747 - active sleep time
2748 - idle sleep time
2749*/
2750
2751void AudioFlinger::PlaybackThread::cacheParameters_l()
2752{
Andy Hung25c2dac2014-02-27 14:56:00 -08002753 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002754 mActiveSleepTimeUs = activeSleepTimeUs();
2755 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002756
2757 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2758 // truncating audio when going to standby.
2759 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2760 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2761 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2762 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2763 }
2764 }
Eric Laurent81784c32012-11-19 14:55:58 -08002765}
2766
Eric Laurent13084622016-05-17 10:51:49 -07002767bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002768{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002769 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002770 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002771 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002772 size_t size = mTracks.size();
2773 for (size_t i = 0; i < size; i++) {
2774 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002775 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002776 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002777 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002778 }
2779 }
Eric Laurent13084622016-05-17 10:51:49 -07002780 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002781}
2782
Haynes Mathew George05317d22016-05-03 16:34:26 -07002783void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2784{
2785 Mutex::Autolock _l(mLock);
2786 invalidateTracks_l(streamType);
2787}
2788
Eric Laurent81784c32012-11-19 14:55:58 -08002789status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2790{
Glenn Kastend848eb42016-03-08 13:42:11 -08002791 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002792 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2793 status_t result = EffectBufferHalInterface::mirror(
2794 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2795 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2796 &halInBuffer);
2797 if (result != OK) return result;
2798 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002799 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002800 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002801 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002802 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002803 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002804 if (mType != DIRECT) {
2805 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002806 status_t result = EffectBufferHalInterface::allocate(
rago94a1ee82017-07-21 15:11:02 -07002807 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002808 &halInBuffer);
2809 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002810#ifdef FLOAT_EFFECT_CHAIN
2811 buffer = halInBuffer->audioBuffer()->f32;
2812#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08002813 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07002814#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08002815 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2816 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002817 }
2818
2819 // Attach all tracks with same session ID to this chain.
2820 for (size_t i = 0; i < mTracks.size(); ++i) {
2821 sp<Track> track = mTracks[i];
2822 if (session == track->sessionId()) {
2823 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2824 buffer);
2825 track->setMainBuffer(buffer);
2826 chain->incTrackCnt();
2827 }
2828 }
2829
2830 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002831 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002832 if (session == track->sessionId()) {
2833 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2834 chain->incActiveTrackCnt();
2835 }
2836 }
2837 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002838 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002839 chain->setInBuffer(halInBuffer);
2840 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002842 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002843 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2844 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002845 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002846 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002847 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002848 // Effect chain for other sessions are inserted at beginning of effect
2849 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002850 // sessions is not important.
2851 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2852 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2853 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002854 size_t size = mEffectChains.size();
2855 size_t i = 0;
2856 for (i = 0; i < size; i++) {
2857 if (mEffectChains[i]->sessionId() < session) {
2858 break;
2859 }
2860 }
2861 mEffectChains.insertAt(chain, i);
2862 checkSuspendOnAddEffectChain_l(chain);
2863
2864 return NO_ERROR;
2865}
2866
2867size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2868{
Glenn Kastend848eb42016-03-08 13:42:11 -08002869 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002870
2871 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2872
2873 for (size_t i = 0; i < mEffectChains.size(); i++) {
2874 if (chain == mEffectChains[i]) {
2875 mEffectChains.removeAt(i);
2876 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002877 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002878 if (session == track->sessionId()) {
2879 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2880 chain.get(), session);
2881 chain->decActiveTrackCnt();
2882 }
2883 }
2884
2885 // detach all tracks with same session ID from this chain
2886 for (size_t i = 0; i < mTracks.size(); ++i) {
2887 sp<Track> track = mTracks[i];
2888 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07002889 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002890 chain->decTrackCnt();
2891 }
2892 }
2893 break;
2894 }
2895 }
2896 return mEffectChains.size();
2897}
2898
2899status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002900 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002901{
2902 Mutex::Autolock _l(mLock);
2903 return attachAuxEffect_l(track, EffectId);
2904}
2905
2906status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002907 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002908{
2909 status_t status = NO_ERROR;
2910
2911 if (EffectId == 0) {
2912 track->setAuxBuffer(0, NULL);
2913 } else {
2914 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2915 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2916 if (effect != 0) {
2917 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2918 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2919 } else {
2920 status = INVALID_OPERATION;
2921 }
2922 } else {
2923 status = BAD_VALUE;
2924 }
2925 }
2926 return status;
2927}
2928
2929void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2930{
2931 for (size_t i = 0; i < mTracks.size(); ++i) {
2932 sp<Track> track = mTracks[i];
2933 if (track->auxEffectId() == effectId) {
2934 attachAuxEffect_l(track, 0);
2935 }
2936 }
2937}
2938
2939bool AudioFlinger::PlaybackThread::threadLoop()
2940{
Glenn Kasten388d5712017-04-07 14:38:41 -07002941 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002942
Eric Laurent81784c32012-11-19 14:55:58 -08002943 Vector< sp<Track> > tracksToRemove;
2944
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002945 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002946 nsecs_t lastWriteFinished = -1; // time last server write completed
2947 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002948
2949 // MIXER
2950 nsecs_t lastWarning = 0;
2951
2952 // DUPLICATING
2953 // FIXME could this be made local to while loop?
2954 writeFrames = 0;
2955
2956 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002957 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002958
2959 if (mType == MIXER) {
2960 sleepTimeShift = 0;
2961 }
2962
2963 CpuStats cpuStats;
2964 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2965
2966 acquireWakeLock();
2967
Glenn Kasteneef598c2017-04-03 14:41:13 -07002968 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2969 // thread associated with this PlaybackThread.
2970 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2971 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002972 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2973 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002974 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002975 const char *logString = NULL;
2976
rago1bb90822017-05-02 18:31:48 -07002977 // Estimated time for next buffer to be written to hal. This is used only on
2978 // suspended mode (for now) to help schedule the wait time until next iteration.
2979 nsecs_t timeLoopNextNs = 0;
2980
Eric Laurent664539d2013-09-23 18:24:31 -07002981 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002982
Eric Laurent81784c32012-11-19 14:55:58 -08002983 while (!exitPending())
2984 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002985 // Log merge requests are performed during AudioFlinger binder transactions, but
2986 // that does not cover audio playback. It's requested here for that reason.
2987 mAudioFlinger->requestLogMerge();
2988
Eric Laurent81784c32012-11-19 14:55:58 -08002989 cpuStats.sample(myName);
2990
2991 Vector< sp<EffectChain> > effectChains;
2992
Eric Laurent81784c32012-11-19 14:55:58 -08002993 { // scope for mLock
2994
2995 Mutex::Autolock _l(mLock);
2996
Eric Laurent021cf962014-05-13 10:18:14 -07002997 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002998
Glenn Kasteneef598c2017-04-03 14:41:13 -07002999 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003000 if (logString != NULL) {
3001 mNBLogWriter->logTimestamp();
3002 mNBLogWriter->log(logString);
3003 logString = NULL;
3004 }
3005
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003006 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003007 // and associate with the sink frames written out. We need
3008 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003009 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003010 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003011 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003012 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003013 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003014 ExtendedTimestamp timestamp; // use private copy to fetch
3015 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003016
3017 // We keep track of the last valid kernel position in case we are in underrun
3018 // and the normal mixer period is the same as the fast mixer period, or there
3019 // is some error from the HAL.
3020 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3021 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3022 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3023 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3024 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3025
3026 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3027 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3028 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3029 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003030 }
3031
3032 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3033 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003034 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003035 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003036 }
3037
Andy Hung818e7a32016-02-16 18:08:07 -08003038 // copy over kernel info
3039 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003040 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3041 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003042 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3043 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003044 }
3045 // mFramesWritten for non-offloaded tracks are contiguous
3046 // even after standby() is called. This is useful for the track frame
3047 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003048 bool serverLocationUpdate = false;
3049 if (mFramesWritten != lastFramesWritten) {
3050 serverLocationUpdate = true;
3051 lastFramesWritten = mFramesWritten;
3052 }
3053 // Only update timestamps if there is a meaningful change.
3054 // Either the kernel timestamp must be valid or we have written something.
3055 if (kernelLocationUpdate || serverLocationUpdate) {
3056 if (serverLocationUpdate) {
3057 // use the time before we called the HAL write - it is a bit more accurate
3058 // to when the server last read data than the current time here.
3059 //
3060 // If we haven't written anything, mLastWriteTime will be -1
3061 // and we use systemTime().
3062 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3063 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3064 ? systemTime() : mLastWriteTime;
3065 }
Andy Hungdae27702016-10-31 14:01:16 -07003066
3067 for (const sp<Track> &t : mActiveTracks) {
3068 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003069 t->updateTrackFrameInfo(
3070 t->mAudioTrackServerProxy->framesReleased(),
3071 mFramesWritten,
3072 mTimestamp);
3073 }
Andy Hunge10393e2015-06-12 13:59:33 -07003074 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003075 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003076#if 0
3077 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003078 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003079 timespec ts;
3080 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003081 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003082 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003083 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003084 }
3085 ++z;
3086#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003087 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003088 if (mSignalPending) {
3089 // A signal was raised while we were unlocked
3090 mSignalPending = false;
3091 } else if (waitingAsyncCallback_l()) {
3092 if (exitPending()) {
3093 break;
3094 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003095 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003096 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003097 releaseWakeLock_l();
3098 released = true;
3099 }
Andy Hung10cbff12017-02-21 17:30:14 -08003100
3101 const int64_t waitNs = computeWaitTimeNs_l();
3102 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3103 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3104 if (status == TIMED_OUT) {
3105 mSignalPending = true; // if timeout recheck everything
3106 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003108 if (released) {
3109 acquireWakeLock_l();
3110 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003111 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3112 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003113
3114 continue;
3115 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003116 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117 isSuspended()) {
3118 // put audio hardware into standby after short delay
3119 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003120
3121 threadLoop_standby();
3122
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003123 // This is where we go into standby
3124 if (!mStandby) {
3125 LOG_AUDIO_STATE();
3126 }
Eric Laurent81784c32012-11-19 14:55:58 -08003127 mStandby = true;
3128 }
3129
3130 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3131 // we're about to wait, flush the binder command buffer
3132 IPCThreadState::self()->flushCommands();
3133
3134 clearOutputTracks();
3135
3136 if (exitPending()) {
3137 break;
3138 }
3139
3140 releaseWakeLock_l();
3141 // wait until we have something to do...
3142 ALOGV("%s going to sleep", myName.string());
3143 mWaitWorkCV.wait(mLock);
3144 ALOGV("%s waking up", myName.string());
3145 acquireWakeLock_l();
3146
3147 mMixerStatus = MIXER_IDLE;
3148 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3149 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003150 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003151 checkSilentMode_l();
3152
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003153 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3154 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003155 if (mType == MIXER) {
3156 sleepTimeShift = 0;
3157 }
3158
3159 continue;
3160 }
3161 }
Eric Laurent81784c32012-11-19 14:55:58 -08003162 // mMixerStatusIgnoringFastTracks is also updated internally
3163 mMixerStatus = prepareTracks_l(&tracksToRemove);
3164
Andy Hungdae27702016-10-31 14:01:16 -07003165 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003166
Eric Laurent81784c32012-11-19 14:55:58 -08003167 // prevent any changes in effect chain list and in each effect chain
3168 // during mixing and effect process as the audio buffers could be deleted
3169 // or modified if an effect is created or deleted
3170 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003171 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003172
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 if (mBytesRemaining == 0) {
3174 mCurrentWriteLength = 0;
3175 if (mMixerStatus == MIXER_TRACKS_READY) {
3176 // threadLoop_mix() sets mCurrentWriteLength
3177 threadLoop_mix();
3178 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3179 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003180 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003181 // must be written to HAL
3182 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003183 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003184 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003185 }
3186 }
Andy Hung98ef9782014-03-04 14:46:50 -08003187 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003188 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003189 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3190 // or mSinkBuffer (if there are no effects).
3191 //
3192 // This is done pre-effects computation; if effects change to
3193 // support higher precision, this needs to move.
3194 //
3195 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003196 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003197 if (mMixerBufferValid) {
3198 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3199 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3200
Andy Hung2ddee192015-12-18 17:34:44 -08003201 // mono blend occurs for mixer threads only (not direct or offloaded)
3202 // and is handled here if we're going directly to the sink.
3203 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003204 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3205 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003206 }
3207
Andy Hung98ef9782014-03-04 14:46:50 -08003208 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3209 mNormalFrameCount * mChannelCount);
3210 }
3211
Eric Laurentbfb1b832013-01-07 09:53:42 -08003212 mBytesRemaining = mCurrentWriteLength;
3213 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003214 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3215 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3216 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3217 mBytesWritten += mBytesRemaining;
3218 mFramesWritten += framesRemaining;
3219 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003220 mBytesRemaining = 0;
3221 }
Eric Laurent81784c32012-11-19 14:55:58 -08003222
Eric Laurentbfb1b832013-01-07 09:53:42 -08003223 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003224 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003225 for (size_t i = 0; i < effectChains.size(); i ++) {
3226 effectChains[i]->process_l();
3227 }
Eric Laurent81784c32012-11-19 14:55:58 -08003228 }
3229 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003230 // Process effect chains for offloaded thread even if no audio
3231 // was read from audio track: process only updates effect state
3232 // and thus does have to be synchronized with audio writes but may have
3233 // to be called while waiting for async write callback
3234 if (mType == OFFLOAD) {
3235 for (size_t i = 0; i < effectChains.size(); i ++) {
3236 effectChains[i]->process_l();
3237 }
3238 }
Eric Laurent81784c32012-11-19 14:55:58 -08003239
Andy Hung98ef9782014-03-04 14:46:50 -08003240 // Only if the Effects buffer is enabled and there is data in the
3241 // Effects buffer (buffer valid), we need to
3242 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003243 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003244 if (mEffectBufferValid) {
3245 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003246
3247 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003248 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3249 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003250 }
3251
Andy Hung98ef9782014-03-04 14:46:50 -08003252 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3253 mNormalFrameCount * mChannelCount);
3254 }
3255
Eric Laurent81784c32012-11-19 14:55:58 -08003256 // enable changes in effect chain
3257 unlockEffectChains(effectChains);
3258
Eric Laurentbfb1b832013-01-07 09:53:42 -08003259 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003260 // mSleepTimeUs == 0 means we must write to audio hardware
3261 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003262 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003263 // We save lastWriteFinished here, as previousLastWriteFinished,
3264 // for throttling. On thread start, previousLastWriteFinished will be
3265 // set to -1, which properly results in no throttling after the first write.
3266 nsecs_t previousLastWriteFinished = lastWriteFinished;
3267 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003268 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003269 // FIXME rewrite to reduce number of system calls
3270 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003271 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003272 lastWriteFinished = systemTime();
3273 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003274 if (ret < 0) {
3275 mBytesRemaining = 0;
3276 } else {
3277 mBytesWritten += ret;
3278 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003279 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003280 }
3281 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3282 (mMixerStatus == MIXER_DRAIN_ALL)) {
3283 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003284 }
Andy Hung08fb1742015-05-31 23:22:10 -07003285 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003286 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003287 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003288 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003289 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003290 ATRACE_NAME("underrun");
3291 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003292 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003293 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003294 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003295 }
Andy Hung08fb1742015-05-31 23:22:10 -07003296
3297 if (mThreadThrottle
3298 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3299 && ret > 0) { // we wrote something
3300 // Limit MixerThread data processing to no more than twice the
3301 // expected processing rate.
3302 //
3303 // This helps prevent underruns with NuPlayer and other applications
3304 // which may set up buffers that are close to the minimum size, or use
3305 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3306 //
3307 // The throttle smooths out sudden large data drains from the device,
3308 // e.g. when it comes out of standby, which often causes problems with
3309 // (1) mixer threads without a fast mixer (which has its own warm-up)
3310 // (2) minimum buffer sized tracks (even if the track is full,
3311 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003312 //
3313 // Total time spent in last processing cycle equals time spent in
3314 // 1. threadLoop_write, as well as time spent in
3315 // 2. threadLoop_mix (significant for heavy mixing, especially
3316 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003317
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003318 // it's OK if deltaMs (and deltaNs) is an overestimate.
3319 nsecs_t deltaNs;
3320 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3321 __builtin_sub_overflow(
3322 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3323 const int32_t deltaMs = deltaNs / 1000000;
3324
Ivan Lozanoea04d392017-11-07 14:37:07 -08003325 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003326 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3327 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003328 // notify of throttle start on verbose log
3329 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3330 "mixer(%p) throttle begin:"
3331 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003332 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003333 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003334 // Throttle must be attributed to the previous mixer loop's write time
3335 // to allow back-to-back throttling.
3336 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003337 } else {
3338 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3339 if (diff > 0) {
3340 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003341 // but prevent spamming for bluetooth
3342 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3343 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003344 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3345 }
Andy Hung08fb1742015-05-31 23:22:10 -07003346 }
3347 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003348 }
Eric Laurent81784c32012-11-19 14:55:58 -08003349
Eric Laurentbfb1b832013-01-07 09:53:42 -08003350 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003351 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003352 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003353 // suspended requires accurate metering of sleep time.
3354 if (isSuspended()) {
3355 // advance by expected sleepTime
3356 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3357 const nsecs_t nowNs = systemTime();
3358
3359 // compute expected next time vs current time.
3360 // (negative deltas are treated as delays).
3361 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3362 if (deltaNs < -kMaxNextBufferDelayNs) {
3363 // Delays longer than the max allowed trigger a reset.
3364 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3365 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3366 timeLoopNextNs = nowNs + deltaNs;
3367 } else if (deltaNs < 0) {
3368 // Delays within the max delay allowed: zero the delta/sleepTime
3369 // to help the system catch up in the next iteration(s)
3370 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3371 deltaNs = 0;
3372 }
3373 // update sleep time (which is >= 0)
3374 mSleepTimeUs = deltaNs / 1000;
3375 }
Eric Laurente93cc032016-05-05 10:15:10 -07003376 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3377 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003378 }
Glenn Kastene7754022014-10-31 12:11:26 -07003379 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003380 }
Eric Laurent81784c32012-11-19 14:55:58 -08003381 }
3382
3383 // Finally let go of removed track(s), without the lock held
3384 // since we can't guarantee the destructors won't acquire that
3385 // same lock. This will also mutate and push a new fast mixer state.
3386 threadLoop_removeTracks(tracksToRemove);
3387 tracksToRemove.clear();
3388
3389 // FIXME I don't understand the need for this here;
3390 // it was in the original code but maybe the
3391 // assignment in saveOutputTracks() makes this unnecessary?
3392 clearOutputTracks();
3393
3394 // Effect chains will be actually deleted here if they were removed from
3395 // mEffectChains list during mixing or effects processing
3396 effectChains.clear();
3397
3398 // FIXME Note that the above .clear() is no longer necessary since effectChains
3399 // is now local to this block, but will keep it for now (at least until merge done).
3400 }
3401
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402 threadLoop_exit();
3403
Eric Laurentcf817a22014-08-04 20:36:31 -07003404 if (!mStandby) {
3405 threadLoop_standby();
3406 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003407 }
3408
3409 releaseWakeLock();
3410
3411 ALOGV("Thread %p type %d exiting", this, mType);
3412 return false;
3413}
3414
Eric Laurentbfb1b832013-01-07 09:53:42 -08003415// removeTracks_l() must be called with ThreadBase::mLock held
3416void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3417{
3418 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003419 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003420 for (size_t i=0 ; i<count ; i++) {
3421 const sp<Track>& track = tracksToRemove.itemAt(i);
3422 mActiveTracks.remove(track);
3423 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3424 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3425 if (chain != 0) {
3426 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3427 track->sessionId());
3428 chain->decActiveTrackCnt();
3429 }
3430 if (track->isTerminated()) {
3431 removeTrack_l(track);
3432 }
3433 }
3434 }
3435
3436}
Eric Laurent81784c32012-11-19 14:55:58 -08003437
Eric Laurentaccc1472013-09-20 09:36:34 -07003438status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3439{
3440 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003441 ExtendedTimestamp ets;
3442 status_t status = mNormalSink->getTimestamp(ets);
3443 if (status == NO_ERROR) {
3444 status = ets.getBestTimestamp(&timestamp);
3445 }
3446 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003447 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003448 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003449 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003450 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003451 timestamp.mPosition = (uint32_t)position64;
3452 return NO_ERROR;
3453 }
3454 }
3455 return INVALID_OPERATION;
3456}
Eric Laurent1c333e22014-05-20 10:48:17 -07003457
Eric Laurent054d9d32015-04-24 08:48:48 -07003458status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3459 audio_patch_handle_t *handle)
3460{
Andy Hungf60abce2016-08-26 11:37:54 -07003461 status_t status;
3462 if (property_get_bool("af.patch_park", false /* default_value */)) {
3463 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3464 // or if HAL does not properly lock against access.
3465 AutoPark<FastMixer> park(mFastMixer);
3466 status = PlaybackThread::createAudioPatch_l(patch, handle);
3467 } else {
3468 status = PlaybackThread::createAudioPatch_l(patch, handle);
3469 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003470 return status;
3471}
3472
Eric Laurent1c333e22014-05-20 10:48:17 -07003473status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3474 audio_patch_handle_t *handle)
3475{
3476 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003477
3478 // store new device and send to effects
3479 audio_devices_t type = AUDIO_DEVICE_NONE;
3480 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3481 type |= patch->sinks[i].ext.device.type;
3482 }
3483
3484#ifdef ADD_BATTERY_DATA
3485 // when changing the audio output device, call addBatteryData to notify
3486 // the change
3487 if (mOutDevice != type) {
3488 uint32_t params = 0;
3489 // check whether speaker is on
3490 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3491 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003492 }
3493
Eric Laurent054d9d32015-04-24 08:48:48 -07003494 audio_devices_t deviceWithoutSpeaker
3495 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3496 // check if any other device (except speaker) is on
3497 if (type & deviceWithoutSpeaker) {
3498 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3499 }
3500
3501 if (params != 0) {
3502 addBatteryData(params);
3503 }
3504 }
3505#endif
3506
3507 for (size_t i = 0; i < mEffectChains.size(); i++) {
3508 mEffectChains[i]->setDevice_l(type);
3509 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003510
3511 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3512 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3513 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003514 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003515 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003516
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003517 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003518 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3519 status = hwDevice->createAudioPatch(patch->num_sources,
3520 patch->sources,
3521 patch->num_sinks,
3522 patch->sinks,
3523 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003524 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003525 char *address;
3526 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3527 //FIXME: we only support address on first sink with HAL version < 3.0
3528 address = audio_device_address_to_parameter(
3529 patch->sinks[0].ext.device.type,
3530 patch->sinks[0].ext.device.address);
3531 } else {
3532 address = (char *)calloc(1, 1);
3533 }
3534 AudioParameter param = AudioParameter(String8(address));
3535 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003536 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003537 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003538 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003539 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003540 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003541 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003542 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3543 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003544 return status;
3545}
3546
Eric Laurent054d9d32015-04-24 08:48:48 -07003547status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3548{
Andy Hungf60abce2016-08-26 11:37:54 -07003549 status_t status;
3550 if (property_get_bool("af.patch_park", false /* default_value */)) {
3551 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3552 // or if HAL does not properly lock against access.
3553 AutoPark<FastMixer> park(mFastMixer);
3554 status = PlaybackThread::releaseAudioPatch_l(handle);
3555 } else {
3556 status = PlaybackThread::releaseAudioPatch_l(handle);
3557 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003558 return status;
3559}
3560
Eric Laurent1c333e22014-05-20 10:48:17 -07003561status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3562{
3563 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003564
3565 mOutDevice = AUDIO_DEVICE_NONE;
3566
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003567 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003568 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3569 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003570 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003571 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003572 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003573 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003574 }
3575 return status;
3576}
3577
Eric Laurent83b88082014-06-20 18:31:16 -07003578void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3579{
3580 Mutex::Autolock _l(mLock);
3581 mTracks.add(track);
3582}
3583
3584void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3585{
3586 Mutex::Autolock _l(mLock);
3587 destroyTrack_l(track);
3588}
3589
3590void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3591{
3592 ThreadBase::getAudioPortConfig(config);
3593 config->role = AUDIO_PORT_ROLE_SOURCE;
3594 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3595 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3596}
3597
Eric Laurent81784c32012-11-19 14:55:58 -08003598// ----------------------------------------------------------------------------
3599
3600AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003601 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3602 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003603 // mAudioMixer below
3604 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003605 mFastMixerFutex(0),
3606 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003607 // mOutputSink below
3608 // mPipeSink below
3609 // mNormalSink below
3610{
3611 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003612 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3613 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003614 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3615 mNormalFrameCount);
3616 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3617
Andy Hungfbfc3952015-01-15 13:33:51 -08003618 if (type == DUPLICATING) {
3619 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3620 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3621 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3622 return;
3623 }
Eric Laurent81784c32012-11-19 14:55:58 -08003624 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003625 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003626 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003627 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003628#if !LOG_NDEBUG
3629 ssize_t index =
3630#else
3631 (void)
3632#endif
3633 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003634 ALOG_ASSERT(index == 0);
3635
3636 // initialize fast mixer depending on configuration
3637 bool initFastMixer;
3638 switch (kUseFastMixer) {
3639 case FastMixer_Never:
3640 initFastMixer = false;
3641 break;
3642 case FastMixer_Always:
3643 initFastMixer = true;
3644 break;
3645 case FastMixer_Static:
3646 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003647 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3648 // where the period is less than an experimentally determined threshold that can be
3649 // scheduled reliably with CFS. However, the BT A2DP HAL is
3650 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3651 initFastMixer = mFrameCount < mNormalFrameCount
3652 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003653 break;
3654 }
Andy Hungfda69402017-02-15 14:33:12 -08003655 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3656 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3657 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003658 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003659 audio_format_t fastMixerFormat;
3660 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3661 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3662 } else {
3663 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3664 }
3665 if (mFormat != fastMixerFormat) {
3666 // change our Sink format to accept our intermediate precision
3667 mFormat = fastMixerFormat;
3668 free(mSinkBuffer);
3669 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3670 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3671 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3672 }
Eric Laurent81784c32012-11-19 14:55:58 -08003673
3674 // create a MonoPipe to connect our submix to FastMixer
3675 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003676#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003677 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003678#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003679 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003680 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003681 format.mFormat = fastMixerFormat;
3682 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3683
Eric Laurent81784c32012-11-19 14:55:58 -08003684 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3685 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3686 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3687 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3688 const NBAIO_Format offers[1] = {format};
3689 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003690#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003691 ssize_t index =
3692#else
3693 (void)
3694#endif
3695 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003696 ALOG_ASSERT(index == 0);
3697 monoPipe->setAvgFrames((mScreenState & 1) ?
3698 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3699 mPipeSink = monoPipe;
3700
Glenn Kasten46909e72013-02-26 09:20:22 -08003701#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003702 if (mTeeSinkOutputEnabled) {
3703 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003704 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3705 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003706 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003707 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003708 ALOG_ASSERT(index == 0);
3709 mTeeSink = teeSink;
3710 PipeReader *teeSource = new PipeReader(*teeSink);
3711 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003712 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003713 ALOG_ASSERT(index == 0);
3714 mTeeSource = teeSource;
3715 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003716#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003717
3718 // create fast mixer and configure it initially with just one fast track for our submix
3719 mFastMixer = new FastMixer();
3720 FastMixerStateQueue *sq = mFastMixer->sq();
3721#ifdef STATE_QUEUE_DUMP
3722 sq->setObserverDump(&mStateQueueObserverDump);
3723 sq->setMutatorDump(&mStateQueueMutatorDump);
3724#endif
3725 FastMixerState *state = sq->begin();
3726 FastTrack *fastTrack = &state->mFastTracks[0];
3727 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3728 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3729 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003730 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3731 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003732 fastTrack->mGeneration++;
3733 state->mFastTracksGen++;
3734 state->mTrackMask = 1;
3735 // fast mixer will use the HAL output sink
3736 state->mOutputSink = mOutputSink.get();
3737 state->mOutputSinkGen++;
3738 state->mFrameCount = mFrameCount;
3739 state->mCommand = FastMixerState::COLD_IDLE;
3740 // already done in constructor initialization list
3741 //mFastMixerFutex = 0;
3742 state->mColdFutexAddr = &mFastMixerFutex;
3743 state->mColdGen++;
3744 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003745#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003746 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003747#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003748 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3749 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003750 sq->end();
3751 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3752
3753 // start the fast mixer
3754 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3755 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003756 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003757 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003758
3759#ifdef AUDIO_WATCHDOG
3760 // create and start the watchdog
3761 mAudioWatchdog = new AudioWatchdog();
3762 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3763 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3764 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003765 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003766#endif
3767
Eric Laurent81784c32012-11-19 14:55:58 -08003768 }
3769
3770 switch (kUseFastMixer) {
3771 case FastMixer_Never:
3772 case FastMixer_Dynamic:
3773 mNormalSink = mOutputSink;
3774 break;
3775 case FastMixer_Always:
3776 mNormalSink = mPipeSink;
3777 break;
3778 case FastMixer_Static:
3779 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3780 break;
3781 }
3782}
3783
3784AudioFlinger::MixerThread::~MixerThread()
3785{
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::COLD_IDLE) {
3790 int32_t old = android_atomic_inc(&mFastMixerFutex);
3791 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003792 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003793 }
3794 }
3795 state->mCommand = FastMixerState::EXIT;
3796 sq->end();
3797 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3798 mFastMixer->join();
3799 // Though the fast mixer thread has exited, it's state queue is still valid.
3800 // We'll use that extract the final state which contains one remaining fast track
3801 // corresponding to our sub-mix.
3802 state = sq->begin();
3803 ALOG_ASSERT(state->mTrackMask == 1);
3804 FastTrack *fastTrack = &state->mFastTracks[0];
3805 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3806 delete fastTrack->mBufferProvider;
3807 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003808 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003809#ifdef AUDIO_WATCHDOG
3810 if (mAudioWatchdog != 0) {
3811 mAudioWatchdog->requestExit();
3812 mAudioWatchdog->requestExitAndWait();
3813 mAudioWatchdog.clear();
3814 }
3815#endif
3816 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003817 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003818 delete mAudioMixer;
3819}
3820
3821
3822uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3823{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003824 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003825 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3826 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3827 }
3828 return latency;
3829}
3830
3831
3832void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3833{
3834 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3835}
3836
Eric Laurentbfb1b832013-01-07 09:53:42 -08003837ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003838{
3839 // FIXME we should only do one push per cycle; confirm this is true
3840 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003841 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003842 FastMixerStateQueue *sq = mFastMixer->sq();
3843 FastMixerState *state = sq->begin();
3844 if (state->mCommand != FastMixerState::MIX_WRITE &&
3845 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3846 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003847
3848 // FIXME workaround for first HAL write being CPU bound on some devices
3849 ATRACE_BEGIN("write");
3850 mOutput->write((char *)mSinkBuffer, 0);
3851 ATRACE_END();
3852
Eric Laurent81784c32012-11-19 14:55:58 -08003853 int32_t old = android_atomic_inc(&mFastMixerFutex);
3854 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003855 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003856 }
3857#ifdef AUDIO_WATCHDOG
3858 if (mAudioWatchdog != 0) {
3859 mAudioWatchdog->resume();
3860 }
3861#endif
3862 }
3863 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003864#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003865 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003866 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003867#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003868 sq->end();
3869 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3870 if (kUseFastMixer == FastMixer_Dynamic) {
3871 mNormalSink = mPipeSink;
3872 }
3873 } else {
3874 sq->end(false /*didModify*/);
3875 }
3876 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003877 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003878}
3879
3880void AudioFlinger::MixerThread::threadLoop_standby()
3881{
3882 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003883 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003884 FastMixerStateQueue *sq = mFastMixer->sq();
3885 FastMixerState *state = sq->begin();
3886 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003887 // Report any frames trapped in the Monopipe
3888 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3889 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3890 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3891 "monoPipeWritten:%lld monoPipeLeft:%lld",
3892 (long long)mFramesWritten, (long long)mSuspendedFrames,
3893 (long long)mPipeSink->framesWritten(), pipeFrames);
3894 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3895
Eric Laurent81784c32012-11-19 14:55:58 -08003896 state->mCommand = FastMixerState::COLD_IDLE;
3897 state->mColdFutexAddr = &mFastMixerFutex;
3898 state->mColdGen++;
3899 mFastMixerFutex = 0;
3900 sq->end();
3901 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3902 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3903 if (kUseFastMixer == FastMixer_Dynamic) {
3904 mNormalSink = mOutputSink;
3905 }
3906#ifdef AUDIO_WATCHDOG
3907 if (mAudioWatchdog != 0) {
3908 mAudioWatchdog->pause();
3909 }
3910#endif
3911 } else {
3912 sq->end(false /*didModify*/);
3913 }
3914 }
3915 PlaybackThread::threadLoop_standby();
3916}
3917
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3919{
3920 return false;
3921}
3922
3923bool AudioFlinger::PlaybackThread::shouldStandby_l()
3924{
3925 return !mStandby;
3926}
3927
3928bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3929{
3930 Mutex::Autolock _l(mLock);
3931 return waitingAsyncCallback_l();
3932}
3933
Eric Laurent81784c32012-11-19 14:55:58 -08003934// shared by MIXER and DIRECT, overridden by DUPLICATING
3935void AudioFlinger::PlaybackThread::threadLoop_standby()
3936{
3937 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003938 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003939 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003940 // discard any pending drain or write ack by incrementing sequence
3941 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3942 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003943 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003944 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3945 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003946 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003947 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003948}
3949
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003950void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3951{
3952 ALOGV("signal playback thread");
3953 broadcast_l();
3954}
3955
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003956void AudioFlinger::PlaybackThread::onAsyncError()
3957{
3958 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3959 invalidateTracks((audio_stream_type_t)i);
3960 }
3961}
3962
Eric Laurent81784c32012-11-19 14:55:58 -08003963void AudioFlinger::MixerThread::threadLoop_mix()
3964{
Eric Laurent81784c32012-11-19 14:55:58 -08003965 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003966 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003967 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003968 // increase sleep time progressively when application underrun condition clears.
3969 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3970 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3971 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003972 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003973 sleepTimeShift--;
3974 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003975 mSleepTimeUs = 0;
3976 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003977 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003978
Eric Laurent81784c32012-11-19 14:55:58 -08003979}
3980
3981void AudioFlinger::MixerThread::threadLoop_sleepTime()
3982{
3983 // If no tracks are ready, sleep once for the duration of an output
3984 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003985 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003986 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003987 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3988 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3989 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003990 }
3991 // reduce sleep time in case of consecutive application underruns to avoid
3992 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3993 // duration we would end up writing less data than needed by the audio HAL if
3994 // the condition persists.
3995 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3996 sleepTimeShift++;
3997 }
3998 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003999 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004000 }
4001 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004002 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4003 // before effects processing or output.
4004 if (mMixerBufferValid) {
4005 memset(mMixerBuffer, 0, mMixerBufferSize);
4006 } else {
4007 memset(mSinkBuffer, 0, mSinkBufferSize);
4008 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004009 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004010 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4011 "anticipated start");
4012 }
4013 // TODO add standby time extension fct of effect tail
4014}
4015
4016// prepareTracks_l() must be called with ThreadBase::mLock held
4017AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4018 Vector< sp<Track> > *tracksToRemove)
4019{
4020
4021 mixer_state mixerStatus = MIXER_IDLE;
4022 // find out which tracks need to be processed
4023 size_t count = mActiveTracks.size();
4024 size_t mixedTracks = 0;
4025 size_t tracksWithEffect = 0;
4026 // counts only _active_ fast tracks
4027 size_t fastTracks = 0;
4028 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4029
4030 float masterVolume = mMasterVolume;
4031 bool masterMute = mMasterMute;
4032
4033 if (masterMute) {
4034 masterVolume = 0;
4035 }
4036 // Delegate master volume control to effect in output mix effect chain if needed
4037 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4038 if (chain != 0) {
4039 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4040 chain->setVolume_l(&v, &v);
4041 masterVolume = (float)((v + (1 << 23)) >> 24);
4042 chain.clear();
4043 }
4044
4045 // prepare a new state to push
4046 FastMixerStateQueue *sq = NULL;
4047 FastMixerState *state = NULL;
4048 bool didModify = false;
4049 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004050 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004051 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004052 sq = mFastMixer->sq();
4053 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004054 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004055 }
4056
Andy Hung69aed5f2014-02-25 17:24:40 -08004057 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004058 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004059
Eric Laurent81784c32012-11-19 14:55:58 -08004060 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004061 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004062
4063 // this const just means the local variable doesn't change
4064 Track* const track = t.get();
4065
4066 // process fast tracks
4067 if (track->isFastTrack()) {
4068
4069 // It's theoretically possible (though unlikely) for a fast track to be created
4070 // and then removed within the same normal mix cycle. This is not a problem, as
4071 // the track never becomes active so it's fast mixer slot is never touched.
4072 // The converse, of removing an (active) track and then creating a new track
4073 // at the identical fast mixer slot within the same normal mix cycle,
4074 // is impossible because the slot isn't marked available until the end of each cycle.
4075 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004076 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004077 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4078 FastTrack *fastTrack = &state->mFastTracks[j];
4079
4080 // Determine whether the track is currently in underrun condition,
4081 // and whether it had a recent underrun.
4082 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4083 FastTrackUnderruns underruns = ftDump->mUnderruns;
4084 uint32_t recentFull = (underruns.mBitFields.mFull -
4085 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4086 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4087 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4088 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4089 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4090 uint32_t recentUnderruns = recentPartial + recentEmpty;
4091 track->mObservedUnderruns = underruns;
4092 // don't count underruns that occur while stopping or pausing
4093 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004094 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4095 recentUnderruns > 0) {
4096 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4097 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004098 } else {
4099 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004100 }
4101
4102 // This is similar to the state machine for normal tracks,
4103 // with a few modifications for fast tracks.
4104 bool isActive = true;
4105 switch (track->mState) {
4106 case TrackBase::STOPPING_1:
4107 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004109 track->mState = TrackBase::STOPPING_2;
4110 }
4111 break;
4112 case TrackBase::PAUSING:
4113 // ramp down is not yet implemented
4114 track->setPaused();
4115 break;
4116 case TrackBase::RESUMING:
4117 // ramp up is not yet implemented
4118 track->mState = TrackBase::ACTIVE;
4119 break;
4120 case TrackBase::ACTIVE:
4121 if (recentFull > 0 || recentPartial > 0) {
4122 // track has provided at least some frames recently: reset retry count
4123 track->mRetryCount = kMaxTrackRetries;
4124 }
4125 if (recentUnderruns == 0) {
4126 // no recent underruns: stay active
4127 break;
4128 }
4129 // there has recently been an underrun of some kind
4130 if (track->sharedBuffer() == 0) {
4131 // were any of the recent underruns "empty" (no frames available)?
4132 if (recentEmpty == 0) {
4133 // no, then ignore the partial underruns as they are allowed indefinitely
4134 break;
4135 }
4136 // there has recently been an "empty" underrun: decrement the retry counter
4137 if (--(track->mRetryCount) > 0) {
4138 break;
4139 }
4140 // indicate to client process that the track was disabled because of underrun;
4141 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004142 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004143 // remove from active list, but state remains ACTIVE [confusing but true]
4144 isActive = false;
4145 break;
4146 }
4147 // fall through
4148 case TrackBase::STOPPING_2:
4149 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004150 case TrackBase::STOPPED:
4151 case TrackBase::FLUSHED: // flush() while active
4152 // Check for presentation complete if track is inactive
4153 // We have consumed all the buffers of this track.
4154 // This would be incomplete if we auto-paused on underrun
4155 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004156 uint32_t latency = 0;
4157 status_t result = mOutput->stream->getLatency(&latency);
4158 ALOGE_IF(result != OK,
4159 "Error when retrieving output stream latency: %d", result);
4160 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004161 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004162 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4163 // track stays in active list until presentation is complete
4164 break;
4165 }
4166 }
4167 if (track->isStopping_2()) {
4168 track->mState = TrackBase::STOPPED;
4169 }
4170 if (track->isStopped()) {
4171 // Can't reset directly, as fast mixer is still polling this track
4172 // track->reset();
4173 // So instead mark this track as needing to be reset after push with ack
4174 resetMask |= 1 << i;
4175 }
4176 isActive = false;
4177 break;
4178 case TrackBase::IDLE:
4179 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004180 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004181 }
4182
4183 if (isActive) {
4184 // was it previously inactive?
4185 if (!(state->mTrackMask & (1 << j))) {
4186 ExtendedAudioBufferProvider *eabp = track;
4187 VolumeProvider *vp = track;
4188 fastTrack->mBufferProvider = eabp;
4189 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004190 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004191 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004192 fastTrack->mGeneration++;
4193 state->mTrackMask |= 1 << j;
4194 didModify = true;
4195 // no acknowledgement required for newly active tracks
4196 }
4197 // cache the combined master volume and stream type volume for fast mixer; this
4198 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004199 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004200 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004201 track->mCachedVolume = masterVolume
4202 * mStreamTypes[track->streamType()].volume
4203 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004204 ++fastTracks;
4205 } else {
4206 // was it previously active?
4207 if (state->mTrackMask & (1 << j)) {
4208 fastTrack->mBufferProvider = NULL;
4209 fastTrack->mGeneration++;
4210 state->mTrackMask &= ~(1 << j);
4211 didModify = true;
4212 // If any fast tracks were removed, we must wait for acknowledgement
4213 // because we're about to decrement the last sp<> on those tracks.
4214 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4215 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004216 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4217 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4218 j, track->mState, state->mTrackMask, recentUnderruns,
4219 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004220 }
4221 tracksToRemove->add(track);
4222 // Avoids a misleading display in dumpsys
4223 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4224 }
4225 continue;
4226 }
4227
4228 { // local variable scope to avoid goto warning
4229
4230 audio_track_cblk_t* cblk = track->cblk();
4231
4232 // The first time a track is added we wait
4233 // for all its buffers to be filled before processing it
4234 int name = track->name();
4235 // make sure that we have enough frames to mix one full buffer.
4236 // enforce this condition only once to enable draining the buffer in case the client
4237 // app does not call stop() and relies on underrun to stop:
4238 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4239 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004240 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004241 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004242 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004243
4244 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004245 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004246 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4247 // add frames already consumed but not yet released by the resampler
4248 // because mAudioTrackServerProxy->framesReady() will include these frames
4249 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4250
Eric Laurent81784c32012-11-19 14:55:58 -08004251 uint32_t minFrames = 1;
4252 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4253 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004254 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004255 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004256
4257 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004258 if (ATRACE_ENABLED()) {
4259 // I wish we had formatted trace names
4260 char traceName[16];
4261 strcpy(traceName, "nRdy");
4262 int name = track->name();
4263 if (AudioMixer::TRACK0 <= name &&
4264 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4265 name -= AudioMixer::TRACK0;
4266 traceName[4] = (name / 10) + '0';
4267 traceName[5] = (name % 10) + '0';
4268 } else {
4269 traceName[4] = '?';
4270 traceName[5] = '?';
4271 }
4272 traceName[6] = '\0';
4273 ATRACE_INT(traceName, framesReady);
4274 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004275 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004276 !track->isPaused() && !track->isTerminated())
4277 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004278 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004279
4280 mixedTracks++;
4281
Andy Hung69aed5f2014-02-25 17:24:40 -08004282 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4283 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004284 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004285 if (track->mainBuffer() != mSinkBuffer &&
4286 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004287 if (mEffectBufferEnabled) {
4288 mEffectBufferValid = true; // Later can set directly.
4289 }
Eric Laurent81784c32012-11-19 14:55:58 -08004290 chain = getEffectChain_l(track->sessionId());
4291 // Delegate volume control to effect in track effect chain if needed
4292 if (chain != 0) {
4293 tracksWithEffect++;
4294 } else {
4295 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4296 "session %d",
4297 name, track->sessionId());
4298 }
4299 }
4300
4301
4302 int param = AudioMixer::VOLUME;
4303 if (track->mFillingUpStatus == Track::FS_FILLED) {
4304 // no ramp for the first volume setting
4305 track->mFillingUpStatus = Track::FS_ACTIVE;
4306 if (track->mState == TrackBase::RESUMING) {
4307 track->mState = TrackBase::ACTIVE;
4308 param = AudioMixer::RAMP_VOLUME;
4309 }
4310 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004311 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004312 // FIXME should not make a decision based on mServer
4313 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004314 // If the track is stopped before the first frame was mixed,
4315 // do not apply ramp
4316 param = AudioMixer::RAMP_VOLUME;
4317 }
4318
4319 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004320 uint32_t vl, vr; // in U8.24 integer format
4321 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004322 // read original volumes with volume control
4323 float typeVolume = mStreamTypes[track->streamType()].volume;
4324 float v = masterVolume * typeVolume;
4325
Glenn Kastene4756fe2012-11-29 13:38:14 -08004326 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004327 vl = vr = 0;
4328 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004329 if (track->isPausing()) {
4330 track->setPaused();
4331 }
4332 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004333 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004334 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004335 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4336 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004337 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004338 if (vlf > GAIN_FLOAT_UNITY) {
4339 ALOGV("Track left volume out of range: %.3g", vlf);
4340 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004341 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004342 if (vrf > GAIN_FLOAT_UNITY) {
4343 ALOGV("Track right volume out of range: %.3g", vrf);
4344 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004345 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004346 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004347 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004348 // now apply the master volume and stream type volume and shaper volume
4349 vlf *= v * vh;
4350 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004351 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004352 // then derive vl and vr as U8.24 versions for the effect chain
4353 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4354 vl = (uint32_t) (scaleto8_24 * vlf);
4355 vr = (uint32_t) (scaleto8_24 * vrf);
4356 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004357 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004358 // send level comes from shared memory and so may be corrupt
4359 if (sendLevel > MAX_GAIN_INT) {
4360 ALOGV("Track send level out of range: %04X", sendLevel);
4361 sendLevel = MAX_GAIN_INT;
4362 }
Andy Hung6be49402014-05-30 10:42:03 -07004363 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4364 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004365 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004366
Eric Laurent81784c32012-11-19 14:55:58 -08004367 // Delegate volume control to effect in track effect chain if needed
4368 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4369 // Do not ramp volume if volume is controlled by effect
4370 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004371 // Update remaining floating point volume levels
4372 vlf = (float)vl / (1 << 24);
4373 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004374 track->mHasVolumeController = true;
4375 } else {
4376 // force no volume ramp when volume controller was just disabled or removed
4377 // from effect chain to avoid volume spike
4378 if (track->mHasVolumeController) {
4379 param = AudioMixer::VOLUME;
4380 }
4381 track->mHasVolumeController = false;
4382 }
4383
Eric Laurent7c29ec92017-09-20 17:54:22 -07004384 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4385 // still applied by the mixer.
4386 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4387 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4388 if (v != mLeftVolFloat) {
4389 status_t result = mOutput->stream->setVolume(v, v);
4390 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4391 if (result == OK) {
4392 mLeftVolFloat = v;
4393 }
4394 }
4395 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4396 // remove stream volume contribution from software volume.
4397 if (v != 0.0f && mLeftVolFloat == v) {
4398 vlf = min(1.0f, vlf / v);
4399 vrf = min(1.0f, vrf / v);
4400 vaf = min(1.0f, vaf / v);
4401 }
4402 }
Eric Laurent81784c32012-11-19 14:55:58 -08004403 // XXX: these things DON'T need to be done each time
4404 mAudioMixer->setBufferProvider(name, track);
4405 mAudioMixer->enable(name);
4406
Andy Hung6be49402014-05-30 10:42:03 -07004407 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4408 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4409 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004410 mAudioMixer->setParameter(
4411 name,
4412 AudioMixer::TRACK,
4413 AudioMixer::FORMAT, (void *)track->format());
4414 mAudioMixer->setParameter(
4415 name,
4416 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004417 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004418 mAudioMixer->setParameter(
4419 name,
4420 AudioMixer::TRACK,
4421 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004422 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004423 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004424 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004425 if (reqSampleRate == 0) {
4426 reqSampleRate = mSampleRate;
4427 } else if (reqSampleRate > maxSampleRate) {
4428 reqSampleRate = maxSampleRate;
4429 }
Eric Laurent81784c32012-11-19 14:55:58 -08004430 mAudioMixer->setParameter(
4431 name,
4432 AudioMixer::RESAMPLE,
4433 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004434 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004435
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004436 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004437 mAudioMixer->setParameter(
4438 name,
4439 AudioMixer::TIMESTRETCH,
4440 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004441 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004442
Andy Hung69aed5f2014-02-25 17:24:40 -08004443 /*
4444 * Select the appropriate output buffer for the track.
4445 *
Andy Hung98ef9782014-03-04 14:46:50 -08004446 * Tracks with effects go into their own effects chain buffer
4447 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004448 *
4449 * Other tracks can use mMixerBuffer for higher precision
4450 * channel accumulation. If this buffer is enabled
4451 * (mMixerBufferEnabled true), then selected tracks will accumulate
4452 * into it.
4453 *
4454 */
4455 if (mMixerBufferEnabled
4456 && (track->mainBuffer() == mSinkBuffer
4457 || track->mainBuffer() == mMixerBuffer)) {
4458 mAudioMixer->setParameter(
4459 name,
4460 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004461 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004462 mAudioMixer->setParameter(
4463 name,
4464 AudioMixer::TRACK,
4465 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4466 // TODO: override track->mainBuffer()?
4467 mMixerBufferValid = true;
4468 } else {
4469 mAudioMixer->setParameter(
4470 name,
4471 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004472 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004473 mAudioMixer->setParameter(
4474 name,
4475 AudioMixer::TRACK,
4476 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4477 }
Eric Laurent81784c32012-11-19 14:55:58 -08004478 mAudioMixer->setParameter(
4479 name,
4480 AudioMixer::TRACK,
4481 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4482
4483 // reset retry count
4484 track->mRetryCount = kMaxTrackRetries;
4485
4486 // If one track is ready, set the mixer ready if:
4487 // - the mixer was not ready during previous round OR
4488 // - no other track is not ready
4489 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4490 mixerStatus != MIXER_TRACKS_ENABLED) {
4491 mixerStatus = MIXER_TRACKS_READY;
4492 }
4493 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004494 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004495 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4496 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004497 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004498 } else {
4499 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004500 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004501
Eric Laurent81784c32012-11-19 14:55:58 -08004502 // clear effect chain input buffer if an active track underruns to avoid sending
4503 // previous audio buffer again to effects
4504 chain = getEffectChain_l(track->sessionId());
4505 if (chain != 0) {
4506 chain->clearInputBuffer();
4507 }
4508
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004509 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004510 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4511 track->isStopped() || track->isPaused()) {
4512 // We have consumed all the buffers of this track.
4513 // Remove it from the list of active tracks.
4514 // TODO: use actual buffer filling status instead of latency when available from
4515 // audio HAL
4516 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004517 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004518 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4519 if (track->isStopped()) {
4520 track->reset();
4521 }
4522 tracksToRemove->add(track);
4523 }
4524 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004525 // No buffers for this track. Give it a few chances to
4526 // fill a buffer, then remove it from active list.
4527 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004528 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004529 tracksToRemove->add(track);
4530 // indicate to client process that the track was disabled because of underrun;
4531 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004532 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004533 // If one track is not ready, mark the mixer also not ready if:
4534 // - the mixer was ready during previous round OR
4535 // - no other track is ready
4536 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4537 mixerStatus != MIXER_TRACKS_READY) {
4538 mixerStatus = MIXER_TRACKS_ENABLED;
4539 }
4540 }
4541 mAudioMixer->disable(name);
4542 }
4543
4544 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004545
4546 }
4547
4548 // Push the new FastMixer state if necessary
4549 bool pauseAudioWatchdog = false;
4550 if (didModify) {
4551 state->mFastTracksGen++;
4552 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4553 if (kUseFastMixer == FastMixer_Dynamic &&
4554 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4555 state->mCommand = FastMixerState::COLD_IDLE;
4556 state->mColdFutexAddr = &mFastMixerFutex;
4557 state->mColdGen++;
4558 mFastMixerFutex = 0;
4559 if (kUseFastMixer == FastMixer_Dynamic) {
4560 mNormalSink = mOutputSink;
4561 }
4562 // If we go into cold idle, need to wait for acknowledgement
4563 // so that fast mixer stops doing I/O.
4564 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4565 pauseAudioWatchdog = true;
4566 }
Eric Laurent81784c32012-11-19 14:55:58 -08004567 }
4568 if (sq != NULL) {
4569 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004570 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4571 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4572 // when bringing the output sink into standby.)
4573 //
4574 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4575 //
4576 // This occurs with BT suspend when we idle the FastMixer with
4577 // active tracks, which may be added or removed.
4578 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004579 }
4580#ifdef AUDIO_WATCHDOG
4581 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4582 mAudioWatchdog->pause();
4583 }
4584#endif
4585
4586 // Now perform the deferred reset on fast tracks that have stopped
4587 while (resetMask != 0) {
4588 size_t i = __builtin_ctz(resetMask);
4589 ALOG_ASSERT(i < count);
4590 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004591 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004592 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4593 track->reset();
4594 }
4595
4596 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004597 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004598
Eric Laurent97d547d2014-09-02 14:45:53 -07004599 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4600 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004601 }
4602
4603 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004604 // as long as there are effects we should clear the effects buffer, to avoid
4605 // passing a non-clean buffer to the effect chain
4606 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004607 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004608 // sink or mix buffer must be cleared if all tracks are connected to an
4609 // effect chain as in this case the mixer will not write to the sink or mix buffer
4610 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004611 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4612 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004613 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004614 if (mMixerBufferValid) {
4615 memset(mMixerBuffer, 0, mMixerBufferSize);
4616 // TODO: In testing, mSinkBuffer below need not be cleared because
4617 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4618 // after mixing.
4619 //
4620 // To enforce this guarantee:
4621 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4622 // (mixedTracks == 0 && fastTracks > 0))
4623 // must imply MIXER_TRACKS_READY.
4624 // Later, we may clear buffers regardless, and skip much of this logic.
4625 }
Andy Hung98ef9782014-03-04 14:46:50 -08004626 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004627 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004628 }
4629
4630 // if any fast tracks, then status is ready
4631 mMixerStatusIgnoringFastTracks = mixerStatus;
4632 if (fastTracks > 0) {
4633 mixerStatus = MIXER_TRACKS_READY;
4634 }
4635 return mixerStatus;
4636}
4637
Eric Laurentad7dd962016-09-22 12:38:37 -07004638// trackCountForUid_l() must be called with ThreadBase::mLock held
4639uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4640{
4641 uint32_t trackCount = 0;
4642 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004643 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004644 trackCount++;
4645 }
4646 }
4647 return trackCount;
4648}
4649
Eric Laurent81784c32012-11-19 14:55:58 -08004650// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004651int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004652 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004653{
Eric Laurentad7dd962016-09-22 12:38:37 -07004654 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4655 return -1;
4656 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004657 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004658}
4659
4660// deleteTrackName_l() must be called with ThreadBase::mLock held
4661void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4662{
4663 ALOGV("remove track (%d) and delete from mixer", name);
4664 mAudioMixer->deleteTrackName(name);
4665}
4666
Eric Laurent10351942014-05-08 18:49:52 -07004667// checkForNewParameter_l() must be called with ThreadBase::mLock held
4668bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4669 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004670{
Eric Laurent81784c32012-11-19 14:55:58 -08004671 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004672 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004673
Eric Laurent10351942014-05-08 18:49:52 -07004674 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004675
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004676 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004677
Eric Laurent10351942014-05-08 18:49:52 -07004678 AudioParameter param = AudioParameter(keyValuePair);
4679 int value;
4680 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4681 reconfig = true;
4682 }
4683 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004684 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004685 status = BAD_VALUE;
4686 } else {
4687 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004688 reconfig = true;
4689 }
Eric Laurent10351942014-05-08 18:49:52 -07004690 }
4691 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004692 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004693 status = BAD_VALUE;
4694 } else {
4695 // no need to save value, since it's constant
4696 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004697 }
Eric Laurent10351942014-05-08 18:49:52 -07004698 }
4699 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4700 // do not accept frame count changes if tracks are open as the track buffer
4701 // size depends on frame count and correct behavior would not be guaranteed
4702 // if frame count is changed after track creation
4703 if (!mTracks.isEmpty()) {
4704 status = INVALID_OPERATION;
4705 } else {
4706 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004707 }
Eric Laurent10351942014-05-08 18:49:52 -07004708 }
4709 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004710#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004711 // when changing the audio output device, call addBatteryData to notify
4712 // the change
4713 if (mOutDevice != value) {
4714 uint32_t params = 0;
4715 // check whether speaker is on
4716 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4717 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004718 }
Eric Laurent10351942014-05-08 18:49:52 -07004719
4720 audio_devices_t deviceWithoutSpeaker
4721 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4722 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004723 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004724 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4725 }
4726
4727 if (params != 0) {
4728 addBatteryData(params);
4729 }
4730 }
Eric Laurent81784c32012-11-19 14:55:58 -08004731#endif
4732
Eric Laurent10351942014-05-08 18:49:52 -07004733 // forward device change to effects that have requested to be
4734 // aware of attached audio device.
4735 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004736 a2dpDeviceChanged =
4737 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004738 mOutDevice = value;
4739 for (size_t i = 0; i < mEffectChains.size(); i++) {
4740 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004741 }
4742 }
Eric Laurent10351942014-05-08 18:49:52 -07004743 }
Eric Laurent81784c32012-11-19 14:55:58 -08004744
Eric Laurent10351942014-05-08 18:49:52 -07004745 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004746 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004747 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004748 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004749 mStandby = true;
4750 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004751 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004752 }
Eric Laurent10351942014-05-08 18:49:52 -07004753 if (status == NO_ERROR && reconfig) {
4754 readOutputParameters_l();
4755 delete mAudioMixer;
4756 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4757 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004758 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004759 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004760 if (name < 0) {
4761 break;
4762 }
4763 mTracks[i]->mName = name;
4764 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004765 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004766 }
Eric Laurent81784c32012-11-19 14:55:58 -08004767 }
4768
Eric Laurent42537be2016-01-08 17:16:42 -08004769 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004770}
4771
4772
4773void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4774{
Eric Laurent81784c32012-11-19 14:55:58 -08004775 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004776 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004777 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004778 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004779
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004780 if (hasFastMixer()) {
4781 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4782
4783 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4784 // while we are dumping it. It may be inconsistent, but it won't mutate!
4785 // This is a large object so we place it on the heap.
4786 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4787 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4788 copy->dump(fd);
4789 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004790
4791#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004792 // Similar for state queue
4793 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4794 observerCopy.dump(fd);
4795 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4796 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004797#endif
4798
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004799#ifdef AUDIO_WATCHDOG
4800 if (mAudioWatchdog != 0) {
4801 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4802 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4803 wdCopy.dump(fd);
4804 }
4805#endif
4806
4807 } else {
4808 dprintf(fd, " No FastMixer\n");
4809 }
4810
Glenn Kasten46909e72013-02-26 09:20:22 -08004811#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004812 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004813 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004814#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004815
Eric Laurent81784c32012-11-19 14:55:58 -08004816}
4817
4818uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4819{
4820 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4821}
4822
4823uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4824{
4825 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4826}
4827
4828void AudioFlinger::MixerThread::cacheParameters_l()
4829{
4830 PlaybackThread::cacheParameters_l();
4831
4832 // FIXME: Relaxed timing because of a certain device that can't meet latency
4833 // Should be reduced to 2x after the vendor fixes the driver issue
4834 // increase threshold again due to low power audio mode. The way this warning
4835 // threshold is calculated and its usefulness should be reconsidered anyway.
4836 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4837}
4838
4839// ----------------------------------------------------------------------------
4840
4841AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004842 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4843 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004844{
4845}
4846
Eric Laurentbfb1b832013-01-07 09:53:42 -08004847AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4848 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004849 ThreadBase::type_t type, bool systemReady)
4850 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08004851 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004852{
4853}
4854
Eric Laurent81784c32012-11-19 14:55:58 -08004855AudioFlinger::DirectOutputThread::~DirectOutputThread()
4856{
4857}
4858
Eric Laurent5850c4c2016-11-10 13:04:31 -08004859void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004861 float left, right;
4862
4863 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4864 left = right = 0;
4865 } else {
4866 float typeVolume = mStreamTypes[track->streamType()].volume;
4867 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004868 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004869
Andy Hung10cbff12017-02-21 17:30:14 -08004870 // Get volumeshaper scaling
4871 std::pair<float /* volume */, bool /* active */>
4872 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004873 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004874 v *= vh.first;
4875 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004876
Glenn Kastenc56f3422014-03-21 17:53:17 -07004877 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4878 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4879 if (left > GAIN_FLOAT_UNITY) {
4880 left = GAIN_FLOAT_UNITY;
4881 }
4882 left *= v;
4883 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4884 if (right > GAIN_FLOAT_UNITY) {
4885 right = GAIN_FLOAT_UNITY;
4886 }
4887 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 }
4889
4890 if (lastTrack) {
4891 if (left != mLeftVolFloat || right != mRightVolFloat) {
4892 mLeftVolFloat = left;
4893 mRightVolFloat = right;
4894
4895 // Convert volumes from float to 8.24
4896 uint32_t vl = (uint32_t)(left * (1 << 24));
4897 uint32_t vr = (uint32_t)(right * (1 << 24));
4898
4899 // Delegate volume control to effect in track effect chain if needed
4900 // only one effect chain can be present on DirectOutputThread, so if
4901 // there is one, the track is connected to it
4902 if (!mEffectChains.isEmpty()) {
4903 mEffectChains[0]->setVolume_l(&vl, &vr);
4904 left = (float)vl / (1 << 24);
4905 right = (float)vr / (1 << 24);
4906 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004907 status_t result = mOutput->stream->setVolume(left, right);
4908 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004909 }
4910 }
4911}
4912
Phil Burk43b4dcc2015-06-09 16:53:44 -07004913void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4914{
4915 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004916 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917
Eric Laurent0f0631e2015-07-06 18:01:25 -07004918 if (previousTrack != 0 && latestTrack != 0) {
4919 if (mType == DIRECT) {
4920 if (previousTrack.get() != latestTrack.get()) {
4921 mFlushPending = true;
4922 }
4923 } else /* mType == OFFLOAD */ {
4924 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4925 mFlushPending = true;
4926 }
4927 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004928 }
4929 PlaybackThread::onAddNewTrack_l();
4930}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004931
Eric Laurent81784c32012-11-19 14:55:58 -08004932AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4933 Vector< sp<Track> > *tracksToRemove
4934)
4935{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004936 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004937 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004938 bool doHwPause = false;
4939 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004940
4941 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004942 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004943 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004944 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004945 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004946 continue;
4947 }
4948
Eric Laurent5850c4c2016-11-10 13:04:31 -08004949 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004950#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004951 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004952#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004953 // Only consider last track started for volume and mixer state control.
4954 // In theory an older track could underrun and restart after the new one starts
4955 // but as we only care about the transition phase between two tracks on a
4956 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004957 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004958 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004959
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004960 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004961 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004962 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004963 doHwPause = true;
4964 mHwPaused = true;
4965 }
4966 tracksToRemove->add(track);
4967 } else if (track->isFlushPending()) {
4968 track->flushAck();
4969 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004970 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004971 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004972 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004973 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004974 if (last) {
4975 mLeftVolFloat = mRightVolFloat = -1.0;
4976 if (mHwPaused) {
4977 doHwResume = true;
4978 mHwPaused = false;
4979 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004980 }
4981 }
4982
Eric Laurent81784c32012-11-19 14:55:58 -08004983 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004984 // for all its buffers to be filled before processing it.
4985 // Allow draining the buffer in case the client
4986 // app does not call stop() and relies on underrun to stop:
4987 // hence the test on (track->mRetryCount > 1).
4988 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004989 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004990 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004991 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004992 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004993 minFrames = mNormalFrameCount;
4994 } else {
4995 minFrames = 1;
4996 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004997
Eric Laurentab5cdba2014-06-09 17:22:27 -07004998 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4999 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005000 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005001 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005002
5003 if (track->mFillingUpStatus == Track::FS_FILLED) {
5004 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005005 if (last) {
5006 // make sure processVolume_l() will apply new volume even if 0
5007 mLeftVolFloat = mRightVolFloat = -1.0;
5008 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005009 if (!mHwSupportsPause) {
5010 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005011 }
5012 }
5013
5014 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005015 processVolume_l(track, last);
5016 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005017 sp<Track> previousTrack = mPreviousTrack.promote();
5018 if (previousTrack != 0) {
5019 if (track != previousTrack.get()) {
5020 // Flush any data still being written from last track
5021 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005022 // Invalidate previous track to force a seek when resuming.
5023 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005024 }
5025 }
5026 mPreviousTrack = track;
5027
Eric Laurentd595b7c2013-04-03 17:27:56 -07005028 // reset retry count
5029 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005030 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005031 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005032 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005033 doHwResume = true;
5034 mHwPaused = false;
5035 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005036 }
Eric Laurent81784c32012-11-19 14:55:58 -08005037 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005038 // clear effect chain input buffer if the last active track started underruns
5039 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005040 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005041 mEffectChains[0]->clearInputBuffer();
5042 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005043 if (track->isStopping_1()) {
5044 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005045 if (last && mHwPaused) {
5046 doHwResume = true;
5047 mHwPaused = false;
5048 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005049 }
5050 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5051 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005052 // We have consumed all the buffers of this track.
5053 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005054 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005055 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005056 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5057 } else {
5058 audioHALFrames = 0;
5059 }
5060
Andy Hung818e7a32016-02-16 18:08:07 -08005061 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005062 if (mStandby || !last ||
5063 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005064 if (track->isStopping_2()) {
5065 track->mState = TrackBase::STOPPED;
5066 }
Eric Laurent81784c32012-11-19 14:55:58 -08005067 if (track->isStopped()) {
5068 track->reset();
5069 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005070 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005071 }
5072 } else {
5073 // No buffers for this track. Give it a few chances to
5074 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005075 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005076 if (--(track->mRetryCount) <= 0) {
5077 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005078 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005079 // indicate to client process that the track was disabled because of underrun;
5080 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005081 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005082 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005083 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5084 "minFrames = %u, mFormat = %#x",
5085 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005086 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005087 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005088 doHwPause = true;
5089 mHwPaused = true;
5090 }
Eric Laurent81784c32012-11-19 14:55:58 -08005091 }
5092 }
5093 }
5094 }
5095
Eric Laurentd1f69b02014-12-15 14:33:13 -08005096 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005097 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005098 for (size_t i = 0; i < mTracks.size(); i++) {
5099 if (mTracks[i]->isFlushPending()) {
5100 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005101 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005102 }
5103 }
5104 }
5105
5106 // make sure the pause/flush/resume sequence is executed in the right order.
5107 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5108 // before flush and then resume HW. This can happen in case of pause/flush/resume
5109 // if resume is received before pause is executed.
5110 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005111 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005112 status_t result = mOutput->stream->pause();
5113 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005114 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005115 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005116 flushHw_l();
5117 }
5118 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005119 status_t result = mOutput->stream->resume();
5120 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005121 }
Eric Laurent81784c32012-11-19 14:55:58 -08005122 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005123 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005124
5125 return mixerStatus;
5126}
5127
5128void AudioFlinger::DirectOutputThread::threadLoop_mix()
5129{
Eric Laurent81784c32012-11-19 14:55:58 -08005130 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005131 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005132 // output audio to hardware
5133 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005134 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005135 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005136 status_t status = mActiveTrack->getNextBuffer(&buffer);
5137 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005138 // no need to pad with 0 for compressed audio
5139 if (audio_has_proportional_frames(mFormat)) {
5140 memset(curBuf, 0, frameCount * mFrameSize);
5141 }
Eric Laurent81784c32012-11-19 14:55:58 -08005142 break;
5143 }
5144 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5145 frameCount -= buffer.frameCount;
5146 curBuf += buffer.frameCount * mFrameSize;
5147 mActiveTrack->releaseBuffer(&buffer);
5148 }
Andy Hung2098f272014-02-27 14:00:06 -08005149 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005150 mSleepTimeUs = 0;
5151 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005152 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005153}
5154
5155void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5156{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005157 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005158 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005159 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005160 return;
5161 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005162 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005163 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005164 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005165 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005166 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005167 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005168 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005169 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005170 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005171 }
5172}
5173
Eric Laurentd1f69b02014-12-15 14:33:13 -08005174void AudioFlinger::DirectOutputThread::threadLoop_exit()
5175{
5176 {
5177 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005178 for (size_t i = 0; i < mTracks.size(); i++) {
5179 if (mTracks[i]->isFlushPending()) {
5180 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005181 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005182 }
5183 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005184 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005185 flushHw_l();
5186 }
5187 }
5188 PlaybackThread::threadLoop_exit();
5189}
5190
5191// must be called with thread mutex locked
5192bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5193{
5194 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005195 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005196
vivek mehta9cd7ad12016-03-17 00:18:29 -07005197 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5198 return !mStandby;
5199 }
5200
Eric Laurentd1f69b02014-12-15 14:33:13 -08005201 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5202 // after a timeout and we will enter standby then.
5203 if (mTracks.size() > 0) {
5204 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005205 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5206 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005207 }
5208
Eric Laurent5cff4032015-05-26 13:49:58 -07005209 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005210}
5211
Eric Laurent81784c32012-11-19 14:55:58 -08005212// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005213int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005214 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005215{
Eric Laurentad7dd962016-09-22 12:38:37 -07005216 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5217 return -1;
5218 }
Eric Laurent81784c32012-11-19 14:55:58 -08005219 return 0;
5220}
5221
5222// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005223void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005224{
5225}
5226
Eric Laurent10351942014-05-08 18:49:52 -07005227// checkForNewParameter_l() must be called with ThreadBase::mLock held
5228bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5229 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005230{
5231 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005232 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005233
Eric Laurent10351942014-05-08 18:49:52 -07005234 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005235
Eric Laurent10351942014-05-08 18:49:52 -07005236 AudioParameter param = AudioParameter(keyValuePair);
5237 int value;
5238 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5239 // forward device change to effects that have requested to be
5240 // aware of attached audio device.
5241 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005242 a2dpDeviceChanged =
5243 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005244 mOutDevice = value;
5245 for (size_t i = 0; i < mEffectChains.size(); i++) {
5246 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005247 }
5248 }
Eric Laurent81784c32012-11-19 14:55:58 -08005249 }
Eric Laurent10351942014-05-08 18:49:52 -07005250 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5251 // do not accept frame count changes if tracks are open as the track buffer
5252 // size depends on frame count and correct behavior would not be garantied
5253 // if frame count is changed after track creation
5254 if (!mTracks.isEmpty()) {
5255 status = INVALID_OPERATION;
5256 } else {
5257 reconfig = true;
5258 }
5259 }
5260 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005261 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005262 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005263 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005264 mStandby = true;
5265 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005266 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005267 }
5268 if (status == NO_ERROR && reconfig) {
5269 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005270 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005271 }
5272 }
5273
Eric Laurent42537be2016-01-08 17:16:42 -08005274 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005275}
5276
5277uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5278{
5279 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005280 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005281 time = PlaybackThread::activeSleepTimeUs();
5282 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005283 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005284 }
5285 return time;
5286}
5287
5288uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5289{
5290 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005291 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005292 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5293 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005294 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005295 }
5296 return time;
5297}
5298
5299uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5300{
5301 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005302 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005303 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5304 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005305 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005306 }
5307 return time;
5308}
5309
5310void AudioFlinger::DirectOutputThread::cacheParameters_l()
5311{
5312 PlaybackThread::cacheParameters_l();
5313
5314 // use shorter standby delay as on normal output to release
5315 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005316 // no delay on outputs with HW A/V sync
5317 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005318 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005319 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005320 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005321 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005322 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005323 }
Eric Laurent81784c32012-11-19 14:55:58 -08005324}
5325
Eric Laurente659ef42014-09-29 13:06:46 -07005326void AudioFlinger::DirectOutputThread::flushHw_l()
5327{
Phil Burk062e67a2015-02-11 13:40:50 -08005328 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005329 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005330 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005331}
5332
Andy Hung10cbff12017-02-21 17:30:14 -08005333int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5334 // If a VolumeShaper is active, we must wake up periodically to update volume.
5335 const int64_t NS_PER_MS = 1000000;
5336 return mVolumeShaperActive ?
5337 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5338}
5339
Eric Laurent81784c32012-11-19 14:55:58 -08005340// ----------------------------------------------------------------------------
5341
Eric Laurentbfb1b832013-01-07 09:53:42 -08005342AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005343 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005345 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005346 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005347 mDrainSequence(0),
5348 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349{
5350}
5351
5352AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5353{
5354}
5355
5356void AudioFlinger::AsyncCallbackThread::onFirstRef()
5357{
5358 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5359}
5360
5361bool AudioFlinger::AsyncCallbackThread::threadLoop()
5362{
5363 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005364 uint32_t writeAckSequence;
5365 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005366 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005367
5368 {
5369 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005370 while (!((mWriteAckSequence & 1) ||
5371 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005372 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005373 exitPending())) {
5374 mWaitWorkCV.wait(mLock);
5375 }
5376
Eric Laurentbfb1b832013-01-07 09:53:42 -08005377 if (exitPending()) {
5378 break;
5379 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005380 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5381 mWriteAckSequence, mDrainSequence);
5382 writeAckSequence = mWriteAckSequence;
5383 mWriteAckSequence &= ~1;
5384 drainSequence = mDrainSequence;
5385 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005386 asyncError = mAsyncError;
5387 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 }
5389 {
Eric Laurent4de95592013-09-26 15:28:21 -07005390 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5391 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005392 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005393 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005395 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005396 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005398 if (asyncError) {
5399 playbackThread->onAsyncError();
5400 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401 }
5402 }
5403 }
5404 return false;
5405}
5406
5407void AudioFlinger::AsyncCallbackThread::exit()
5408{
5409 ALOGV("AsyncCallbackThread::exit");
5410 Mutex::Autolock _l(mLock);
5411 requestExit();
5412 mWaitWorkCV.broadcast();
5413}
5414
Eric Laurent3b4529e2013-09-05 18:09:19 -07005415void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416{
5417 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005418 // bit 0 is cleared
5419 mWriteAckSequence = sequence << 1;
5420}
5421
5422void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5423{
5424 Mutex::Autolock _l(mLock);
5425 // ignore unexpected callbacks
5426 if (mWriteAckSequence & 2) {
5427 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428 mWaitWorkCV.signal();
5429 }
5430}
5431
Eric Laurent3b4529e2013-09-05 18:09:19 -07005432void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005433{
5434 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005435 // bit 0 is cleared
5436 mDrainSequence = sequence << 1;
5437}
5438
5439void AudioFlinger::AsyncCallbackThread::resetDraining()
5440{
5441 Mutex::Autolock _l(mLock);
5442 // ignore unexpected callbacks
5443 if (mDrainSequence & 2) {
5444 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445 mWaitWorkCV.signal();
5446 }
5447}
5448
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005449void AudioFlinger::AsyncCallbackThread::setAsyncError()
5450{
5451 Mutex::Autolock _l(mLock);
5452 mAsyncError = true;
5453 mWaitWorkCV.signal();
5454}
5455
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456
5457// ----------------------------------------------------------------------------
5458AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005459 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5460 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005461 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5462 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005463{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005464 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005465 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005466 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467}
5468
Eric Laurentbfb1b832013-01-07 09:53:42 -08005469void AudioFlinger::OffloadThread::threadLoop_exit()
5470{
5471 if (mFlushPending || mHwPaused) {
5472 // If a flush is pending or track was paused, just discard buffered data
5473 flushHw_l();
5474 } else {
5475 mMixerStatus = MIXER_DRAIN_ALL;
5476 threadLoop_drain();
5477 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005478 if (mUseAsyncWrite) {
5479 ALOG_ASSERT(mCallbackThread != 0);
5480 mCallbackThread->exit();
5481 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 PlaybackThread::threadLoop_exit();
5483}
5484
5485AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5486 Vector< sp<Track> > *tracksToRemove
5487)
5488{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005489 size_t count = mActiveTracks.size();
5490
5491 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005492 bool doHwPause = false;
5493 bool doHwResume = false;
5494
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005495 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005496
Eric Laurentbfb1b832013-01-07 09:53:42 -08005497 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005498 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005499 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005500#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005502#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005503 // Only consider last track started for volume and mixer state control.
5504 // In theory an older track could underrun and restart after the new one starts
5505 // but as we only care about the transition phase between two tracks on a
5506 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005507 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005508 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005509
Haynes Mathew George7844f672014-01-15 12:32:55 -08005510 if (track->isInvalid()) {
5511 ALOGW("An invalidated track shouldn't be in active list");
5512 tracksToRemove->add(track);
5513 continue;
5514 }
5515
5516 if (track->mState == TrackBase::IDLE) {
5517 ALOGW("An idle track shouldn't be in active list");
5518 continue;
5519 }
5520
Eric Laurentbfb1b832013-01-07 09:53:42 -08005521 if (track->isPausing()) {
5522 track->setPaused();
5523 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005524 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005525 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526 mHwPaused = true;
5527 }
5528 // If we were part way through writing the mixbuffer to
5529 // the HAL we must save this until we resume
5530 // BUG - this will be wrong if a different track is made active,
5531 // in that case we want to discard the pending data in the
5532 // mixbuffer and tell the client to present it again when the
5533 // track is resumed
5534 mPausedWriteLength = mCurrentWriteLength;
5535 mPausedBytesRemaining = mBytesRemaining;
5536 mBytesRemaining = 0; // stop writing
5537 }
5538 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005539 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005540 if (track->isStopping_1()) {
5541 track->mRetryCount = kMaxTrackStopRetriesOffload;
5542 } else {
5543 track->mRetryCount = kMaxTrackRetriesOffload;
5544 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005545 track->flushAck();
5546 if (last) {
5547 mFlushPending = true;
5548 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005549 } else if (track->isResumePending()){
5550 track->resumeAck();
5551 if (last) {
5552 if (mPausedBytesRemaining) {
5553 // Need to continue write that was interrupted
5554 mCurrentWriteLength = mPausedWriteLength;
5555 mBytesRemaining = mPausedBytesRemaining;
5556 mPausedBytesRemaining = 0;
5557 }
5558 if (mHwPaused) {
5559 doHwResume = true;
5560 mHwPaused = false;
5561 // threadLoop_mix() will handle the case that we need to
5562 // resume an interrupted write
5563 }
5564 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005565 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005566
Eric Laurent3df841a2016-07-15 15:15:40 -07005567 mLeftVolFloat = mRightVolFloat = -1.0;
5568
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005569 // Do not handle new data in this iteration even if track->framesReady()
5570 mixerStatus = MIXER_TRACKS_ENABLED;
5571 }
5572 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005573 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005574 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 if (track->mFillingUpStatus == Track::FS_FILLED) {
5576 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005577 if (last) {
5578 // make sure processVolume_l() will apply new volume even if 0
5579 mLeftVolFloat = mRightVolFloat = -1.0;
5580 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 }
5582
5583 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005584 sp<Track> previousTrack = mPreviousTrack.promote();
5585 if (previousTrack != 0) {
5586 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005587 // Flush any data still being written from last track
5588 mBytesRemaining = 0;
5589 if (mPausedBytesRemaining) {
5590 // Last track was paused so we also need to flush saved
5591 // mixbuffer state and invalidate track so that it will
5592 // re-submit that unwritten data when it is next resumed
5593 mPausedBytesRemaining = 0;
5594 // Invalidate is a bit drastic - would be more efficient
5595 // to have a flag to tell client that some of the
5596 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005597 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005598 }
5599 // flush data already sent to the DSP if changing audio session as audio
5600 // comes from a different source. Also invalidate previous track to force a
5601 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005602 if (previousTrack->sessionId() != track->sessionId()) {
5603 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005604 }
5605 }
5606 }
5607 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005608 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005609 if (track->isStopping_1()) {
5610 track->mRetryCount = kMaxTrackStopRetriesOffload;
5611 } else {
5612 track->mRetryCount = kMaxTrackRetriesOffload;
5613 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005614 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005615 mixerStatus = MIXER_TRACKS_READY;
5616 }
5617 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005618 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005620 if (--(track->mRetryCount) <= 0) {
5621 // Hardware buffer can hold a large amount of audio so we must
5622 // wait for all current track's data to drain before we say
5623 // that the track is stopped.
5624 if (mBytesRemaining == 0) {
5625 // Only start draining when all data in mixbuffer
5626 // has been written
5627 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5628 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5629 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5630 if (last && !mStandby) {
5631 // do not modify drain sequence if we are already draining. This happens
5632 // when resuming from pause after drain.
5633 if ((mDrainSequence & 1) == 0) {
5634 mSleepTimeUs = 0;
5635 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5636 mixerStatus = MIXER_DRAIN_TRACK;
5637 mDrainSequence += 2;
5638 }
5639 if (mHwPaused) {
5640 // It is possible to move from PAUSED to STOPPING_1 without
5641 // a resume so we must ensure hardware is running
5642 doHwResume = true;
5643 mHwPaused = false;
5644 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005645 }
5646 }
Eric Laurente93cc032016-05-05 10:15:10 -07005647 } else if (last) {
5648 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5649 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005650 }
5651 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005652 // Drain has completed or we are in standby, signal presentation complete
5653 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005654 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005655 uint32_t latency = 0;
5656 status_t result = mOutput->stream->getLatency(&latency);
5657 ALOGE_IF(result != OK,
5658 "Error when retrieving output stream latency: %d", result);
5659 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005660 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005661 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005662 track->presentationComplete(framesWritten, audioHALFrames);
5663 track->reset();
5664 tracksToRemove->add(track);
5665 }
5666 } else {
5667 // No buffers for this track. Give it a few chances to
5668 // fill a buffer, then remove it from active list.
5669 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005670 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005671 uint64_t position = 0;
5672 struct timespec unused;
5673 // The running check restarts the retry counter at least once.
5674 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5675 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5676 running = true;
5677 mOffloadUnderrunPosition = position;
5678 }
5679 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005680 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5681 (long long)position, (long long)mOffloadUnderrunPosition);
5682 }
5683 if (running) { // still running, give us more time.
5684 track->mRetryCount = kMaxTrackRetriesOffload;
5685 } else {
5686 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5687 track->name());
5688 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005689 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005690 // it will then automatically call start() when data is available
5691 track->disable();
5692 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005693 } else if (last){
5694 mixerStatus = MIXER_TRACKS_ENABLED;
5695 }
5696 }
5697 }
5698 // compute volume for this track
5699 processVolume_l(track, last);
5700 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005701
Eric Laurentea0fade2013-10-04 16:23:48 -07005702 // make sure the pause/flush/resume sequence is executed in the right order.
5703 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5704 // before flush and then resume HW. This can happen in case of pause/flush/resume
5705 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005706 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005707 status_t result = mOutput->stream->pause();
5708 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005709 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005710 if (mFlushPending) {
5711 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005712 }
Eric Laurentfd477972013-10-25 18:10:40 -07005713 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005714 status_t result = mOutput->stream->resume();
5715 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005716 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005717
Eric Laurentbfb1b832013-01-07 09:53:42 -08005718 // remove all the tracks that need to be...
5719 removeTracks_l(*tracksToRemove);
5720
5721 return mixerStatus;
5722}
5723
Eric Laurentbfb1b832013-01-07 09:53:42 -08005724// must be called with thread mutex locked
5725bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5726{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005727 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5728 mWriteAckSequence, mDrainSequence);
5729 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005730 return true;
5731 }
5732 return false;
5733}
5734
Eric Laurentbfb1b832013-01-07 09:53:42 -08005735bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5736{
5737 Mutex::Autolock _l(mLock);
5738 return waitingAsyncCallback_l();
5739}
5740
5741void AudioFlinger::OffloadThread::flushHw_l()
5742{
Eric Laurente659ef42014-09-29 13:06:46 -07005743 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744 // Flush anything still waiting in the mixbuffer
5745 mCurrentWriteLength = 0;
5746 mBytesRemaining = 0;
5747 mPausedWriteLength = 0;
5748 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005749 // reset bytes written count to reflect that DSP buffers are empty after flush.
5750 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005751 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005752
Eric Laurentbfb1b832013-01-07 09:53:42 -08005753 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005754 // discard any pending drain or write ack by incrementing sequence
5755 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5756 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005757 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005758 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5759 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005760 }
5761}
5762
Haynes Mathew George05317d22016-05-03 16:34:26 -07005763void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5764{
5765 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005766 if (PlaybackThread::invalidateTracks_l(streamType)) {
5767 mFlushPending = true;
5768 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005769}
5770
Eric Laurentbfb1b832013-01-07 09:53:42 -08005771// ----------------------------------------------------------------------------
5772
Eric Laurent81784c32012-11-19 14:55:58 -08005773AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005774 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005775 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005776 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005777 mWaitTimeMs(UINT_MAX)
5778{
5779 addOutputTrack(mainThread);
5780}
5781
5782AudioFlinger::DuplicatingThread::~DuplicatingThread()
5783{
5784 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5785 mOutputTracks[i]->destroy();
5786 }
5787}
5788
5789void AudioFlinger::DuplicatingThread::threadLoop_mix()
5790{
5791 // mix buffers...
5792 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005793 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005794 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005795 if (mMixerBufferValid) {
5796 memset(mMixerBuffer, 0, mMixerBufferSize);
5797 } else {
5798 memset(mSinkBuffer, 0, mSinkBufferSize);
5799 }
Eric Laurent81784c32012-11-19 14:55:58 -08005800 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005801 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005802 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005803 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005804 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005805}
5806
5807void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5808{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005809 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005810 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005811 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005812 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005813 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005814 }
5815 } else if (mBytesWritten != 0) {
5816 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5817 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005818 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005819 } else {
5820 // flush remaining overflow buffers in output tracks
5821 writeFrames = 0;
5822 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005823 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005824 }
5825}
5826
Eric Laurentbfb1b832013-01-07 09:53:42 -08005827ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005828{
5829 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005830 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005831 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005832 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005833 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005834}
5835
5836void AudioFlinger::DuplicatingThread::threadLoop_standby()
5837{
5838 // DuplicatingThread implements standby by stopping all tracks
5839 for (size_t i = 0; i < outputTracks.size(); i++) {
5840 outputTracks[i]->stop();
5841 }
5842}
5843
5844void AudioFlinger::DuplicatingThread::saveOutputTracks()
5845{
5846 outputTracks = mOutputTracks;
5847}
5848
5849void AudioFlinger::DuplicatingThread::clearOutputTracks()
5850{
5851 outputTracks.clear();
5852}
5853
5854void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5855{
5856 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005857 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5858 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5859 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5860 const size_t frameCount =
5861 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5862 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5863 // from different OutputTracks and their associated MixerThreads (e.g. one may
5864 // nearly empty and the other may be dropping data).
5865
5866 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005867 this,
5868 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005869 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005870 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005871 frameCount,
5872 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005873 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5874 if (status != NO_ERROR) {
5875 ALOGE("addOutputTrack() initCheck failed %d", status);
5876 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005877 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005878 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5879 mOutputTracks.add(outputTrack);
5880 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5881 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005882}
5883
5884void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5885{
5886 Mutex::Autolock _l(mLock);
5887 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5888 if (mOutputTracks[i]->thread() == thread) {
5889 mOutputTracks[i]->destroy();
5890 mOutputTracks.removeAt(i);
5891 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005892 if (thread->getOutput() == mOutput) {
5893 mOutput = NULL;
5894 }
Eric Laurent81784c32012-11-19 14:55:58 -08005895 return;
5896 }
5897 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005898 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005899}
5900
5901// caller must hold mLock
5902void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5903{
5904 mWaitTimeMs = UINT_MAX;
5905 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5906 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5907 if (strong != 0) {
5908 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5909 if (waitTimeMs < mWaitTimeMs) {
5910 mWaitTimeMs = waitTimeMs;
5911 }
5912 }
5913 }
5914}
5915
5916
5917bool AudioFlinger::DuplicatingThread::outputsReady(
5918 const SortedVector< sp<OutputTrack> > &outputTracks)
5919{
5920 for (size_t i = 0; i < outputTracks.size(); i++) {
5921 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5922 if (thread == 0) {
5923 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5924 outputTracks[i].get());
5925 return false;
5926 }
5927 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5928 // see note at standby() declaration
5929 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5930 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5931 thread.get());
5932 return false;
5933 }
5934 }
5935 return true;
5936}
5937
5938uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5939{
5940 return (mWaitTimeMs * 1000) / 2;
5941}
5942
5943void AudioFlinger::DuplicatingThread::cacheParameters_l()
5944{
5945 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5946 updateWaitTime_l();
5947
5948 MixerThread::cacheParameters_l();
5949}
5950
Eric Laurent6acd1d42017-01-04 14:23:29 -08005951
Eric Laurent81784c32012-11-19 14:55:58 -08005952// ----------------------------------------------------------------------------
5953// Record
5954// ----------------------------------------------------------------------------
5955
5956AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5957 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005958 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005959 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005960 audio_devices_t inDevice,
5961 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005962#ifdef TEE_SINK
5963 , const sp<NBAIO_Sink>& teeSink
5964#endif
5965 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005966 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07005967 mInput(input),
5968 mActiveTracks(&this->mLocalLog),
5969 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005970 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005971 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005972#ifdef TEE_SINK
5973 , mTeeSink(teeSink)
5974#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005975 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5976 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005977 // mFastCapture below
5978 , mFastCaptureFutex(0)
5979 // mInputSource
5980 // mPipeSink
5981 // mPipeSource
5982 , mPipeFramesP2(0)
5983 // mPipeMemory
5984 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005985 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07005986 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005987{
Glenn Kastend7dca052015-03-05 16:05:54 -08005988 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5989 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005990
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005991 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005992
5993 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005994 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005995 size_t numCounterOffers = 0;
5996 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005997#if !LOG_NDEBUG
5998 ssize_t index =
5999#else
6000 (void)
6001#endif
6002 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006003 ALOG_ASSERT(index == 0);
6004
6005 // initialize fast capture depending on configuration
6006 bool initFastCapture;
6007 switch (kUseFastCapture) {
6008 case FastCapture_Never:
6009 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006010 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006011 break;
6012 case FastCapture_Always:
6013 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006014 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006015 break;
6016 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006017 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006018 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6019 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6020 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006021 break;
6022 // case FastCapture_Dynamic:
6023 }
6024
6025 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006026 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006027 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006028 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6029 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006030 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006031 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006032 const sp<MemoryDealer> roHeap(readOnlyHeap());
6033 sp<IMemory> pipeMemory;
6034 if ((roHeap == 0) ||
6035 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006036 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6037 ALOGE("not enough memory for pipe buffer size=%zu; "
6038 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6039 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6040 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006041 goto failed;
6042 }
6043 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6044 memset(pipeBuffer, 0, pipeSize);
6045 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6046 const NBAIO_Format offers[1] = {format};
6047 size_t numCounterOffers = 0;
6048 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6049 ALOG_ASSERT(index == 0);
6050 mPipeSink = pipe;
6051 PipeReader *pipeReader = new PipeReader(*pipe);
6052 numCounterOffers = 0;
6053 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6054 ALOG_ASSERT(index == 0);
6055 mPipeSource = pipeReader;
6056 mPipeFramesP2 = pipeFramesP2;
6057 mPipeMemory = pipeMemory;
6058
6059 // create fast capture
6060 mFastCapture = new FastCapture();
6061 FastCaptureStateQueue *sq = mFastCapture->sq();
6062#ifdef STATE_QUEUE_DUMP
6063 // FIXME
6064#endif
6065 FastCaptureState *state = sq->begin();
6066 state->mCblk = NULL;
6067 state->mInputSource = mInputSource.get();
6068 state->mInputSourceGen++;
6069 state->mPipeSink = pipe;
6070 state->mPipeSinkGen++;
6071 state->mFrameCount = mFrameCount;
6072 state->mCommand = FastCaptureState::COLD_IDLE;
6073 // already done in constructor initialization list
6074 //mFastCaptureFutex = 0;
6075 state->mColdFutexAddr = &mFastCaptureFutex;
6076 state->mColdGen++;
6077 state->mDumpState = &mFastCaptureDumpState;
6078#ifdef TEE_SINK
6079 // FIXME
6080#endif
6081 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6082 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6083 sq->end();
6084 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6085
6086 // start the fast capture
6087 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6088 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006089 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006090 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006091#ifdef AUDIO_WATCHDOG
6092 // FIXME
6093#endif
6094
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006095 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006096 }
6097failed: ;
6098
6099 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006100}
6101
Eric Laurent81784c32012-11-19 14:55:58 -08006102AudioFlinger::RecordThread::~RecordThread()
6103{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006104 if (mFastCapture != 0) {
6105 FastCaptureStateQueue *sq = mFastCapture->sq();
6106 FastCaptureState *state = sq->begin();
6107 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6108 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6109 if (old == -1) {
6110 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6111 }
6112 }
6113 state->mCommand = FastCaptureState::EXIT;
6114 sq->end();
6115 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6116 mFastCapture->join();
6117 mFastCapture.clear();
6118 }
6119 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006120 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006121 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006122}
6123
6124void AudioFlinger::RecordThread::onFirstRef()
6125{
Glenn Kastend7dca052015-03-05 16:05:54 -08006126 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006127}
6128
Eric Laurent555530a2017-02-07 18:17:24 -08006129void AudioFlinger::RecordThread::preExit()
6130{
6131 ALOGV(" preExit()");
6132 Mutex::Autolock _l(mLock);
6133 for (size_t i = 0; i < mTracks.size(); i++) {
6134 sp<RecordTrack> track = mTracks[i];
6135 track->invalidate();
6136 }
6137 mActiveTracks.clear();
6138 mStartStopCond.broadcast();
6139}
6140
Eric Laurent81784c32012-11-19 14:55:58 -08006141bool AudioFlinger::RecordThread::threadLoop()
6142{
Eric Laurent81784c32012-11-19 14:55:58 -08006143 nsecs_t lastWarning = 0;
6144
6145 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006146
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006147reacquire_wakelock:
6148 sp<RecordTrack> activeTrack;
6149 {
6150 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006151 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006152 }
6153
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006154 // used to request a deferred sleep, to be executed later while mutex is unlocked
6155 uint32_t sleepUs = 0;
6156
6157 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006158 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006159 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006160
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006161 // activeTracks accumulates a copy of a subset of mActiveTracks
6162 Vector< sp<RecordTrack> > activeTracks;
6163
Glenn Kasten735f45f2014-08-18 15:51:59 -07006164 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006165 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006166
Glenn Kasten735f45f2014-08-18 15:51:59 -07006167 // reference to a fast track which is about to be removed
6168 sp<RecordTrack> fastTrackToRemove;
6169
Eric Laurent81784c32012-11-19 14:55:58 -08006170 { // scope for mLock
6171 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006172
Eric Laurent021cf962014-05-13 10:18:14 -07006173 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006174
Eric Laurent000a4192014-01-29 15:17:32 -08006175 // check exitPending here because checkForNewParameters_l() and
6176 // checkForNewParameters_l() can temporarily release mLock
6177 if (exitPending()) {
6178 break;
6179 }
6180
Eric Laurent5c25d562016-07-13 17:17:45 -07006181 // sleep with mutex unlocked
6182 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006183 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006184 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6185 ATRACE_END();
6186 sleepUs = 0;
6187 continue;
6188 }
6189
Glenn Kasten2b806402013-11-20 16:37:38 -08006190 // if no active track(s), then standby and release wakelock
6191 size_t size = mActiveTracks.size();
6192 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006193 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006194 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006195 releaseWakeLock_l();
6196 ALOGV("RecordThread: loop stopping");
6197 // go to sleep
6198 mWaitWorkCV.wait(mLock);
6199 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006200 goto reacquire_wakelock;
6201 }
6202
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006203 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006204 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006206
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006207 activeTrack = mActiveTracks[i];
6208 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006209 if (activeTrack->isFastTrack()) {
6210 ALOG_ASSERT(fastTrackToRemove == 0);
6211 fastTrackToRemove = activeTrack;
6212 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006213 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006214 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006216 continue;
6217 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006218
6219 TrackBase::track_state activeTrackState = activeTrack->mState;
6220 switch (activeTrackState) {
6221
6222 case TrackBase::PAUSING:
6223 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006224 doBroadcast = true;
6225 size--;
6226 continue;
6227
6228 case TrackBase::STARTING_1:
6229 sleepUs = 10000;
6230 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006231 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006232 continue;
6233
6234 case TrackBase::STARTING_2:
6235 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006236 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006237 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006238 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006239 break;
6240
6241 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006242 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 break;
6244
6245 case TrackBase::IDLE:
6246 i++;
6247 continue;
6248
6249 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006250 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006251 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006252
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006253 activeTracks.add(activeTrack);
6254 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006255
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006256 if (activeTrack->isFastTrack()) {
6257 ALOG_ASSERT(!mFastTrackAvail);
6258 ALOG_ASSERT(fastTrack == 0);
6259 fastTrack = activeTrack;
6260 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006261 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006262
Andy Hungdae27702016-10-31 14:01:16 -07006263 mActiveTracks.updatePowerState(this);
6264
Eric Laurent5c25d562016-07-13 17:17:45 -07006265 if (allStopped) {
6266 standbyIfNotAlreadyInStandby();
6267 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006268 if (doBroadcast) {
6269 mStartStopCond.broadcast();
6270 }
6271
6272 // sleep if there are no active tracks to process
6273 if (activeTracks.size() == 0) {
6274 if (sleepUs == 0) {
6275 sleepUs = kRecordThreadSleepUs;
6276 }
6277 continue;
6278 }
6279 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006280
Eric Laurent81784c32012-11-19 14:55:58 -08006281 lockEffectChains_l(effectChains);
6282 }
6283
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006284 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006285
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006286 size_t size = effectChains.size();
6287 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006288 // thread mutex is not locked, but effect chain is locked
6289 effectChains[i]->process_l();
6290 }
6291
Glenn Kasten735f45f2014-08-18 15:51:59 -07006292 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006293 if (mFastCapture != 0) {
6294 FastCaptureStateQueue *sq = mFastCapture->sq();
6295 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006296 bool didModify = false;
6297 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006298 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6299 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6300 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6301 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6302 if (old == -1) {
6303 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6304 }
6305 }
6306 state->mCommand = FastCaptureState::READ_WRITE;
6307#if 0 // FIXME
6308 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006309 FastThreadDumpState::kSamplingNforLowRamDevice :
6310 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006311#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006312 didModify = true;
6313 }
6314 audio_track_cblk_t *cblkOld = state->mCblk;
6315 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6316 if (cblkNew != cblkOld) {
6317 state->mCblk = cblkNew;
6318 // block until acked if removing a fast track
6319 if (cblkOld != NULL) {
6320 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6321 }
6322 didModify = true;
6323 }
6324 sq->end(didModify);
6325 if (didModify) {
6326 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006327#if 0
6328 if (kUseFastCapture == FastCapture_Dynamic) {
6329 mNormalSource = mPipeSource;
6330 }
6331#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 }
6333 }
6334
Glenn Kasten735f45f2014-08-18 15:51:59 -07006335 // now run the fast track destructor with thread mutex unlocked
6336 fastTrackToRemove.clear();
6337
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006338 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6339 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6340 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6341 // If destination is non-contiguous, first read past the nominal end of buffer, then
6342 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006343
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006344 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006345 ssize_t framesRead;
6346
6347 // If an NBAIO source is present, use it to read the normal capture's data
6348 if (mPipeSource != 0) {
6349 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006350 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006351 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006352 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006353 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6354 // buffer size or at least for 20ms.
6355 size_t sleepFrames = max(
6356 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6357 if (framesRead <= (ssize_t) sleepFrames) {
6358 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6359 }
6360 if (framesRead < 0) {
6361 status_t status = (status_t) framesRead;
6362 switch (status) {
6363 case OVERRUN:
6364 ALOGW("overrun on read from pipe");
6365 framesRead = 0;
6366 break;
6367 case NEGOTIATE:
6368 ALOGE("re-negotiation is needed");
6369 framesRead = -1; // Will cause an attempt to recover.
6370 break;
6371 default:
6372 ALOGE("unknown error %d on read from pipe", status);
6373 break;
6374 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006375 }
6376 // otherwise use the HAL / AudioStreamIn directly
6377 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006378 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006379 size_t bytesRead;
6380 status_t result = mInput->stream->read(
6381 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006382 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006383 if (result < 0) {
6384 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006385 } else {
6386 framesRead = bytesRead / mFrameSize;
6387 }
6388 }
6389
Andy Hung3f0c9022016-01-15 17:49:46 -08006390 // Update server timestamp with server stats
6391 // systemTime() is optional if the hardware supports timestamps.
6392 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6393 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6394
6395 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006396 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006397 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006398 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006399 if (ret == NO_ERROR) {
6400 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6401 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6402 // Note: In general record buffers should tend to be empty in
6403 // a properly running pipeline.
6404 //
6405 // Also, it is not advantageous to call get_presentation_position during the read
6406 // as the read obtains a lock, preventing the timestamp call from executing.
6407 }
6408 }
6409 // Use this to track timestamp information
6410 // ALOGD("%s", mTimestamp.toString().c_str());
6411
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006412 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006413 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006414 // Force input into standby so that it tries to recover at next read attempt
6415 inputStandBy();
6416 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006417 }
6418 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006419 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006420 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006421 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006422
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006423 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006424 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006425 }
6426 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006427 {
6428 size_t part1 = mRsmpInFramesP2 - rear;
6429 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006430 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006431 (framesRead - part1) * mFrameSize);
6432 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 }
6434 rear = mRsmpInRear += framesRead;
6435
6436 size = activeTracks.size();
6437 // loop over each active track
6438 for (size_t i = 0; i < size; i++) {
6439 activeTrack = activeTracks[i];
6440
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006441 // skip fast tracks, as those are handled directly by FastCapture
6442 if (activeTrack->isFastTrack()) {
6443 continue;
6444 }
6445
Andy Hung73c02e42015-03-29 01:13:58 -07006446 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006447 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6448
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006449 enum {
6450 OVERRUN_UNKNOWN,
6451 OVERRUN_TRUE,
6452 OVERRUN_FALSE
6453 } overrun = OVERRUN_UNKNOWN;
6454
6455 // loop over getNextBuffer to handle circular sink
6456 for (;;) {
6457
6458 activeTrack->mSink.frameCount = ~0;
6459 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6460 size_t framesOut = activeTrack->mSink.frameCount;
6461 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6462
Andy Hung73c02e42015-03-29 01:13:58 -07006463 // check available frames and handle overrun conditions
6464 // if the record track isn't draining fast enough.
6465 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006466 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006467 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6468 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006469 overrun = OVERRUN_TRUE;
6470 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006471 if (framesOut == 0 || framesIn == 0) {
6472 break;
6473 }
6474
Andy Hung6770c6f2015-04-07 13:43:36 -07006475 // Don't allow framesOut to be larger than what is possible with resampling
6476 // from framesIn.
6477 // This isn't strictly necessary but helps limit buffer resizing in
6478 // RecordBufferConverter. TODO: remove when no longer needed.
6479 framesOut = min(framesOut,
6480 destinationFramesPossible(
6481 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006482 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6483 framesOut = activeTrack->mRecordBufferConverter->convert(
6484 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006485
6486 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6487 overrun = OVERRUN_FALSE;
6488 }
6489
6490 if (activeTrack->mFramesToDrop == 0) {
6491 if (framesOut > 0) {
6492 activeTrack->mSink.frameCount = framesOut;
6493 activeTrack->releaseBuffer(&activeTrack->mSink);
6494 }
6495 } else {
6496 // FIXME could do a partial drop of framesOut
6497 if (activeTrack->mFramesToDrop > 0) {
6498 activeTrack->mFramesToDrop -= framesOut;
6499 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006500 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006501 }
6502 } else {
6503 activeTrack->mFramesToDrop += framesOut;
6504 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6505 activeTrack->mSyncStartEvent->isCancelled()) {
6506 ALOGW("Synced record %s, session %d, trigger session %d",
6507 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6508 activeTrack->sessionId(),
6509 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006510 activeTrack->mSyncStartEvent->triggerSession() :
6511 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006512 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006513 }
6514 }
6515 }
6516
6517 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006518 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006519 }
6520 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006521
6522 switch (overrun) {
6523 case OVERRUN_TRUE:
6524 // client isn't retrieving buffers fast enough
6525 if (!activeTrack->setOverflow()) {
6526 nsecs_t now = systemTime();
6527 // FIXME should lastWarning per track?
6528 if ((now - lastWarning) > kWarningThrottleNs) {
6529 ALOGW("RecordThread: buffer overflow");
6530 lastWarning = now;
6531 }
6532 }
6533 break;
6534 case OVERRUN_FALSE:
6535 activeTrack->clearOverflow();
6536 break;
6537 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006538 break;
6539 }
6540
Andy Hung3f0c9022016-01-15 17:49:46 -08006541 // update frame information and push timestamp out
6542 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006543 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006544 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6545 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006546 }
6547
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006548unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006549 // enable changes in effect chain
6550 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006551 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006552 }
6553
Glenn Kasten93e471f2013-08-19 08:40:07 -07006554 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006555
6556 {
6557 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006558 for (size_t i = 0; i < mTracks.size(); i++) {
6559 sp<RecordTrack> track = mTracks[i];
6560 track->invalidate();
6561 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006562 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006563 mStartStopCond.broadcast();
6564 }
6565
6566 releaseWakeLock();
6567
6568 ALOGV("RecordThread %p exiting", this);
6569 return false;
6570}
6571
Glenn Kasten93e471f2013-08-19 08:40:07 -07006572void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006573{
6574 if (!mStandby) {
6575 inputStandBy();
6576 mStandby = true;
6577 }
6578}
6579
6580void AudioFlinger::RecordThread::inputStandBy()
6581{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006582 // Idle the fast capture if it's currently running
6583 if (mFastCapture != 0) {
6584 FastCaptureStateQueue *sq = mFastCapture->sq();
6585 FastCaptureState *state = sq->begin();
6586 if (!(state->mCommand & FastCaptureState::IDLE)) {
6587 state->mCommand = FastCaptureState::COLD_IDLE;
6588 state->mColdFutexAddr = &mFastCaptureFutex;
6589 state->mColdGen++;
6590 mFastCaptureFutex = 0;
6591 sq->end();
6592 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6593 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6594#if 0
6595 if (kUseFastCapture == FastCapture_Dynamic) {
6596 // FIXME
6597 }
6598#endif
6599#ifdef AUDIO_WATCHDOG
6600 // FIXME
6601#endif
6602 } else {
6603 sq->end(false /*didModify*/);
6604 }
6605 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006606 status_t result = mInput->stream->standby();
6607 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006608
6609 // If going into standby, flush the pipe source.
6610 if (mPipeSource.get() != nullptr) {
6611 const ssize_t flushed = mPipeSource->flush();
6612 if (flushed > 0) {
6613 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6614 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6615 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6616 }
6617 }
Eric Laurent81784c32012-11-19 14:55:58 -08006618}
6619
Glenn Kasten05997e22014-03-13 15:08:33 -07006620// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006621sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006622 const sp<AudioFlinger::Client>& client,
6623 uint32_t sampleRate,
6624 audio_format_t format,
6625 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006626 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006627 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006628 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006629 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006630 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006631 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006632 status_t *status,
6633 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006634{
Glenn Kasten74935e42013-12-19 08:56:45 -08006635 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006636 sp<RecordTrack> track;
6637 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006638 audio_input_flags_t inputFlags = mInput->flags;
6639
6640 // special case for FAST flag considered OK if fast capture is present
6641 if (hasFastCapture()) {
6642 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6643 }
6644
6645 // Check if requested flags are compatible with output stream flags
6646 if ((*flags & inputFlags) != *flags) {
6647 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6648 " input flags (%08x)",
6649 *flags, inputFlags);
6650 *flags = (audio_input_flags_t)(*flags & inputFlags);
6651 }
Eric Laurent81784c32012-11-19 14:55:58 -08006652
Glenn Kasten90e58b12013-07-31 16:16:02 -07006653 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006654 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006655 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006656 // we formerly checked for a callback handler (non-0 tid),
6657 // but that is no longer required for TRANSFER_OBTAIN mode
6658 //
Glenn Kasten74105912014-07-03 12:28:53 -07006659 // frame count is not specified, or is exactly the pipe depth
6660 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006661 // PCM data
6662 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006663 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006664 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006665 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006666 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006667 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006668 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006669 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006670 hasFastCapture() &&
6671 // there are sufficient fast track slots available
6672 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006673 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006674 // check compatibility with audio effects.
6675 Mutex::Autolock _l(mLock);
6676 // Do not accept FAST flag if the session has software effects
6677 sp<EffectChain> chain = getEffectChain_l(sessionId);
6678 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006679 audio_input_flags_t old = *flags;
6680 chain->checkInputFlagCompatibility(flags);
6681 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006682 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6683 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006684 }
6685 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006686 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006687 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6688 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006689 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006690 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6691 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006692 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006693 this, frameCount, mFrameCount, mPipeFramesP2,
6694 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006695 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006696 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006697 }
6698 }
6699
6700 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006701 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006702 // fast track: frame count is exactly the pipe depth
6703 frameCount = mPipeFramesP2;
6704 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6705 *notificationFrames = mFrameCount;
6706 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006707 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6708 // or 20 ms if there is a fast capture
6709 // TODO This could be a roundupRatio inline, and const
6710 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6711 * sampleRate + mSampleRate - 1) / mSampleRate;
6712 // minimum number of notification periods is at least kMinNotifications,
6713 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6714 static const size_t kMinNotifications = 3;
6715 static const uint32_t kMinMs = 30;
6716 // TODO This could be a roundupRatio inline
6717 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6718 // TODO This could be a roundupRatio inline
6719 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6720 maxNotificationFrames;
6721 const size_t minFrameCount = maxNotificationFrames *
6722 max(kMinNotifications, minNotificationsByMs);
6723 frameCount = max(frameCount, minFrameCount);
6724 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6725 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006726 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006727 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006728 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006729
Glenn Kasten15e57982013-09-24 11:52:37 -07006730 lStatus = initCheck();
6731 if (lStatus != NO_ERROR) {
6732 ALOGE("createRecordTrack_l() audio driver not initialized");
6733 goto Exit;
6734 }
Eric Laurent81784c32012-11-19 14:55:58 -08006735
6736 { // scope for mLock
6737 Mutex::Autolock _l(mLock);
6738
6739 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006740 format, channelMask, frameCount,
6741 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006742 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006743
Glenn Kasten03003332013-08-06 15:40:54 -07006744 lStatus = track->initCheck();
6745 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006746 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006747 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006748 goto Exit;
6749 }
6750 mTracks.add(track);
6751
Eric Laurent05067782016-06-01 18:27:28 -07006752 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006753 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6754 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6755 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006756 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006757 }
Eric Laurent81784c32012-11-19 14:55:58 -08006758 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006759
Eric Laurent81784c32012-11-19 14:55:58 -08006760 lStatus = NO_ERROR;
6761
6762Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006763 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006764 return track;
6765}
6766
6767status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6768 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006769 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006770{
6771 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6772 sp<ThreadBase> strongMe = this;
6773 status_t status = NO_ERROR;
6774
6775 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006776 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006777 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006778 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006779 triggerSession,
6780 recordTrack->sessionId(),
6781 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006782 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006783 // Sync event can be cancelled by the trigger session if the track is not in a
6784 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006785 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006786 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006787 } else {
6788 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006789 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006790 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006791 }
6792 }
6793
6794 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006795 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006796 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006797 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6798 if (recordTrack->mState == TrackBase::PAUSING) {
6799 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006800 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006801 } else {
6802 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006803 }
6804 return status;
6805 }
6806
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006807 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6808 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6809 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006810 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006811 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006812 status_t status = NO_ERROR;
6813 if (recordTrack->isExternalTrack()) {
6814 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006815 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006816 mLock.lock();
6817 // FIXME should verify that recordTrack is still in mActiveTracks
6818 if (status != NO_ERROR) {
6819 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006820 recordTrack->clearSyncStartEvent();
6821 ALOGV("RecordThread::start error %d", status);
6822 return status;
6823 }
Eric Laurent81784c32012-11-19 14:55:58 -08006824 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006825 // Catch up with current buffer indices if thread is already running.
6826 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6827 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6828 // see previously buffered data before it called start(), but with greater risk of overrun.
6829
Andy Hung73c02e42015-03-29 01:13:58 -07006830 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006831 // clear any converter state as new data will be discontinuous
6832 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006833 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006834 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006835 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006836 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006837 ALOGV("Record failed to start");
6838 status = BAD_VALUE;
6839 goto startError;
6840 }
Eric Laurent81784c32012-11-19 14:55:58 -08006841 return status;
6842 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006843
Eric Laurent81784c32012-11-19 14:55:58 -08006844startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006845 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006846 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006847 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006848 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006849 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006850 return status;
6851}
6852
Eric Laurent81784c32012-11-19 14:55:58 -08006853void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6854{
6855 sp<SyncEvent> strongEvent = event.promote();
6856
6857 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006858 sp<RefBase> ptr = strongEvent->cookie().promote();
6859 if (ptr != 0) {
6860 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6861 recordTrack->handleSyncStartEvent(strongEvent);
6862 }
Eric Laurent81784c32012-11-19 14:55:58 -08006863 }
6864}
6865
Glenn Kastena8356f62013-07-25 14:37:52 -07006866bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006867 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006868 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006869 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006870 return false;
6871 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006872 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006873 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006874 // signal thread to stop
6875 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006876 // do not wait for mStartStopCond if exiting
6877 if (exitPending()) {
6878 return true;
6879 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006880 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006881 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006882 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006883 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006884 ALOGV("Record stopped OK");
6885 return true;
6886 }
6887 return false;
6888}
6889
Glenn Kasten0f11b512014-01-31 16:18:54 -08006890bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006891{
6892 return false;
6893}
6894
Glenn Kasten0f11b512014-01-31 16:18:54 -08006895status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006896{
6897#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6898 if (!isValidSyncEvent(event)) {
6899 return BAD_VALUE;
6900 }
6901
Glenn Kastend848eb42016-03-08 13:42:11 -08006902 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006903 status_t ret = NAME_NOT_FOUND;
6904
6905 Mutex::Autolock _l(mLock);
6906
6907 for (size_t i = 0; i < mTracks.size(); i++) {
6908 sp<RecordTrack> track = mTracks[i];
6909 if (eventSession == track->sessionId()) {
6910 (void) track->setSyncEvent(event);
6911 ret = NO_ERROR;
6912 }
6913 }
6914 return ret;
6915#else
6916 return BAD_VALUE;
6917#endif
6918}
6919
6920// destroyTrack_l() must be called with ThreadBase::mLock held
6921void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6922{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006923 track->terminate();
6924 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006925 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006926 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006927 removeTrack_l(track);
6928 }
6929}
6930
6931void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6932{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006933 String8 result;
6934 track->appendDump(result, false /* active */);
6935 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
6936
Eric Laurent81784c32012-11-19 14:55:58 -08006937 mTracks.remove(track);
6938 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006939 if (track->isFastTrack()) {
6940 ALOG_ASSERT(!mFastTrackAvail);
6941 mFastTrackAvail = true;
6942 }
Eric Laurent81784c32012-11-19 14:55:58 -08006943}
6944
6945void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6946{
6947 dumpInternals(fd, args);
6948 dumpTracks(fd, args);
6949 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006950 dprintf(fd, " Local log:\n");
6951 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08006952}
6953
6954void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6955{
Glenn Kasten44182c22015-03-05 17:12:23 -08006956 dumpBase(fd, args);
6957
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006958 AudioStreamIn *input = mInput;
6959 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6960 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6961 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006962 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006963 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006964 }
Andy Hungbfa64962017-06-12 14:43:19 -07006965
6966 if (input != nullptr) {
6967 dprintf(fd, " Hal stream dump:\n");
6968 (void)input->stream->dump(fd);
6969 }
6970
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006971 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006972 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006973
Glenn Kasten2f90c512015-12-02 11:40:09 -08006974 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6975 // while we are dumping it. It may be inconsistent, but it won't mutate!
6976 // This is a large object so we place it on the heap.
6977 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6978 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6979 copy->dump(fd);
6980 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006981}
6982
Glenn Kasten0f11b512014-01-31 16:18:54 -08006983void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006984{
Eric Laurent81784c32012-11-19 14:55:58 -08006985 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08006986 size_t numtracks = mTracks.size();
6987 size_t numactive = mActiveTracks.size();
6988 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006989 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006990 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08006991 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006992 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006993 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08006994 RecordTrack::appendDumpHeader(result);
6995 for (size_t i = 0; i < numtracks ; ++i) {
6996 sp<RecordTrack> track = mTracks[i];
6997 if (track != 0) {
6998 bool active = mActiveTracks.indexOf(track) >= 0;
6999 if (active) {
7000 numactiveseen++;
7001 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007002 result.append(prefix);
7003 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007004 }
Eric Laurent81784c32012-11-19 14:55:58 -08007005 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007006 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007007 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007008 }
7009
Marco Nelissenb2208842014-02-07 14:00:50 -08007010 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007011 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007012 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007013 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007014 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007015 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007016 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007017 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007018 result.append(prefix);
7019 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007020 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007021 }
Eric Laurent81784c32012-11-19 14:55:58 -08007022
7023 }
7024 write(fd, result.string(), result.size());
7025}
7026
Andy Hung73c02e42015-03-29 01:13:58 -07007027
7028void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7029{
7030 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7031 RecordThread *recordThread = (RecordThread *) threadBase.get();
7032 mRsmpInFront = recordThread->mRsmpInRear;
7033 mRsmpInUnrel = 0;
7034}
7035
7036void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7037 size_t *framesAvailable, bool *hasOverrun)
7038{
7039 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7040 RecordThread *recordThread = (RecordThread *) threadBase.get();
7041 const int32_t rear = recordThread->mRsmpInRear;
7042 const int32_t front = mRsmpInFront;
7043 const ssize_t filled = rear - front;
7044
7045 size_t framesIn;
7046 bool overrun = false;
7047 if (filled < 0) {
7048 // should not happen, but treat like a massive overrun and re-sync
7049 framesIn = 0;
7050 mRsmpInFront = rear;
7051 overrun = true;
7052 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7053 framesIn = (size_t) filled;
7054 } else {
7055 // client is not keeping up with server, but give it latest data
7056 framesIn = recordThread->mRsmpInFrames;
7057 mRsmpInFront = /* front = */ rear - framesIn;
7058 overrun = true;
7059 }
7060 if (framesAvailable != NULL) {
7061 *framesAvailable = framesIn;
7062 }
7063 if (hasOverrun != NULL) {
7064 *hasOverrun = overrun;
7065 }
7066}
7067
Eric Laurent81784c32012-11-19 14:55:58 -08007068// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007069status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007070 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007071{
Andy Hung73c02e42015-03-29 01:13:58 -07007072 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007073 if (threadBase == 0) {
7074 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007075 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007076 return NOT_ENOUGH_DATA;
7077 }
7078 RecordThread *recordThread = (RecordThread *) threadBase.get();
7079 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007080 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007081 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007082 // FIXME should not be P2 (don't want to increase latency)
7083 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007084 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007085 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007086 front &= recordThread->mRsmpInFramesP2 - 1;
7087 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007088 if (part1 > (size_t) filled) {
7089 part1 = filled;
7090 }
7091 size_t ask = buffer->frameCount;
7092 ALOG_ASSERT(ask > 0);
7093 if (part1 > ask) {
7094 part1 = ask;
7095 }
7096 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007097 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007098 buffer->raw = NULL;
7099 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007100 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007101 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007102 }
7103
Andy Hung57446612015-04-19 23:56:46 -07007104 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007105 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007106 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007107 return NO_ERROR;
7108}
7109
7110// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007111void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7112 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007113{
Glenn Kasten85948432013-08-19 12:09:05 -07007114 size_t stepCount = buffer->frameCount;
7115 if (stepCount == 0) {
7116 return;
7117 }
Andy Hung73c02e42015-03-29 01:13:58 -07007118 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7119 mRsmpInUnrel -= stepCount;
7120 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007121 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007122 buffer->frameCount = 0;
7123}
7124
Eric Laurentd8365c52017-07-16 15:27:05 -07007125void AudioFlinger::RecordThread::checkBtNrec()
7126{
7127 Mutex::Autolock _l(mLock);
7128 checkBtNrec_l();
7129}
7130
7131void AudioFlinger::RecordThread::checkBtNrec_l()
7132{
7133 // disable AEC and NS if the device is a BT SCO headset supporting those
7134 // pre processings
7135 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7136 mAudioFlinger->btNrecIsOff();
7137 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7138 for (size_t i = 0; i < mEffectChains.size(); i++) {
7139 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7140 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7141 }
7142 }
7143}
7144
Andy Hung97a893e2015-03-29 01:03:07 -07007145
Eric Laurent10351942014-05-08 18:49:52 -07007146bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7147 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007148{
7149 bool reconfig = false;
7150
Eric Laurent10351942014-05-08 18:49:52 -07007151 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007152
Eric Laurent10351942014-05-08 18:49:52 -07007153 audio_format_t reqFormat = mFormat;
7154 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007155 // 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 -07007156 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7157
7158 AudioParameter param = AudioParameter(keyValuePair);
7159 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007160
7161 // scope for AutoPark extends to end of method
7162 AutoPark<FastCapture> park(mFastCapture);
7163
Eric Laurent10351942014-05-08 18:49:52 -07007164 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7165 // channel count change can be requested. Do we mandate the first client defines the
7166 // HAL sampling rate and channel count or do we allow changes on the fly?
7167 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7168 samplingRate = value;
7169 reconfig = true;
7170 }
7171 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007172 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007173 status = BAD_VALUE;
7174 } else {
7175 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007176 reconfig = true;
7177 }
Eric Laurent10351942014-05-08 18:49:52 -07007178 }
7179 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7180 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007181 if (!audio_is_input_channel(mask) ||
7182 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007183 status = BAD_VALUE;
7184 } else {
7185 channelMask = mask;
7186 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007187 }
Eric Laurent10351942014-05-08 18:49:52 -07007188 }
7189 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7190 // do not accept frame count changes if tracks are open as the track buffer
7191 // size depends on frame count and correct behavior would not be guaranteed
7192 // if frame count is changed after track creation
7193 if (mActiveTracks.size() > 0) {
7194 status = INVALID_OPERATION;
7195 } else {
7196 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007197 }
Eric Laurent10351942014-05-08 18:49:52 -07007198 }
7199 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7200 // forward device change to effects that have requested to be
7201 // aware of attached audio device.
7202 for (size_t i = 0; i < mEffectChains.size(); i++) {
7203 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007204 }
Eric Laurent81784c32012-11-19 14:55:58 -08007205
Eric Laurent10351942014-05-08 18:49:52 -07007206 // store input device and output device but do not forward output device to audio HAL.
7207 // Note that status is ignored by the caller for output device
7208 // (see AudioFlinger::setParameters()
7209 if (audio_is_output_devices(value)) {
7210 mOutDevice = value;
7211 status = BAD_VALUE;
7212 } else {
7213 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007214 if (value != AUDIO_DEVICE_NONE) {
7215 mPrevInDevice = value;
7216 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007217 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007218 }
Eric Laurent10351942014-05-08 18:49:52 -07007219 }
7220 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7221 mAudioSource != (audio_source_t)value) {
7222 // forward device change to effects that have requested to be
7223 // aware of attached audio device.
7224 for (size_t i = 0; i < mEffectChains.size(); i++) {
7225 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007226 }
Eric Laurent10351942014-05-08 18:49:52 -07007227 mAudioSource = (audio_source_t)value;
7228 }
Glenn Kastene198c362013-08-13 09:13:36 -07007229
Eric Laurent10351942014-05-08 18:49:52 -07007230 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007231 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007232 if (status == INVALID_OPERATION) {
7233 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007234 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007235 }
7236 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007237 if (status == BAD_VALUE) {
7238 uint32_t sRate;
7239 audio_channel_mask_t channelMask;
7240 audio_format_t format;
7241 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7242 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7243 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7244 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7245 status = NO_ERROR;
7246 }
Eric Laurent81784c32012-11-19 14:55:58 -08007247 }
Eric Laurent10351942014-05-08 18:49:52 -07007248 if (status == NO_ERROR) {
7249 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007250 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007251 }
7252 }
Eric Laurent81784c32012-11-19 14:55:58 -08007253 }
Eric Laurent10351942014-05-08 18:49:52 -07007254
Eric Laurent81784c32012-11-19 14:55:58 -08007255 return reconfig;
7256}
7257
7258String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7259{
Eric Laurent81784c32012-11-19 14:55:58 -08007260 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007261 if (initCheck() == NO_ERROR) {
7262 String8 out_s8;
7263 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7264 return out_s8;
7265 }
Eric Laurent81784c32012-11-19 14:55:58 -08007266 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007267 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007268}
7269
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007270void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007271 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7272
7273 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007274
7275 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007276 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007277 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007278 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007279 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007280 desc->mChannelMask = mChannelMask;
7281 desc->mSamplingRate = mSampleRate;
7282 desc->mFormat = mFormat;
7283 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007284 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007285 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007286 break;
7287
Eric Laurent73e26b62015-04-27 16:55:58 -07007288 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007289 default:
7290 break;
7291 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007292 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007293}
7294
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007295void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007296{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007297 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7298 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007299 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007300 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007301 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007302 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7303 result = mInput->stream->getFrameSize(&mFrameSize);
7304 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7305 result = mInput->stream->getBufferSize(&mBufferSize);
7306 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007307 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007308 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7309 "mBufferSize=%lld, mFrameCount=%lld",
7310 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7311 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007312 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007313 // 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 -07007314 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007315 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007316 // A larger value should allow more old data to be read after a track calls start(),
7317 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007318 //
7319 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007320 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007321 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007322 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007323 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007324
7325 // TODO optimize audio capture buffer sizes ...
7326 // Here we calculate the size of the sliding buffer used as a source
7327 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7328 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7329 // be better to have it derived from the pipe depth in the long term.
7330 // The current value is higher than necessary. However it should not add to latency.
7331
Glenn Kasten85948432013-08-19 12:09:05 -07007332 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007333 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7334 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007335 // if posix_memalign fails, will segv here.
7336 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007337
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007338 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7339 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007340}
7341
Glenn Kasten5f972c02014-01-13 09:59:31 -08007342uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007343{
7344 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007345 uint32_t result;
7346 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7347 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007348 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007349 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007350}
7351
Eric Laurent4c415062016-06-17 16:14:16 -07007352// hasAudioSession_l() must be called with ThreadBase::mLock held
7353uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007354{
Eric Laurent81784c32012-11-19 14:55:58 -08007355 uint32_t result = 0;
7356 if (getEffectChain_l(sessionId) != 0) {
7357 result = EFFECT_SESSION;
7358 }
7359
7360 for (size_t i = 0; i < mTracks.size(); ++i) {
7361 if (sessionId == mTracks[i]->sessionId()) {
7362 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007363 if (mTracks[i]->isFastTrack()) {
7364 result |= FAST_SESSION;
7365 }
Eric Laurent81784c32012-11-19 14:55:58 -08007366 break;
7367 }
7368 }
7369
7370 return result;
7371}
7372
Glenn Kastend848eb42016-03-08 13:42:11 -08007373KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007374{
Glenn Kastend848eb42016-03-08 13:42:11 -08007375 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007376 Mutex::Autolock _l(mLock);
7377 for (size_t j = 0; j < mTracks.size(); ++j) {
7378 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007379 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007380 if (ids.indexOfKey(sessionId) < 0) {
7381 ids.add(sessionId, true);
7382 }
7383 }
7384 return ids;
7385}
7386
7387AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7388{
7389 Mutex::Autolock _l(mLock);
7390 AudioStreamIn *input = mInput;
7391 mInput = NULL;
7392 return input;
7393}
7394
7395// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007396sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007397{
7398 if (mInput == NULL) {
7399 return NULL;
7400 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007401 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007402}
7403
7404status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7405{
7406 // only one chain per input thread
7407 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007408 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007409 return INVALID_OPERATION;
7410 }
7411 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007412 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007413 chain->setInBuffer(NULL);
7414 chain->setOutBuffer(NULL);
7415
7416 checkSuspendOnAddEffectChain_l(chain);
7417
Eric Laurent1b928682014-10-02 19:41:47 -07007418 // make sure enabled pre processing effects state is communicated to the HAL as we
7419 // just moved them to a new input stream.
7420 chain->syncHalEffectsState();
7421
Eric Laurent81784c32012-11-19 14:55:58 -08007422 mEffectChains.add(chain);
7423
7424 return NO_ERROR;
7425}
7426
7427size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7428{
7429 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7430 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007431 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007432 chain.get(), mEffectChains.size(), this);
7433 if (mEffectChains.size() == 1) {
7434 mEffectChains.removeAt(0);
7435 }
7436 return 0;
7437}
7438
Eric Laurent1c333e22014-05-20 10:48:17 -07007439status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7440 audio_patch_handle_t *handle)
7441{
7442 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007443
7444 // store new device and send to effects
7445 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007446 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007447 for (size_t i = 0; i < mEffectChains.size(); i++) {
7448 mEffectChains[i]->setDevice_l(mInDevice);
7449 }
7450
Eric Laurentd8365c52017-07-16 15:27:05 -07007451 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007452
7453 // store new source and send to effects
7454 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7455 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007456 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007457 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007458 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007459 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007460
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007461 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007462 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7463 status = hwDevice->createAudioPatch(patch->num_sources,
7464 patch->sources,
7465 patch->num_sinks,
7466 patch->sinks,
7467 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007468 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007469 char *address;
7470 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7471 address = audio_device_address_to_parameter(
7472 patch->sources[0].ext.device.type,
7473 patch->sources[0].ext.device.address);
7474 } else {
7475 address = (char *)calloc(1, 1);
7476 }
7477 AudioParameter param = AudioParameter(String8(address));
7478 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007479 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007480 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007481 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007482 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007483 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007484 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007485 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007486
Eric Laurente8726fe2015-06-26 09:39:24 -07007487 if (mInDevice != mPrevInDevice) {
7488 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7489 mPrevInDevice = mInDevice;
7490 }
Eric Laurent296fb132015-05-01 11:38:42 -07007491
Eric Laurent1c333e22014-05-20 10:48:17 -07007492 return status;
7493}
7494
7495status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7496{
7497 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007498
7499 mInDevice = AUDIO_DEVICE_NONE;
7500
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007501 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007502 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7503 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007504 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007505 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007506 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007507 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007508 }
7509 return status;
7510}
7511
Eric Laurent83b88082014-06-20 18:31:16 -07007512void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7513{
7514 Mutex::Autolock _l(mLock);
7515 mTracks.add(record);
7516}
7517
7518void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7519{
7520 Mutex::Autolock _l(mLock);
7521 destroyTrack_l(record);
7522}
7523
7524void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7525{
7526 ThreadBase::getAudioPortConfig(config);
7527 config->role = AUDIO_PORT_ROLE_SINK;
7528 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7529 config->ext.mix.usecase.source = mAudioSource;
7530}
Eric Laurent1c333e22014-05-20 10:48:17 -07007531
Eric Laurent6acd1d42017-01-04 14:23:29 -08007532// ----------------------------------------------------------------------------
7533// Mmap
7534// ----------------------------------------------------------------------------
7535
7536AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7537 : mThread(thread)
7538{
Phil Burk9fabbf82017-08-03 12:02:00 -07007539 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007540}
7541
7542AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7543{
Phil Burk9fabbf82017-08-03 12:02:00 -07007544 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007545}
7546
7547status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7548 struct audio_mmap_buffer_info *info)
7549{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007550 return mThread->createMmapBuffer(minSizeFrames, info);
7551}
7552
7553status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7554{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007555 return mThread->getMmapPosition(position);
7556}
7557
Eric Laurenta54f1282017-07-01 19:39:32 -07007558status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007559 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007560
7561{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007562 return mThread->start(client, handle);
7563}
7564
7565status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7566{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007567 return mThread->stop(handle);
7568}
7569
Eric Laurent18b57012017-02-13 16:23:52 -08007570status_t AudioFlinger::MmapThreadHandle::standby()
7571{
Eric Laurent18b57012017-02-13 16:23:52 -08007572 return mThread->standby();
7573}
7574
Eric Laurent6acd1d42017-01-04 14:23:29 -08007575
7576AudioFlinger::MmapThread::MmapThread(
7577 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7578 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7579 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7580 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007581 mSessionId(AUDIO_SESSION_NONE),
7582 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007583 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7584 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007585{
Eric Laurent18b57012017-02-13 16:23:52 -08007586 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007587 readHalParameters_l();
7588}
7589
7590AudioFlinger::MmapThread::~MmapThread()
7591{
Eric Laurent18b57012017-02-13 16:23:52 -08007592 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007593}
7594
7595void AudioFlinger::MmapThread::onFirstRef()
7596{
7597 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7598}
7599
7600void AudioFlinger::MmapThread::disconnect()
7601{
7602 for (const sp<MmapTrack> &t : mActiveTracks) {
7603 stop(t->portId());
7604 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007605 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007606 if (isOutput()) {
7607 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7608 } else {
7609 AudioSystem::releaseInput(mId, mSessionId);
7610 }
7611}
7612
7613
7614void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7615 audio_stream_type_t streamType __unused,
7616 audio_session_t sessionId,
7617 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007618 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007619 audio_port_handle_t portId)
7620{
7621 mAttr = *attr;
7622 mSessionId = sessionId;
7623 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007624 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007625 mPortId = portId;
7626}
7627
7628status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7629 struct audio_mmap_buffer_info *info)
7630{
7631 if (mHalStream == 0) {
7632 return NO_INIT;
7633 }
Eric Laurent18b57012017-02-13 16:23:52 -08007634 mStandby = true;
7635 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007636 return mHalStream->createMmapBuffer(minSizeFrames, info);
7637}
7638
7639status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7640{
7641 if (mHalStream == 0) {
7642 return NO_INIT;
7643 }
7644 return mHalStream->getMmapPosition(position);
7645}
7646
Eric Laurenta54f1282017-07-01 19:39:32 -07007647status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007648 audio_port_handle_t *handle)
7649{
Eric Laurenta54f1282017-07-01 19:39:32 -07007650 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7651 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007652 if (mHalStream == 0) {
7653 return NO_INIT;
7654 }
7655
7656 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007657
Eric Laurenta54f1282017-07-01 19:39:32 -07007658 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007659 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007660 ret = mHalStream->start();
7661 if (ret != NO_ERROR) {
7662 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7663 return ret;
7664 }
Eric Laurent18b57012017-02-13 16:23:52 -08007665 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007666 return NO_ERROR;
7667 }
7668
Phil Burk81ad5ec2017-09-01 10:45:41 -07007669 if (!isOutput() && !recordingAllowed(client.packageName, client.clientPid, client.clientUid)) {
7670 return PERMISSION_DENIED;
7671 }
7672
Eric Laurenta54f1282017-07-01 19:39:32 -07007673 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7674
7675 audio_io_handle_t io = mId;
7676 if (isOutput()) {
7677 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7678 config.sample_rate = mSampleRate;
7679 config.channel_mask = mChannelMask;
7680 config.format = mFormat;
7681 audio_stream_type_t stream = streamType();
7682 audio_output_flags_t flags =
7683 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007684 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007685 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7686 mSessionId,
7687 &stream,
7688 client.clientUid,
7689 &config,
7690 flags,
7691 &deviceId,
7692 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007693 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007694 audio_config_base_t config;
7695 config.sample_rate = mSampleRate;
7696 config.channel_mask = mChannelMask;
7697 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007698 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007699 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7700 mSessionId,
7701 client.clientPid,
7702 client.clientUid,
7703 &config,
7704 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7705 &deviceId,
7706 &portId);
7707 }
7708 // APM should not chose a different input or output stream for the same set of attributes
7709 // and audo configuration
7710 if (ret != NO_ERROR || io != mId) {
7711 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7712 __FUNCTION__, ret, io, mId);
7713 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007714 }
7715
7716 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007717 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007718 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007719 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007720 }
7721
7722 // abort if start is rejected by audio policy manager
7723 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007724 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007725 if (mActiveTracks.size() != 0) {
7726 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007727 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007728 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007729 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007730 }
Eric Laurent18b57012017-02-13 16:23:52 -08007731 } else {
7732 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007733 }
7734 return PERMISSION_DENIED;
7735 }
7736
Eric Laurenta54f1282017-07-01 19:39:32 -07007737 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7738 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007739
7740 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007741 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007742 if (chain != 0) {
7743 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7744 chain->incTrackCnt();
7745 chain->incActiveTrackCnt();
7746 }
7747
7748 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007749 broadcast_l();
7750
Eric Laurenta54f1282017-07-01 19:39:32 -07007751 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007752
7753 return NO_ERROR;
7754}
7755
7756status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7757{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007758 ALOGV("%s handle %d", __FUNCTION__, handle);
7759
7760 if (mHalStream == 0) {
7761 return NO_INIT;
7762 }
7763
Eric Laurenta54f1282017-07-01 19:39:32 -07007764 if (handle == mPortId) {
7765 mHalStream->stop();
7766 return NO_ERROR;
7767 }
7768
Eric Laurent6acd1d42017-01-04 14:23:29 -08007769 sp<MmapTrack> track;
7770 for (const sp<MmapTrack> &t : mActiveTracks) {
7771 if (handle == t->portId()) {
7772 track = t;
7773 break;
7774 }
7775 }
7776 if (track == 0) {
7777 return BAD_VALUE;
7778 }
7779
7780 mActiveTracks.remove(track);
7781
7782 if (isOutput()) {
7783 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007784 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007785 } else {
7786 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007787 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007788 }
7789
7790 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7791 if (chain != 0) {
7792 chain->decActiveTrackCnt();
7793 chain->decTrackCnt();
7794 }
7795
7796 broadcast_l();
7797
Eric Laurent6acd1d42017-01-04 14:23:29 -08007798 return NO_ERROR;
7799}
7800
Eric Laurent18b57012017-02-13 16:23:52 -08007801status_t AudioFlinger::MmapThread::standby()
7802{
7803 ALOGV("%s", __FUNCTION__);
7804
7805 if (mHalStream == 0) {
7806 return NO_INIT;
7807 }
7808 if (mActiveTracks.size() != 0) {
7809 return INVALID_OPERATION;
7810 }
7811 mHalStream->standby();
7812 mStandby = true;
7813 releaseWakeLock();
7814 return NO_ERROR;
7815}
7816
Eric Laurent6acd1d42017-01-04 14:23:29 -08007817
7818void AudioFlinger::MmapThread::readHalParameters_l()
7819{
7820 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7821 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7822 mFormat = mHALFormat;
7823 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7824 result = mHalStream->getFrameSize(&mFrameSize);
7825 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7826 result = mHalStream->getBufferSize(&mBufferSize);
7827 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7828 mFrameCount = mBufferSize / mFrameSize;
7829}
7830
7831bool AudioFlinger::MmapThread::threadLoop()
7832{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007833 checkSilentMode_l();
7834
7835 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7836
7837 while (!exitPending())
7838 {
7839 Mutex::Autolock _l(mLock);
7840 Vector< sp<EffectChain> > effectChains;
7841
7842 if (mSignalPending) {
7843 // A signal was raised while we were unlocked
7844 mSignalPending = false;
7845 } else {
7846 if (mConfigEvents.isEmpty()) {
7847 // we're about to wait, flush the binder command buffer
7848 IPCThreadState::self()->flushCommands();
7849
7850 if (exitPending()) {
7851 break;
7852 }
7853
Eric Laurent6acd1d42017-01-04 14:23:29 -08007854 // wait until we have something to do...
7855 ALOGV("%s going to sleep", myName.string());
7856 mWaitWorkCV.wait(mLock);
7857 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007858
7859 checkSilentMode_l();
7860
7861 continue;
7862 }
7863 }
7864
7865 processConfigEvents_l();
7866
7867 processVolume_l();
7868
7869 checkInvalidTracks_l();
7870
7871 mActiveTracks.updatePowerState(this);
7872
7873 lockEffectChains_l(effectChains);
7874 for (size_t i = 0; i < effectChains.size(); i ++) {
7875 effectChains[i]->process_l();
7876 }
7877 // enable changes in effect chain
7878 unlockEffectChains(effectChains);
7879 // Effect chains will be actually deleted here if they were removed from
7880 // mEffectChains list during mixing or effects processing
7881 }
7882
7883 threadLoop_exit();
7884
7885 if (!mStandby) {
7886 threadLoop_standby();
7887 mStandby = true;
7888 }
7889
Eric Laurent6acd1d42017-01-04 14:23:29 -08007890 ALOGV("Thread %p type %d exiting", this, mType);
7891 return false;
7892}
7893
7894// checkForNewParameter_l() must be called with ThreadBase::mLock held
7895bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7896 status_t& status)
7897{
7898 AudioParameter param = AudioParameter(keyValuePair);
7899 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07007900 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007901 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007902 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007903 // forward device change to effects that have requested to be
7904 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07007905 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007906 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007907 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007908 }
7909 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007910 if (audio_is_output_devices(device)) {
7911 mOutDevice = device;
7912 if (!isOutput()) {
7913 sendToHal = false;
7914 }
7915 } else {
7916 mInDevice = device;
7917 if (device != AUDIO_DEVICE_NONE) {
7918 mPrevInDevice = value;
7919 }
7920 // TODO: implement and call checkBtNrec_l();
7921 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007922 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007923 if (sendToHal) {
7924 status = mHalStream->setParameters(keyValuePair);
7925 } else {
7926 status = NO_ERROR;
7927 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007928
7929 return false;
7930}
7931
7932String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7933{
7934 Mutex::Autolock _l(mLock);
7935 String8 out_s8;
7936 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7937 return out_s8;
7938 }
7939 return String8();
7940}
7941
7942void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7943 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7944
7945 desc->mIoHandle = mId;
7946
7947 switch (event) {
7948 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007949 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08007950 case AUDIO_INPUT_CONFIG_CHANGED:
7951 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007952 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08007953 case AUDIO_OUTPUT_CONFIG_CHANGED:
7954 desc->mPatch = mPatch;
7955 desc->mChannelMask = mChannelMask;
7956 desc->mSamplingRate = mSampleRate;
7957 desc->mFormat = mFormat;
7958 desc->mFrameCount = mFrameCount;
7959 desc->mFrameCountHAL = mFrameCount;
7960 desc->mLatency = 0;
7961 break;
7962
7963 case AUDIO_INPUT_CLOSED:
7964 case AUDIO_OUTPUT_CLOSED:
7965 default:
7966 break;
7967 }
7968 mAudioFlinger->ioConfigChanged(event, desc, pid);
7969}
7970
7971status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7972 audio_patch_handle_t *handle)
7973{
7974 status_t status = NO_ERROR;
7975
7976 // store new device and send to effects
7977 audio_devices_t type = AUDIO_DEVICE_NONE;
7978 audio_port_handle_t deviceId;
7979 if (isOutput()) {
7980 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7981 type |= patch->sinks[i].ext.device.type;
7982 }
7983 deviceId = patch->sinks[0].id;
7984 } else {
7985 type = patch->sources[0].ext.device.type;
7986 deviceId = patch->sources[0].id;
7987 }
7988
7989 for (size_t i = 0; i < mEffectChains.size(); i++) {
7990 mEffectChains[i]->setDevice_l(type);
7991 }
7992
7993 if (isOutput()) {
7994 mOutDevice = type;
7995 } else {
7996 mInDevice = type;
7997 // store new source and send to effects
7998 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7999 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8000 for (size_t i = 0; i < mEffectChains.size(); i++) {
8001 mEffectChains[i]->setAudioSource_l(mAudioSource);
8002 }
8003 }
8004 }
8005
8006 if (mAudioHwDev->supportsAudioPatches()) {
8007 status = mHalDevice->createAudioPatch(patch->num_sources,
8008 patch->sources,
8009 patch->num_sinks,
8010 patch->sinks,
8011 handle);
8012 } else {
8013 char *address;
8014 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8015 //FIXME: we only support address on first sink with HAL version < 3.0
8016 address = audio_device_address_to_parameter(
8017 patch->sinks[0].ext.device.type,
8018 patch->sinks[0].ext.device.address);
8019 } else {
8020 address = (char *)calloc(1, 1);
8021 }
8022 AudioParameter param = AudioParameter(String8(address));
8023 free(address);
8024 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8025 if (!isOutput()) {
8026 param.addInt(String8(AudioParameter::keyInputSource),
8027 (int)patch->sinks[0].ext.mix.usecase.source);
8028 }
8029 status = mHalStream->setParameters(param.toString());
8030 *handle = AUDIO_PATCH_HANDLE_NONE;
8031 }
8032
8033 if (isOutput() && mPrevOutDevice != mOutDevice) {
8034 mPrevOutDevice = type;
8035 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008036 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008037 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008038 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008039 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008040 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008041 }
8042 if (!isOutput() && mPrevInDevice != mInDevice) {
8043 mPrevInDevice = type;
8044 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008045 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008046 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008047 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008048 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008049 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008050 }
8051 return status;
8052}
8053
8054status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8055{
8056 status_t status = NO_ERROR;
8057
8058 mInDevice = AUDIO_DEVICE_NONE;
8059
8060 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8061 supportsAudioPatches : false;
8062
8063 if (supportsAudioPatches) {
8064 status = mHalDevice->releaseAudioPatch(handle);
8065 } else {
8066 AudioParameter param;
8067 param.addInt(String8(AudioParameter::keyRouting), 0);
8068 status = mHalStream->setParameters(param.toString());
8069 }
8070 return status;
8071}
8072
8073void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8074{
8075 ThreadBase::getAudioPortConfig(config);
8076 if (isOutput()) {
8077 config->role = AUDIO_PORT_ROLE_SOURCE;
8078 config->ext.mix.hw_module = mAudioHwDev->handle();
8079 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8080 } else {
8081 config->role = AUDIO_PORT_ROLE_SINK;
8082 config->ext.mix.hw_module = mAudioHwDev->handle();
8083 config->ext.mix.usecase.source = mAudioSource;
8084 }
8085}
8086
8087status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8088{
8089 audio_session_t session = chain->sessionId();
8090
8091 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8092 // Attach all tracks with same session ID to this chain.
8093 // indicate all active tracks in the chain
8094 for (const sp<MmapTrack> &track : mActiveTracks) {
8095 if (session == track->sessionId()) {
8096 chain->incTrackCnt();
8097 chain->incActiveTrackCnt();
8098 }
8099 }
8100
8101 chain->setThread(this);
8102 chain->setInBuffer(nullptr);
8103 chain->setOutBuffer(nullptr);
8104 chain->syncHalEffectsState();
8105
8106 mEffectChains.add(chain);
8107 checkSuspendOnAddEffectChain_l(chain);
8108 return NO_ERROR;
8109}
8110
8111size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8112{
8113 audio_session_t session = chain->sessionId();
8114
8115 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8116
8117 for (size_t i = 0; i < mEffectChains.size(); i++) {
8118 if (chain == mEffectChains[i]) {
8119 mEffectChains.removeAt(i);
8120 // detach all active tracks from the chain
8121 // detach all tracks with same session ID from this chain
8122 for (const sp<MmapTrack> &track : mActiveTracks) {
8123 if (session == track->sessionId()) {
8124 chain->decActiveTrackCnt();
8125 chain->decTrackCnt();
8126 }
8127 }
8128 break;
8129 }
8130 }
8131 return mEffectChains.size();
8132}
8133
8134// hasAudioSession_l() must be called with ThreadBase::mLock held
8135uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8136{
8137 uint32_t result = 0;
8138 if (getEffectChain_l(sessionId) != 0) {
8139 result = EFFECT_SESSION;
8140 }
8141
8142 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8143 sp<MmapTrack> track = mActiveTracks[i];
8144 if (sessionId == track->sessionId()) {
8145 result |= TRACK_SESSION;
8146 if (track->isFastTrack()) {
8147 result |= FAST_SESSION;
8148 }
8149 break;
8150 }
8151 }
8152
8153 return result;
8154}
8155
8156void AudioFlinger::MmapThread::threadLoop_standby()
8157{
8158 mHalStream->standby();
8159}
8160
8161void AudioFlinger::MmapThread::threadLoop_exit()
8162{
Phil Burk7dce7282017-09-27 13:51:41 -07008163 // Do not call callback->onTearDown() because it is redundant for thread exit
8164 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008165}
8166
8167status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8168{
8169 return BAD_VALUE;
8170}
8171
8172bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8173{
8174 return false;
8175}
8176
8177status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8178 const effect_descriptor_t *desc, audio_session_t sessionId)
8179{
8180 // No global effect sessions on mmap threads
8181 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8182 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8183 desc->name, mThreadName);
8184 return BAD_VALUE;
8185 }
8186
8187 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8188 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8189 desc->name);
8190 return BAD_VALUE;
8191 }
8192 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008193 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8194 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008195 return BAD_VALUE;
8196 }
8197
8198 // Only allow effects without processing load or latency
8199 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8200 return BAD_VALUE;
8201 }
8202
8203 return NO_ERROR;
8204
8205}
8206
8207void AudioFlinger::MmapThread::checkInvalidTracks_l()
8208{
8209 for (const sp<MmapTrack> &track : mActiveTracks) {
8210 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008211 sp<MmapStreamCallback> callback = mCallback.promote();
8212 if (callback != 0) {
8213 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008214 }
8215 break;
8216 }
8217 }
8218}
8219
8220void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8221{
8222 dumpInternals(fd, args);
8223 dumpTracks(fd, args);
8224 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008225 dprintf(fd, " Local log:\n");
8226 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008227}
8228
8229void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8230{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008231 dumpBase(fd, args);
8232
8233 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8234 mAttr.content_type, mAttr.usage, mAttr.source);
8235 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8236 if (mActiveTracks.size() == 0) {
8237 dprintf(fd, " No active clients\n");
8238 }
8239}
8240
8241void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8242{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008243 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008244 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008245 dprintf(fd, " %zu Tracks\n", numtracks);
8246 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008247 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008248 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008249 MmapTrack::appendDumpHeader(result);
8250 for (size_t i = 0; i < numtracks ; ++i) {
8251 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008252 result.append(prefix);
8253 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008254 }
8255 } else {
8256 dprintf(fd, "\n");
8257 }
8258 write(fd, result.string(), result.size());
8259}
8260
8261AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8262 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8263 AudioHwDevice *hwDev, AudioStreamOut *output,
8264 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8265 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8266 mStreamType(AUDIO_STREAM_MUSIC),
8267 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8268{
8269 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8270 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8271 mMasterVolume = audioFlinger->masterVolume_l();
8272 mMasterMute = audioFlinger->masterMute_l();
8273 if (mAudioHwDev) {
8274 if (mAudioHwDev->canSetMasterVolume()) {
8275 mMasterVolume = 1.0;
8276 }
8277
8278 if (mAudioHwDev->canSetMasterMute()) {
8279 mMasterMute = false;
8280 }
8281 }
8282}
8283
8284void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8285 audio_stream_type_t streamType,
8286 audio_session_t sessionId,
8287 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008288 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008289 audio_port_handle_t portId)
8290{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008291 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008292 mStreamType = streamType;
8293}
8294
8295AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8296{
8297 Mutex::Autolock _l(mLock);
8298 AudioStreamOut *output = mOutput;
8299 mOutput = NULL;
8300 return output;
8301}
8302
8303void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8304{
8305 Mutex::Autolock _l(mLock);
8306 // Don't apply master volume in SW if our HAL can do it for us.
8307 if (mAudioHwDev &&
8308 mAudioHwDev->canSetMasterVolume()) {
8309 mMasterVolume = 1.0;
8310 } else {
8311 mMasterVolume = value;
8312 }
8313}
8314
8315void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8316{
8317 Mutex::Autolock _l(mLock);
8318 // Don't apply master mute in SW if our HAL can do it for us.
8319 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8320 mMasterMute = false;
8321 } else {
8322 mMasterMute = muted;
8323 }
8324}
8325
8326void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8327{
8328 Mutex::Autolock _l(mLock);
8329 if (stream == mStreamType) {
8330 mStreamVolume = value;
8331 broadcast_l();
8332 }
8333}
8334
8335float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8336{
8337 Mutex::Autolock _l(mLock);
8338 if (stream == mStreamType) {
8339 return mStreamVolume;
8340 }
8341 return 0.0f;
8342}
8343
8344void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8345{
8346 Mutex::Autolock _l(mLock);
8347 if (stream == mStreamType) {
8348 mStreamMute= muted;
8349 broadcast_l();
8350 }
8351}
8352
8353void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8354{
8355 Mutex::Autolock _l(mLock);
8356 if (streamType == mStreamType) {
8357 for (const sp<MmapTrack> &track : mActiveTracks) {
8358 track->invalidate();
8359 }
8360 broadcast_l();
8361 }
8362}
8363
8364void AudioFlinger::MmapPlaybackThread::processVolume_l()
8365{
8366 float volume;
8367
8368 if (mMasterMute || mStreamMute) {
8369 volume = 0;
8370 } else {
8371 volume = mMasterVolume * mStreamVolume;
8372 }
8373
8374 if (volume != mHalVolFloat) {
8375 mHalVolFloat = volume;
8376
8377 // Convert volumes from float to 8.24
8378 uint32_t vol = (uint32_t)(volume * (1 << 24));
8379
8380 // Delegate volume control to effect in track effect chain if needed
8381 // only one effect chain can be present on DirectOutputThread, so if
8382 // there is one, the track is connected to it
8383 if (!mEffectChains.isEmpty()) {
8384 mEffectChains[0]->setVolume_l(&vol, &vol);
8385 volume = (float)vol / (1 << 24);
8386 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008387 // Try to use HW volume control and fall back to SW control if not implemented
8388 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8389 sp<MmapStreamCallback> callback = mCallback.promote();
8390 if (callback != 0) {
8391 int channelCount;
8392 if (isOutput()) {
8393 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8394 } else {
8395 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8396 }
8397 Vector<float> values;
8398 for (int i = 0; i < channelCount; i++) {
8399 values.add(volume);
8400 }
8401 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008402 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008403 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008404 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008405 }
8406 }
8407}
8408
8409void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8410{
8411 if (!mMasterMute) {
8412 char value[PROPERTY_VALUE_MAX];
8413 if (property_get("ro.audio.silent", value, "0") > 0) {
8414 char *endptr;
8415 unsigned long ul = strtoul(value, &endptr, 0);
8416 if (*endptr == '\0' && ul != 0) {
8417 ALOGD("Silence is golden");
8418 // The setprop command will not allow a property to be changed after
8419 // the first time it is set, so we don't have to worry about un-muting.
8420 setMasterMute_l(true);
8421 }
8422 }
8423 }
8424}
8425
8426void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8427{
8428 MmapThread::dumpInternals(fd, args);
8429
Glenn Kastend3bb6452016-12-05 18:14:37 -08008430 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8431 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008432 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8433}
8434
8435AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8436 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8437 AudioHwDevice *hwDev, AudioStreamIn *input,
8438 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8439 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8440 mInput(input)
8441{
8442 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8443 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8444}
8445
8446AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8447{
8448 Mutex::Autolock _l(mLock);
8449 AudioStreamIn *input = mInput;
8450 mInput = NULL;
8451 return input;
8452}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008453} // namespace android