blob: a67acd64d467a5cf710aeeba8665e6904f82643a [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 Kasten9f81de32014-07-27 15:02:23 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
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
1172 switch (mType) {
1173 case MIXER: {
1174 // Reject any effect on mixer multichannel sinks.
1175 // TODO: fix both format and multichannel issues with effects.
1176 if (mChannelCount != FCC_2) {
1177 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1178 " thread %s", desc->name, mChannelCount, mThreadName);
1179 return BAD_VALUE;
1180 }
1181 audio_output_flags_t flags = mOutput->flags;
1182 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1184 // global effects are applied only to non fast tracks if they are SW
1185 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1186 break;
1187 }
1188 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1189 // only post processing on output stage session
1190 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1191 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1192 " on output stage session", desc->name);
1193 return BAD_VALUE;
1194 }
1195 } else {
1196 // no restriction on effects applied on non fast tracks
1197 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1198 break;
1199 }
1200 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001201
1202 // always allow effects without processing load or latency
1203 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1204 break;
1205 }
Eric Laurent4c415062016-06-17 16:14:16 -07001206 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1207 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1208 desc->name);
1209 return BAD_VALUE;
1210 }
1211 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1212 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1213 " in fast mode", desc->name);
1214 return BAD_VALUE;
1215 }
1216 }
1217 } break;
1218 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001219 // nothing actionable on offload threads, if the effect:
1220 // - is offloadable: the effect can be created
1221 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1222 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001223 break;
1224 case DIRECT:
1225 // Reject any effect on Direct output threads for now, since the format of
1226 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1227 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1228 desc->name, mThreadName);
1229 return BAD_VALUE;
1230 case DUPLICATING:
1231 // Reject any effect on mixer multichannel sinks.
1232 // TODO: fix both format and multichannel issues with effects.
1233 if (mChannelCount != FCC_2) {
1234 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1235 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1236 return BAD_VALUE;
1237 }
1238 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1239 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1240 " thread %s", desc->name, mThreadName);
1241 return BAD_VALUE;
1242 }
1243 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1244 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1245 " DUPLICATING thread %s", desc->name, mThreadName);
1246 return BAD_VALUE;
1247 }
1248 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1249 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1250 " DUPLICATING thread %s", desc->name, mThreadName);
1251 return BAD_VALUE;
1252 }
1253 break;
1254 default:
1255 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1256 }
1257
1258 return NO_ERROR;
1259}
1260
Eric Laurent81784c32012-11-19 14:55:58 -08001261// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1262sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1263 const sp<AudioFlinger::Client>& client,
1264 const sp<IEffectClient>& effectClient,
1265 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001266 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001267 effect_descriptor_t *desc,
1268 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001269 status_t *status,
1270 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001271{
1272 sp<EffectModule> effect;
1273 sp<EffectHandle> handle;
1274 status_t lStatus;
1275 sp<EffectChain> chain;
1276 bool chainCreated = false;
1277 bool effectCreated = false;
1278 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001279 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001280
1281 lStatus = initCheck();
1282 if (lStatus != NO_ERROR) {
1283 ALOGW("createEffect_l() Audio driver not initialized.");
1284 goto Exit;
1285 }
1286
Eric Laurent81784c32012-11-19 14:55:58 -08001287 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1288
1289 { // scope for mLock
1290 Mutex::Autolock _l(mLock);
1291
Eric Laurent4c415062016-06-17 16:14:16 -07001292 lStatus = checkEffectCompatibility_l(desc, sessionId);
1293 if (lStatus != NO_ERROR) {
1294 goto Exit;
1295 }
1296
Eric Laurent81784c32012-11-19 14:55:58 -08001297 // check for existing effect chain with the requested audio session
1298 chain = getEffectChain_l(sessionId);
1299 if (chain == 0) {
1300 // create a new chain for this session
1301 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1302 chain = new EffectChain(this, sessionId);
1303 addEffectChain_l(chain);
1304 chain->setStrategy(getStrategyForSession_l(sessionId));
1305 chainCreated = true;
1306 } else {
1307 effect = chain->getEffectFromDesc_l(desc);
1308 }
1309
1310 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1311
1312 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001313 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001314 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001315 lStatus = AudioSystem::registerEffect(
1316 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001317 if (lStatus != NO_ERROR) {
1318 goto Exit;
1319 }
1320 effectRegistered = true;
1321 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001322 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 if (lStatus != NO_ERROR) {
1324 goto Exit;
1325 }
1326 effectCreated = true;
1327
1328 effect->setDevice(mOutDevice);
1329 effect->setDevice(mInDevice);
1330 effect->setMode(mAudioFlinger->getMode());
1331 effect->setAudioSource(mAudioSource);
1332 }
1333 // create effect handle and connect it to effect module
1334 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001335 lStatus = handle->initCheck();
1336 if (lStatus == OK) {
1337 lStatus = effect->addHandle(handle.get());
1338 }
Eric Laurent81784c32012-11-19 14:55:58 -08001339 if (enabled != NULL) {
1340 *enabled = (int)effect->isEnabled();
1341 }
1342 }
1343
1344Exit:
1345 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1346 Mutex::Autolock _l(mLock);
1347 if (effectCreated) {
1348 chain->removeEffect_l(effect);
1349 }
1350 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001351 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 }
1353 if (chainCreated) {
1354 removeEffectChain_l(chain);
1355 }
1356 handle.clear();
1357 }
1358
Glenn Kasten9156ef32013-08-06 15:39:08 -07001359 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001360 return handle;
1361}
1362
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001363void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1364 bool unpinIfLast)
1365{
1366 bool remove = false;
1367 sp<EffectModule> effect;
1368 {
1369 Mutex::Autolock _l(mLock);
1370
1371 effect = handle->effect().promote();
1372 if (effect == 0) {
1373 return;
1374 }
1375 // restore suspended effects if the disconnected handle was enabled and the last one.
1376 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1377 if (remove) {
1378 removeEffect_l(effect, true);
1379 }
1380 }
1381 if (remove) {
1382 mAudioFlinger->updateOrphanEffectChains(effect);
1383 AudioSystem::unregisterEffect(effect->id());
1384 if (handle->enabled()) {
1385 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1386 }
1387 }
1388}
1389
Glenn Kastend848eb42016-03-08 13:42:11 -08001390sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1391 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001392{
1393 Mutex::Autolock _l(mLock);
1394 return getEffect_l(sessionId, effectId);
1395}
1396
Glenn Kastend848eb42016-03-08 13:42:11 -08001397sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1398 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001399{
1400 sp<EffectChain> chain = getEffectChain_l(sessionId);
1401 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1402}
1403
1404// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1405// PlaybackThread::mLock held
1406status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1407{
1408 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001409 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001410 sp<EffectChain> chain = getEffectChain_l(sessionId);
1411 bool chainCreated = false;
1412
Eric Laurent5baf2af2013-09-12 17:37:00 -07001413 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1414 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1415 this, effect->desc().name, effect->desc().flags);
1416
Eric Laurent81784c32012-11-19 14:55:58 -08001417 if (chain == 0) {
1418 // create a new chain for this session
1419 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1420 chain = new EffectChain(this, sessionId);
1421 addEffectChain_l(chain);
1422 chain->setStrategy(getStrategyForSession_l(sessionId));
1423 chainCreated = true;
1424 }
1425 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1426
1427 if (chain->getEffectFromId_l(effect->id()) != 0) {
1428 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1429 this, effect->desc().name, chain.get());
1430 return BAD_VALUE;
1431 }
1432
Eric Laurent5baf2af2013-09-12 17:37:00 -07001433 effect->setOffloaded(mType == OFFLOAD, mId);
1434
Eric Laurent81784c32012-11-19 14:55:58 -08001435 status_t status = chain->addEffect_l(effect);
1436 if (status != NO_ERROR) {
1437 if (chainCreated) {
1438 removeEffectChain_l(chain);
1439 }
1440 return status;
1441 }
1442
1443 effect->setDevice(mOutDevice);
1444 effect->setDevice(mInDevice);
1445 effect->setMode(mAudioFlinger->getMode());
1446 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001447
Eric Laurent81784c32012-11-19 14:55:58 -08001448 return NO_ERROR;
1449}
1450
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001451void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001452
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001453 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001454 effect_descriptor_t desc = effect->desc();
1455 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1456 detachAuxEffect_l(effect->id());
1457 }
1458
1459 sp<EffectChain> chain = effect->chain().promote();
1460 if (chain != 0) {
1461 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001462 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001463 removeEffectChain_l(chain);
1464 }
1465 } else {
1466 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1467 }
1468}
1469
1470void AudioFlinger::ThreadBase::lockEffectChains_l(
1471 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1472{
1473 effectChains = mEffectChains;
1474 for (size_t i = 0; i < mEffectChains.size(); i++) {
1475 mEffectChains[i]->lock();
1476 }
1477}
1478
1479void AudioFlinger::ThreadBase::unlockEffectChains(
1480 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1481{
1482 for (size_t i = 0; i < effectChains.size(); i++) {
1483 effectChains[i]->unlock();
1484 }
1485}
1486
Glenn Kastend848eb42016-03-08 13:42:11 -08001487sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001488{
1489 Mutex::Autolock _l(mLock);
1490 return getEffectChain_l(sessionId);
1491}
1492
Glenn Kastend848eb42016-03-08 13:42:11 -08001493sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1494 const
Eric Laurent81784c32012-11-19 14:55:58 -08001495{
1496 size_t size = mEffectChains.size();
1497 for (size_t i = 0; i < size; i++) {
1498 if (mEffectChains[i]->sessionId() == sessionId) {
1499 return mEffectChains[i];
1500 }
1501 }
1502 return 0;
1503}
1504
1505void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1506{
1507 Mutex::Autolock _l(mLock);
1508 size_t size = mEffectChains.size();
1509 for (size_t i = 0; i < size; i++) {
1510 mEffectChains[i]->setMode_l(mode);
1511 }
1512}
1513
Eric Laurent83b88082014-06-20 18:31:16 -07001514void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1515{
1516 config->type = AUDIO_PORT_TYPE_MIX;
1517 config->ext.mix.handle = mId;
1518 config->sample_rate = mSampleRate;
1519 config->format = mFormat;
1520 config->channel_mask = mChannelMask;
1521 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1522 AUDIO_PORT_CONFIG_FORMAT;
1523}
1524
Eric Laurent72e3f392015-05-20 14:43:50 -07001525void AudioFlinger::ThreadBase::systemReady()
1526{
1527 Mutex::Autolock _l(mLock);
1528 if (mSystemReady) {
1529 return;
1530 }
1531 mSystemReady = true;
1532
1533 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1534 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1535 }
1536 mPendingConfigEvents.clear();
1537}
1538
Andy Hungdae27702016-10-31 14:01:16 -07001539template <typename T>
1540ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1541 ssize_t index = mActiveTracks.indexOf(track);
1542 if (index >= 0) {
1543 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1544 return index;
1545 }
1546 mActiveTracksGeneration++;
1547 mLatestActiveTrack = track;
1548 ++mBatteryCounter[track->uid()].second;
1549 return mActiveTracks.add(track);
1550}
1551
1552template <typename T>
1553ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1554 ssize_t index = mActiveTracks.remove(track);
1555 if (index < 0) {
1556 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1557 return index;
1558 }
1559 mActiveTracksGeneration++;
1560 --mBatteryCounter[track->uid()].second;
1561 // mLatestActiveTrack is not cleared even if is the same as track.
1562 return index;
1563}
1564
1565template <typename T>
1566void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1567 for (const sp<T> &track : mActiveTracks) {
1568 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1569 }
1570 mLastActiveTracksGeneration = mActiveTracksGeneration;
1571 mActiveTracks.clear();
1572 mLatestActiveTrack.clear();
1573 mBatteryCounter.clear();
1574}
1575
1576template <typename T>
1577void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1578 sp<ThreadBase> thread, bool force) {
1579 // Updates ActiveTracks client uids to the thread wakelock.
1580 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1581 thread->updateWakeLockUids_l(getWakeLockUids());
1582 mLastActiveTracksGeneration = mActiveTracksGeneration;
1583 }
1584
1585 // Updates BatteryNotifier uids
1586 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1587 const uid_t uid = it->first;
1588 ssize_t &previous = it->second.first;
1589 ssize_t &current = it->second.second;
1590 if (current > 0) {
1591 if (previous == 0) {
1592 BatteryNotifier::getInstance().noteStartAudio(uid);
1593 }
1594 previous = current;
1595 ++it;
1596 } else if (current == 0) {
1597 if (previous > 0) {
1598 BatteryNotifier::getInstance().noteStopAudio(uid);
1599 }
1600 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1601 } else /* (current < 0) */ {
1602 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1603 }
1604 }
1605}
Eric Laurent83b88082014-06-20 18:31:16 -07001606
Eric Laurent6acd1d42017-01-04 14:23:29 -08001607void AudioFlinger::ThreadBase::broadcast_l()
1608{
1609 // Thread could be blocked waiting for async
1610 // so signal it to handle state changes immediately
1611 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1612 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1613 mSignalPending = true;
1614 mWaitWorkCV.broadcast();
1615}
1616
Eric Laurent81784c32012-11-19 14:55:58 -08001617// ----------------------------------------------------------------------------
1618// Playback
1619// ----------------------------------------------------------------------------
1620
1621AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1622 AudioStreamOut* output,
1623 audio_io_handle_t id,
1624 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001625 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001626 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001627 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001628 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001629 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001630 mMixerBuffer(NULL),
1631 mMixerBufferSize(0),
1632 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1633 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001634 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001635 mEffectBuffer(NULL),
1636 mEffectBufferSize(0),
1637 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1638 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001639 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001640 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001641 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001642 // mStreamTypes[] initialized in constructor body
1643 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001644 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001645 mMixerStatus(MIXER_IDLE),
1646 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001647 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001648 mBytesRemaining(0),
1649 mCurrentWriteLength(0),
1650 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001651 mWriteAckSequence(0),
1652 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001653 mScreenState(AudioFlinger::mScreenState),
1654 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001655 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001656 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001657{
Glenn Kastend7dca052015-03-05 16:05:54 -08001658 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1659 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001660
1661 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1662 // it would be safer to explicitly pass initial masterVolume/masterMute as
1663 // parameter.
1664 //
1665 // If the HAL we are using has support for master volume or master mute,
1666 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1667 // and the mute set to false).
1668 mMasterVolume = audioFlinger->masterVolume_l();
1669 mMasterMute = audioFlinger->masterMute_l();
1670 if (mOutput && mOutput->audioHwDev) {
1671 if (mOutput->audioHwDev->canSetMasterVolume()) {
1672 mMasterVolume = 1.0;
1673 }
1674
1675 if (mOutput->audioHwDev->canSetMasterMute()) {
1676 mMasterMute = false;
1677 }
1678 }
1679
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001680 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001681
Eric Laurent223fd5c2014-11-11 13:43:36 -08001682 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001683 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001684 stream = (audio_stream_type_t) (stream + 1)) {
1685 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1686 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1687 }
Eric Laurent81784c32012-11-19 14:55:58 -08001688}
1689
1690AudioFlinger::PlaybackThread::~PlaybackThread()
1691{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001692 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001693 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001694 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001695 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001696}
1697
1698void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1699{
1700 dumpInternals(fd, args);
1701 dumpTracks(fd, args);
1702 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001703 dprintf(fd, " Local log:\n");
1704 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001705}
1706
Glenn Kasten0f11b512014-01-31 16:18:54 -08001707void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001708{
1709 const size_t SIZE = 256;
1710 char buffer[SIZE];
1711 String8 result;
1712
Marco Nelissenb2208842014-02-07 14:00:50 -08001713 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001714 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1715 const stream_type_t *st = &mStreamTypes[i];
1716 if (i > 0) {
1717 result.appendFormat(", ");
1718 }
1719 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1720 if (st->mute) {
1721 result.append("M");
1722 }
1723 }
1724 result.append("\n");
1725 write(fd, result.string(), result.length());
1726 result.clear();
1727
Eric Laurent81784c32012-11-19 14:55:58 -08001728 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1729 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001730 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001731 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001732
1733 size_t numtracks = mTracks.size();
1734 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001735 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001736 size_t numactiveseen = 0;
1737 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001738 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001739 Track::appendDumpHeader(result);
1740 for (size_t i = 0; i < numtracks; ++i) {
1741 sp<Track> track = mTracks[i];
1742 if (track != 0) {
1743 bool active = mActiveTracks.indexOf(track) >= 0;
1744 if (active) {
1745 numactiveseen++;
1746 }
1747 track->dump(buffer, SIZE, active);
1748 result.append(buffer);
1749 }
1750 }
1751 } else {
1752 result.append("\n");
1753 }
1754 if (numactiveseen != numactive) {
1755 // some tracks in the active list were not in the tracks list
1756 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1757 " not in the track list\n");
1758 result.append(buffer);
1759 Track::appendDumpHeader(result);
1760 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001761 sp<Track> track = mActiveTracks[i];
1762 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001763 track->dump(buffer, SIZE, true);
1764 result.append(buffer);
1765 }
1766 }
1767 }
1768
1769 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001770}
1771
1772void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1773{
Glenn Kasten44182c22015-03-05 17:12:23 -08001774 dumpBase(fd, args);
1775
Elliott Hughes87cebad2014-05-22 10:14:43 -07001776 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001777 dprintf(fd, " Last write occurred (msecs): %llu\n",
1778 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001779 dprintf(fd, " Total writes: %d\n", mNumWrites);
1780 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1781 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1782 dprintf(fd, " Suspend count: %d\n", mSuspended);
1783 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1784 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1785 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1786 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001787 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001788 AudioStreamOut *output = mOutput;
1789 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001790 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1791 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001792 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1793 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1794 if (mPipeSink.get() != nullptr) {
1795 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1796 }
1797 if (output != nullptr) {
1798 dprintf(fd, " Hal stream dump:\n");
1799 (void)output->stream->dump(fd);
1800 }
Eric Laurent81784c32012-11-19 14:55:58 -08001801}
1802
1803// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001804
1805void AudioFlinger::PlaybackThread::onFirstRef()
1806{
Glenn Kastend7dca052015-03-05 16:05:54 -08001807 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001808}
1809
1810// ThreadBase virtuals
1811void AudioFlinger::PlaybackThread::preExit()
1812{
1813 ALOGV(" preExit()");
1814 // FIXME this is using hard-coded strings but in the future, this functionality will be
1815 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001816 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1817 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001818}
1819
1820// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1821sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1822 const sp<AudioFlinger::Client>& client,
1823 audio_stream_type_t streamType,
1824 uint32_t sampleRate,
1825 audio_format_t format,
1826 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001827 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001828 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001829 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001830 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001831 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001832 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001833 status_t *status,
1834 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001835{
Glenn Kasten74935e42013-12-19 08:56:45 -08001836 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001837 sp<Track> track;
1838 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001839 audio_output_flags_t outputFlags = mOutput->flags;
1840
1841 // special case for FAST flag considered OK if fast mixer is present
1842 if (hasFastMixer()) {
1843 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1844 }
1845
1846 // Check if requested flags are compatible with output stream flags
1847 if ((*flags & outputFlags) != *flags) {
1848 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1849 *flags, outputFlags);
1850 *flags = (audio_output_flags_t)(*flags & outputFlags);
1851 }
Eric Laurent81784c32012-11-19 14:55:58 -08001852
Eric Laurent81784c32012-11-19 14:55:58 -08001853 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001854 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001855 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001856 // PCM data
1857 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001858 // TODO: extract as a data library function that checks that a computationally
1859 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001860 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001861 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1862 (channelMask == AUDIO_CHANNEL_OUT_MONO
1863 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001864 // hardware sample rate
1865 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001866 // normal mixer has an associated fast mixer
1867 hasFastMixer() &&
1868 // there are sufficient fast track slots available
1869 (mFastTrackAvailMask != 0)
1870 // FIXME test that MixerThread for this fast track has a capable output HAL
1871 // FIXME add a permission test also?
1872 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001873 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1874 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001875 // read the fast track multiplier property the first time it is needed
1876 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1877 if (ok != 0) {
1878 ALOGE("%s pthread_once failed: %d", __func__, ok);
1879 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001880 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001881 }
Eric Laurent4c415062016-06-17 16:14:16 -07001882
1883 // check compatibility with audio effects.
1884 { // scope for mLock
1885 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001886 for (audio_session_t session : {
1887 AUDIO_SESSION_OUTPUT_STAGE,
1888 AUDIO_SESSION_OUTPUT_MIX,
1889 sessionId,
1890 }) {
1891 sp<EffectChain> chain = getEffectChain_l(session);
1892 if (chain.get() != nullptr) {
1893 audio_output_flags_t old = *flags;
1894 chain->checkOutputFlagCompatibility(flags);
1895 if (old != *flags) {
1896 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1897 (int)session, (int)old, (int)*flags);
1898 }
Eric Laurent4c415062016-06-17 16:14:16 -07001899 }
1900 }
1901 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001902 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001903 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1904 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001905 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001906 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1907 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001908 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001909 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001910 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001911 audio_is_linear_pcm(format),
1912 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001913 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001914 }
1915 }
1916 // For normal PCM streaming tracks, update minimum frame count.
1917 // For compatibility with AudioTrack calculation, buffer depth is forced
1918 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1919 // This is probably too conservative, but legacy application code may depend on it.
1920 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001921 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001922 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001923 // this must match AudioTrack.cpp calculateMinFrameCount().
1924 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001925 uint32_t latencyMs = 0;
1926 lStatus = mOutput->stream->getLatency(&latencyMs);
1927 if (lStatus != OK) {
1928 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1929 goto Exit;
1930 }
Eric Laurent81784c32012-11-19 14:55:58 -08001931 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1932 if (minBufCount < 2) {
1933 minBufCount = 2;
1934 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001935 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1936 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001937 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001938 minBufCount * sourceFramesNeededWithTimestretch(
1939 sampleRate, mNormalFrameCount,
1940 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001941 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001942 frameCount = minFrameCount;
1943 }
Eric Laurent81784c32012-11-19 14:55:58 -08001944 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001945 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001946
Glenn Kastenc3df8382014-03-13 15:05:25 -07001947 switch (mType) {
1948
1949 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001950 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001951 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001952 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1953 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001954 sampleRate, format, channelMask, mOutput, mFormat);
1955 lStatus = BAD_VALUE;
1956 goto Exit;
1957 }
1958 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001959 break;
1960
1961 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001962 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001963 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1964 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001965 sampleRate, format, channelMask, mOutput, mFormat);
1966 lStatus = BAD_VALUE;
1967 goto Exit;
1968 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001969 break;
1970
1971 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001972 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001973 ALOGE("createTrack_l() Bad parameter: format %#x \""
1974 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001975 format, mOutput, mFormat);
1976 lStatus = BAD_VALUE;
1977 goto Exit;
1978 }
Andy Hungcd044842014-08-07 11:04:34 -07001979 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001980 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1981 lStatus = BAD_VALUE;
1982 goto Exit;
1983 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001984 break;
1985
Eric Laurent81784c32012-11-19 14:55:58 -08001986 }
1987
1988 lStatus = initCheck();
1989 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001990 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001991 goto Exit;
1992 }
1993
1994 { // scope for mLock
1995 Mutex::Autolock _l(mLock);
1996
1997 // all tracks in same audio session must share the same routing strategy otherwise
1998 // conflicts will happen when tracks are moved from one output to another by audio policy
1999 // manager
2000 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2001 for (size_t i = 0; i < mTracks.size(); ++i) {
2002 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002003 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002004 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2005 if (sessionId == t->sessionId() && strategy != actual) {
2006 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2007 strategy, actual);
2008 lStatus = BAD_VALUE;
2009 goto Exit;
2010 }
2011 }
2012 }
2013
Glenn Kastend79072e2016-01-06 08:41:20 -08002014 track = new Track(this, client, streamType, sampleRate, format,
2015 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002016 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002017
Glenn Kasten03003332013-08-06 15:40:54 -07002018 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2019 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002020 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002021 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002022 goto Exit;
2023 }
2024 mTracks.add(track);
2025
2026 sp<EffectChain> chain = getEffectChain_l(sessionId);
2027 if (chain != 0) {
2028 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2029 track->setMainBuffer(chain->inBuffer());
2030 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2031 chain->incTrackCnt();
2032 }
2033
Eric Laurent05067782016-06-01 18:27:28 -07002034 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002035 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2036 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2037 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002038 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002039 }
2040 }
2041
2042 lStatus = NO_ERROR;
2043
2044Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002045 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002046 return track;
2047}
2048
2049uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2050{
2051 return latency;
2052}
2053
2054uint32_t AudioFlinger::PlaybackThread::latency() const
2055{
2056 Mutex::Autolock _l(mLock);
2057 return latency_l();
2058}
2059uint32_t AudioFlinger::PlaybackThread::latency_l() const
2060{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002061 uint32_t latency;
2062 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2063 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002064 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002065 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002066}
2067
2068void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2069{
2070 Mutex::Autolock _l(mLock);
2071 // Don't apply master volume in SW if our HAL can do it for us.
2072 if (mOutput && mOutput->audioHwDev &&
2073 mOutput->audioHwDev->canSetMasterVolume()) {
2074 mMasterVolume = 1.0;
2075 } else {
2076 mMasterVolume = value;
2077 }
2078}
2079
2080void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2081{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002082 if (isDuplicating()) {
2083 return;
2084 }
Eric Laurent81784c32012-11-19 14:55:58 -08002085 Mutex::Autolock _l(mLock);
2086 // Don't apply master mute in SW if our HAL can do it for us.
2087 if (mOutput && mOutput->audioHwDev &&
2088 mOutput->audioHwDev->canSetMasterMute()) {
2089 mMasterMute = false;
2090 } else {
2091 mMasterMute = muted;
2092 }
2093}
2094
2095void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2096{
2097 Mutex::Autolock _l(mLock);
2098 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002099 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002100}
2101
2102void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2103{
2104 Mutex::Autolock _l(mLock);
2105 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002106 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002107}
2108
2109float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2110{
2111 Mutex::Autolock _l(mLock);
2112 return mStreamTypes[stream].volume;
2113}
2114
2115// addTrack_l() must be called with ThreadBase::mLock held
2116status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2117{
2118 status_t status = ALREADY_EXISTS;
2119
Eric Laurent81784c32012-11-19 14:55:58 -08002120 if (mActiveTracks.indexOf(track) < 0) {
2121 // the track is newly added, make sure it fills up all its
2122 // buffers before playing. This is to ensure the client will
2123 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002124 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002125 TrackBase::track_state state = track->mState;
2126 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002127 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002128 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002129 mLock.lock();
2130 // abort track was stopped/paused while we released the lock
2131 if (state != track->mState) {
2132 if (status == NO_ERROR) {
2133 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002134 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002135 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002136 mLock.lock();
2137 }
2138 return INVALID_OPERATION;
2139 }
2140 // abort if start is rejected by audio policy manager
2141 if (status != NO_ERROR) {
2142 return PERMISSION_DENIED;
2143 }
2144#ifdef ADD_BATTERY_DATA
2145 // to track the speaker usage
2146 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2147#endif
2148 }
2149
Eric Laurent51716182016-02-29 18:00:56 -08002150 // set retry count for buffer fill
2151 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002152 if (track->isStopping_1()) {
2153 track->mRetryCount = kMaxTrackStopRetriesOffload;
2154 } else {
2155 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2156 }
2157 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002158 } else {
2159 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002160 track->mFillingUpStatus =
2161 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002162 }
2163
Eric Laurent81784c32012-11-19 14:55:58 -08002164 track->mResetDone = false;
2165 track->mPresentationCompleteFrames = 0;
2166 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002167 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2168 if (chain != 0) {
2169 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2170 track->sessionId());
2171 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002172 }
2173
Andy Hung2148bf02016-11-28 19:01:02 -08002174 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07002175 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08002176 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2177
Eric Laurent81784c32012-11-19 14:55:58 -08002178 status = NO_ERROR;
2179 }
2180
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002181 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002182 return status;
2183}
2184
Eric Laurentbfb1b832013-01-07 09:53:42 -08002185bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002186{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002187 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002188 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002189 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2190 track->mState = TrackBase::STOPPED;
2191 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002192 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002193 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002194 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002195 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002196
2197 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002198}
2199
2200void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2201{
2202 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002203
2204 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07002205 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08002206 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2207
Eric Laurent81784c32012-11-19 14:55:58 -08002208 mTracks.remove(track);
2209 deleteTrackName_l(track->name());
2210 // redundant as track is about to be destroyed, for dumpsys only
2211 track->mName = -1;
2212 if (track->isFastTrack()) {
2213 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002214 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002215 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2216 mFastTrackAvailMask |= 1 << index;
2217 // redundant as track is about to be destroyed, for dumpsys only
2218 track->mFastIndex = -1;
2219 }
2220 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2221 if (chain != 0) {
2222 chain->decTrackCnt();
2223 }
2224}
2225
2226String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2227{
Eric Laurent81784c32012-11-19 14:55:58 -08002228 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002229 String8 out_s8;
2230 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2231 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002232 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002233 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002234}
2235
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002236void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002237 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2238 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002239
Eric Laurent73e26b62015-04-27 16:55:58 -07002240 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002241
2242 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002243 case AUDIO_OUTPUT_OPENED:
2244 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002245 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002246 desc->mChannelMask = mChannelMask;
2247 desc->mSamplingRate = mSampleRate;
2248 desc->mFormat = mFormat;
2249 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002250 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002251 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002252 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002253 break;
2254
Eric Laurent73e26b62015-04-27 16:55:58 -07002255 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002256 default:
2257 break;
2258 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002259 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002260}
2261
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002262void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002263{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002264 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002265}
2266
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002267void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002268{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002269 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002270}
2271
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002272void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002273{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002274 mCallbackThread->setAsyncError();
2275}
2276
Eric Laurent3b4529e2013-09-05 18:09:19 -07002277void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278{
2279 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002280 // reject out of sequence requests
2281 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2282 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283 mWaitWorkCV.signal();
2284 }
2285}
2286
Eric Laurent3b4529e2013-09-05 18:09:19 -07002287void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288{
2289 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002290 // reject out of sequence requests
2291 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2292 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002293 mWaitWorkCV.signal();
2294 }
2295}
2296
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002297void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002298{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002299 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002300 mSampleRate = mOutput->getSampleRate();
2301 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002302 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002303 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002304 }
Andy Hung9a592762014-07-21 21:56:01 -07002305 if ((mType == MIXER || mType == DUPLICATING)
2306 && !isValidPcmSinkChannelMask(mChannelMask)) {
2307 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2308 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002309 }
Andy Hunge5412692014-05-16 11:25:07 -07002310 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002311
2312 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002313 status_t result = mOutput->stream->getFormat(&mHALFormat);
2314 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002315 // Get format from the shim, which will be different than the HAL format
2316 // if playing compressed audio over HDMI passthrough.
2317 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002318 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002319 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002320 }
Andy Hung6146c082014-03-18 11:56:15 -07002321 if ((mType == MIXER || mType == DUPLICATING)
2322 && !isValidPcmSinkFormat(mFormat)) {
2323 LOG_FATAL("HAL format %#x not supported for mixed output",
2324 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002325 }
Phil Burk062e67a2015-02-11 13:40:50 -08002326 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002327 result = mOutput->stream->getBufferSize(&mBufferSize);
2328 LOG_ALWAYS_FATAL_IF(result != OK,
2329 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002330 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002331 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002332 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002333 mFrameCount);
2334 }
2335
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002336 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2337 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002338 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002339 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002340 }
2341 }
2342
Eric Laurentd1f69b02014-12-15 14:33:13 -08002343 mHwSupportsPause = false;
2344 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002345 bool supportsPause = false, supportsResume = false;
2346 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2347 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002348 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002349 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002350 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002351 } else if (supportsResume) {
2352 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002353 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002354 }
2355 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002356 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2357 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2358 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002359
Andy Hungfbfc3952015-01-15 13:33:51 -08002360 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2361 // For best precision, we use float instead of the associated output
2362 // device format (typically PCM 16 bit).
2363
2364 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2365 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2366 mBufferSize = mFrameSize * mFrameCount;
2367
2368 // TODO: We currently use the associated output device channel mask and sample rate.
2369 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2370 // (if a valid mask) to avoid premature downmix.
2371 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2372 // instead of the output device sample rate to avoid loss of high frequency information.
2373 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2374 }
2375
Andy Hung09a50072014-02-27 14:30:47 -08002376 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002377 double multiplier = 1.0;
2378 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2379 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002380 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2381 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002382
Eric Laurent81784c32012-11-19 14:55:58 -08002383 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2384 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2385 maxNormalFrameCount = maxNormalFrameCount & ~15;
2386 if (maxNormalFrameCount < minNormalFrameCount) {
2387 maxNormalFrameCount = minNormalFrameCount;
2388 }
2389 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2390 if (multiplier <= 1.0) {
2391 multiplier = 1.0;
2392 } else if (multiplier <= 2.0) {
2393 if (2 * mFrameCount <= maxNormalFrameCount) {
2394 multiplier = 2.0;
2395 } else {
2396 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2397 }
2398 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002399 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002400 }
2401 }
2402 mNormalFrameCount = multiplier * mFrameCount;
2403 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002404 if (mType == MIXER || mType == DUPLICATING) {
2405 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2406 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002407 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002408 mNormalFrameCount);
2409
Andy Hung08fb1742015-05-31 23:22:10 -07002410 // Check if we want to throttle the processing to no more than 2x normal rate
2411 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002412 mThreadThrottleTimeMs = 0;
2413 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002414 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2415
Andy Hung010a1a12014-03-13 13:57:33 -07002416 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2417 // Originally this was int16_t[] array, need to remove legacy implications.
2418 free(mSinkBuffer);
2419 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002420 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2421 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2422 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002423 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002424
Andy Hung69aed5f2014-02-25 17:24:40 -08002425 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2426 // drives the output.
2427 free(mMixerBuffer);
2428 mMixerBuffer = NULL;
2429 if (mMixerBufferEnabled) {
2430 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2431 mMixerBufferSize = mNormalFrameCount * mChannelCount
2432 * audio_bytes_per_sample(mMixerBufferFormat);
2433 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2434 }
Andy Hung98ef9782014-03-04 14:46:50 -08002435 free(mEffectBuffer);
2436 mEffectBuffer = NULL;
2437 if (mEffectBufferEnabled) {
2438 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2439 mEffectBufferSize = mNormalFrameCount * mChannelCount
2440 * audio_bytes_per_sample(mEffectBufferFormat);
2441 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2442 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002443
Eric Laurent81784c32012-11-19 14:55:58 -08002444 // force reconfiguration of effect chains and engines to take new buffer size and audio
2445 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002446 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002447 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2448 // matter.
2449 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2450 Vector< sp<EffectChain> > effectChains = mEffectChains;
2451 for (size_t i = 0; i < effectChains.size(); i ++) {
2452 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2453 }
2454}
2455
2456
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002457status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002458{
2459 if (halFrames == NULL || dspFrames == NULL) {
2460 return BAD_VALUE;
2461 }
2462 Mutex::Autolock _l(mLock);
2463 if (initCheck() != NO_ERROR) {
2464 return INVALID_OPERATION;
2465 }
Andy Hung818e7a32016-02-16 18:08:07 -08002466 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002467 *halFrames = framesWritten;
2468
2469 if (isSuspended()) {
2470 // return an estimation of rendered frames when the output is suspended
2471 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002472 *dspFrames = (uint32_t)
2473 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002474 return NO_ERROR;
2475 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002476 status_t status;
2477 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002478 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002479 *dspFrames = (size_t)frames;
2480 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002481 }
2482}
2483
Eric Laurent4c415062016-06-17 16:14:16 -07002484// hasAudioSession_l() must be called with ThreadBase::mLock held
2485uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002486{
Eric Laurent81784c32012-11-19 14:55:58 -08002487 uint32_t result = 0;
2488 if (getEffectChain_l(sessionId) != 0) {
2489 result = EFFECT_SESSION;
2490 }
2491
2492 for (size_t i = 0; i < mTracks.size(); ++i) {
2493 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002494 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002495 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002496 if (track->isFastTrack()) {
2497 result |= FAST_SESSION;
2498 }
Eric Laurent81784c32012-11-19 14:55:58 -08002499 break;
2500 }
2501 }
2502
2503 return result;
2504}
2505
Glenn Kastend848eb42016-03-08 13:42:11 -08002506uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002507{
2508 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2509 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2510 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2511 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2512 }
2513 for (size_t i = 0; i < mTracks.size(); i++) {
2514 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002515 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002516 return AudioSystem::getStrategyForStream(track->streamType());
2517 }
2518 }
2519 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2520}
2521
2522
Phil Burk062e67a2015-02-11 13:40:50 -08002523AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002524{
2525 Mutex::Autolock _l(mLock);
2526 return mOutput;
2527}
2528
Phil Burk062e67a2015-02-11 13:40:50 -08002529AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002530{
2531 Mutex::Autolock _l(mLock);
2532 AudioStreamOut *output = mOutput;
2533 mOutput = NULL;
2534 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2535 // must push a NULL and wait for ack
2536 mOutputSink.clear();
2537 mPipeSink.clear();
2538 mNormalSink.clear();
2539 return output;
2540}
2541
2542// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002544{
2545 if (mOutput == NULL) {
2546 return NULL;
2547 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002548 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002549}
2550
2551uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2552{
2553 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2554}
2555
2556status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2557{
2558 if (!isValidSyncEvent(event)) {
2559 return BAD_VALUE;
2560 }
2561
2562 Mutex::Autolock _l(mLock);
2563
2564 for (size_t i = 0; i < mTracks.size(); ++i) {
2565 sp<Track> track = mTracks[i];
2566 if (event->triggerSession() == track->sessionId()) {
2567 (void) track->setSyncEvent(event);
2568 return NO_ERROR;
2569 }
2570 }
2571
2572 return NAME_NOT_FOUND;
2573}
2574
2575bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2576{
2577 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2578}
2579
2580void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2581 const Vector< sp<Track> >& tracksToRemove)
2582{
2583 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002584 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002585 for (size_t i = 0 ; i < count ; i++) {
2586 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002587 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002588 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002589 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590#ifdef ADD_BATTERY_DATA
2591 // to track the speaker usage
2592 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2593#endif
2594 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002595 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002596 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002597 }
Eric Laurent81784c32012-11-19 14:55:58 -08002598 }
2599 }
2600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601}
2602
2603void AudioFlinger::PlaybackThread::checkSilentMode_l()
2604{
2605 if (!mMasterMute) {
2606 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002607 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2608 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2609 return;
2610 }
Eric Laurent81784c32012-11-19 14:55:58 -08002611 if (property_get("ro.audio.silent", value, "0") > 0) {
2612 char *endptr;
2613 unsigned long ul = strtoul(value, &endptr, 0);
2614 if (*endptr == '\0' && ul != 0) {
2615 ALOGD("Silence is golden");
2616 // The setprop command will not allow a property to be changed after
2617 // the first time it is set, so we don't have to worry about un-muting.
2618 setMasterMute_l(true);
2619 }
2620 }
2621 }
2622}
2623
2624// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002625ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002626{
Eric Laurent81784c32012-11-19 14:55:58 -08002627 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002628 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002629 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002630
2631 // If an NBAIO sink is present, use it to write the normal mixer's submix
2632 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002633
Andy Hung010a1a12014-03-13 13:57:33 -07002634 const size_t count = mBytesRemaining / mFrameSize;
2635
Simon Wilson2d590962012-11-29 15:18:50 -08002636 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002637 // update the setpoint when AudioFlinger::mScreenState changes
2638 uint32_t screenState = AudioFlinger::mScreenState;
2639 if (screenState != mScreenState) {
2640 mScreenState = screenState;
2641 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2642 if (pipe != NULL) {
2643 pipe->setAvgFrames((mScreenState & 1) ?
2644 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2645 }
2646 }
Andy Hung010a1a12014-03-13 13:57:33 -07002647 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002648 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002649 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002650 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002651 } else {
2652 bytesWritten = framesWritten;
2653 }
2654 // otherwise use the HAL / AudioStreamOut directly
2655 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002656 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002657
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002659 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2660 mWriteAckSequence += 2;
2661 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002663 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002665 // FIXME We should have an implementation of timestamps for direct output threads.
2666 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002667 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002668
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 if (mUseAsyncWrite &&
2670 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2671 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002672 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002674 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 }
Eric Laurent81784c32012-11-19 14:55:58 -08002676 }
2677
Eric Laurent81784c32012-11-19 14:55:58 -08002678 mNumWrites++;
2679 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002680 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 return bytesWritten;
2682}
2683
2684void AudioFlinger::PlaybackThread::threadLoop_drain()
2685{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002686 bool supportsDrain = false;
2687 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2689 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002690 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2691 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002693 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002694 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002695 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002696 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002697 }
2698}
2699
2700void AudioFlinger::PlaybackThread::threadLoop_exit()
2701{
Eric Laurent275e8e92014-11-30 15:14:47 -08002702 {
2703 Mutex::Autolock _l(mLock);
2704 for (size_t i = 0; i < mTracks.size(); i++) {
2705 sp<Track> track = mTracks[i];
2706 track->invalidate();
2707 }
Andy Hungdae27702016-10-31 14:01:16 -07002708 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2709 // After we exit there are no more track changes sent to BatteryNotifier
2710 // because that requires an active threadLoop.
2711 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2712 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002713 }
Eric Laurent81784c32012-11-19 14:55:58 -08002714}
2715
2716/*
2717The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002718 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002719 - mActiveSleepTimeUs from activeSleepTimeUs()
2720 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002721 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2722 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002723 - maxPeriod from frame count and sample rate (MIXER only)
2724
2725The parameters that affect these derived values are:
2726 - frame count
2727 - frame size
2728 - sample rate
2729 - device type: A2DP or not
2730 - device latency
2731 - format: PCM or not
2732 - active sleep time
2733 - idle sleep time
2734*/
2735
2736void AudioFlinger::PlaybackThread::cacheParameters_l()
2737{
Andy Hung25c2dac2014-02-27 14:56:00 -08002738 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002739 mActiveSleepTimeUs = activeSleepTimeUs();
2740 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002741
2742 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2743 // truncating audio when going to standby.
2744 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2745 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2746 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2747 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2748 }
2749 }
Eric Laurent81784c32012-11-19 14:55:58 -08002750}
2751
Eric Laurent13084622016-05-17 10:51:49 -07002752bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002753{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002754 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002755 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002756 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002757 size_t size = mTracks.size();
2758 for (size_t i = 0; i < size; i++) {
2759 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002760 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002761 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002762 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002763 }
2764 }
Eric Laurent13084622016-05-17 10:51:49 -07002765 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002766}
2767
Haynes Mathew George05317d22016-05-03 16:34:26 -07002768void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2769{
2770 Mutex::Autolock _l(mLock);
2771 invalidateTracks_l(streamType);
2772}
2773
Eric Laurent81784c32012-11-19 14:55:58 -08002774status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2775{
Glenn Kastend848eb42016-03-08 13:42:11 -08002776 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002777 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2778 status_t result = EffectBufferHalInterface::mirror(
2779 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2780 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2781 &halInBuffer);
2782 if (result != OK) return result;
2783 halOutBuffer = halInBuffer;
2784 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002785
2786 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002787 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002788 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002789 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002790 if (mType != DIRECT) {
2791 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002792 status_t result = EffectBufferHalInterface::allocate(
2793 numSamples * sizeof(int16_t),
2794 &halInBuffer);
2795 if (result != OK) return result;
2796 buffer = halInBuffer->audioBuffer()->s16;
2797 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2798 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002799 }
2800
2801 // Attach all tracks with same session ID to this chain.
2802 for (size_t i = 0; i < mTracks.size(); ++i) {
2803 sp<Track> track = mTracks[i];
2804 if (session == track->sessionId()) {
2805 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2806 buffer);
2807 track->setMainBuffer(buffer);
2808 chain->incTrackCnt();
2809 }
2810 }
2811
2812 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002813 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002814 if (session == track->sessionId()) {
2815 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2816 chain->incActiveTrackCnt();
2817 }
2818 }
2819 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002820 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002821 chain->setInBuffer(halInBuffer);
2822 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002823 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002824 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2826 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002827 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002828 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002829 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002830 // Effect chain for other sessions are inserted at beginning of effect
2831 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002832 // sessions is not important.
2833 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2834 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2835 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002836 size_t size = mEffectChains.size();
2837 size_t i = 0;
2838 for (i = 0; i < size; i++) {
2839 if (mEffectChains[i]->sessionId() < session) {
2840 break;
2841 }
2842 }
2843 mEffectChains.insertAt(chain, i);
2844 checkSuspendOnAddEffectChain_l(chain);
2845
2846 return NO_ERROR;
2847}
2848
2849size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2850{
Glenn Kastend848eb42016-03-08 13:42:11 -08002851 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002852
2853 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2854
2855 for (size_t i = 0; i < mEffectChains.size(); i++) {
2856 if (chain == mEffectChains[i]) {
2857 mEffectChains.removeAt(i);
2858 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002859 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002860 if (session == track->sessionId()) {
2861 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2862 chain.get(), session);
2863 chain->decActiveTrackCnt();
2864 }
2865 }
2866
2867 // detach all tracks with same session ID from this chain
2868 for (size_t i = 0; i < mTracks.size(); ++i) {
2869 sp<Track> track = mTracks[i];
2870 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002871 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002872 chain->decTrackCnt();
2873 }
2874 }
2875 break;
2876 }
2877 }
2878 return mEffectChains.size();
2879}
2880
2881status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002882 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002883{
2884 Mutex::Autolock _l(mLock);
2885 return attachAuxEffect_l(track, EffectId);
2886}
2887
2888status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002889 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002890{
2891 status_t status = NO_ERROR;
2892
2893 if (EffectId == 0) {
2894 track->setAuxBuffer(0, NULL);
2895 } else {
2896 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2897 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2898 if (effect != 0) {
2899 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2900 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2901 } else {
2902 status = INVALID_OPERATION;
2903 }
2904 } else {
2905 status = BAD_VALUE;
2906 }
2907 }
2908 return status;
2909}
2910
2911void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2912{
2913 for (size_t i = 0; i < mTracks.size(); ++i) {
2914 sp<Track> track = mTracks[i];
2915 if (track->auxEffectId() == effectId) {
2916 attachAuxEffect_l(track, 0);
2917 }
2918 }
2919}
2920
2921bool AudioFlinger::PlaybackThread::threadLoop()
2922{
Glenn Kasten388d5712017-04-07 14:38:41 -07002923 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002924
Eric Laurent81784c32012-11-19 14:55:58 -08002925 Vector< sp<Track> > tracksToRemove;
2926
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002927 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002928 nsecs_t lastWriteFinished = -1; // time last server write completed
2929 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002930
2931 // MIXER
2932 nsecs_t lastWarning = 0;
2933
2934 // DUPLICATING
2935 // FIXME could this be made local to while loop?
2936 writeFrames = 0;
2937
2938 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002939 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002940
2941 if (mType == MIXER) {
2942 sleepTimeShift = 0;
2943 }
2944
2945 CpuStats cpuStats;
2946 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2947
2948 acquireWakeLock();
2949
Glenn Kasteneef598c2017-04-03 14:41:13 -07002950 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2951 // thread associated with this PlaybackThread.
2952 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2953 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002954 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2955 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002956 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002957 const char *logString = NULL;
2958
rago1bb90822017-05-02 18:31:48 -07002959 // Estimated time for next buffer to be written to hal. This is used only on
2960 // suspended mode (for now) to help schedule the wait time until next iteration.
2961 nsecs_t timeLoopNextNs = 0;
2962
Eric Laurent664539d2013-09-23 18:24:31 -07002963 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002964
Eric Laurent81784c32012-11-19 14:55:58 -08002965 while (!exitPending())
2966 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002967 // Log merge requests are performed during AudioFlinger binder transactions, but
2968 // that does not cover audio playback. It's requested here for that reason.
2969 mAudioFlinger->requestLogMerge();
2970
Eric Laurent81784c32012-11-19 14:55:58 -08002971 cpuStats.sample(myName);
2972
2973 Vector< sp<EffectChain> > effectChains;
2974
Eric Laurent81784c32012-11-19 14:55:58 -08002975 { // scope for mLock
2976
2977 Mutex::Autolock _l(mLock);
2978
Eric Laurent021cf962014-05-13 10:18:14 -07002979 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002980
Glenn Kasteneef598c2017-04-03 14:41:13 -07002981 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002982 if (logString != NULL) {
2983 mNBLogWriter->logTimestamp();
2984 mNBLogWriter->log(logString);
2985 logString = NULL;
2986 }
2987
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002988 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002989 // and associate with the sink frames written out. We need
2990 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002991 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002992 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002993 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002994 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002995 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002996 ExtendedTimestamp timestamp; // use private copy to fetch
2997 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002998
2999 // We keep track of the last valid kernel position in case we are in underrun
3000 // and the normal mixer period is the same as the fast mixer period, or there
3001 // is some error from the HAL.
3002 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3003 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3004 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3005 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3006 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3007
3008 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3009 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3010 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3011 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003012 }
3013
3014 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3015 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003016 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003017 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003018 }
3019
Andy Hung818e7a32016-02-16 18:08:07 -08003020 // copy over kernel info
3021 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003022 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3023 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003024 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3025 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003026 }
3027 // mFramesWritten for non-offloaded tracks are contiguous
3028 // even after standby() is called. This is useful for the track frame
3029 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003030 bool serverLocationUpdate = false;
3031 if (mFramesWritten != lastFramesWritten) {
3032 serverLocationUpdate = true;
3033 lastFramesWritten = mFramesWritten;
3034 }
3035 // Only update timestamps if there is a meaningful change.
3036 // Either the kernel timestamp must be valid or we have written something.
3037 if (kernelLocationUpdate || serverLocationUpdate) {
3038 if (serverLocationUpdate) {
3039 // use the time before we called the HAL write - it is a bit more accurate
3040 // to when the server last read data than the current time here.
3041 //
3042 // If we haven't written anything, mLastWriteTime will be -1
3043 // and we use systemTime().
3044 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3045 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3046 ? systemTime() : mLastWriteTime;
3047 }
Andy Hungdae27702016-10-31 14:01:16 -07003048
3049 for (const sp<Track> &t : mActiveTracks) {
3050 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003051 t->updateTrackFrameInfo(
3052 t->mAudioTrackServerProxy->framesReleased(),
3053 mFramesWritten,
3054 mTimestamp);
3055 }
Andy Hunge10393e2015-06-12 13:59:33 -07003056 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003057 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003058#if 0
3059 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003060 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003061 timespec ts;
3062 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003063 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003064 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003065 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003066 }
3067 ++z;
3068#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003069 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003070 if (mSignalPending) {
3071 // A signal was raised while we were unlocked
3072 mSignalPending = false;
3073 } else if (waitingAsyncCallback_l()) {
3074 if (exitPending()) {
3075 break;
3076 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003077 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003078 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003079 releaseWakeLock_l();
3080 released = true;
3081 }
Andy Hung10cbff12017-02-21 17:30:14 -08003082
3083 const int64_t waitNs = computeWaitTimeNs_l();
3084 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3085 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3086 if (status == TIMED_OUT) {
3087 mSignalPending = true; // if timeout recheck everything
3088 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003089 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003090 if (released) {
3091 acquireWakeLock_l();
3092 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003093 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3094 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003095
3096 continue;
3097 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003098 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003099 isSuspended()) {
3100 // put audio hardware into standby after short delay
3101 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003102
3103 threadLoop_standby();
3104
3105 mStandby = true;
3106 }
3107
3108 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3109 // we're about to wait, flush the binder command buffer
3110 IPCThreadState::self()->flushCommands();
3111
3112 clearOutputTracks();
3113
3114 if (exitPending()) {
3115 break;
3116 }
3117
3118 releaseWakeLock_l();
3119 // wait until we have something to do...
3120 ALOGV("%s going to sleep", myName.string());
3121 mWaitWorkCV.wait(mLock);
3122 ALOGV("%s waking up", myName.string());
3123 acquireWakeLock_l();
3124
3125 mMixerStatus = MIXER_IDLE;
3126 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3127 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003128 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003129 checkSilentMode_l();
3130
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003131 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3132 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003133 if (mType == MIXER) {
3134 sleepTimeShift = 0;
3135 }
3136
3137 continue;
3138 }
3139 }
Eric Laurent81784c32012-11-19 14:55:58 -08003140 // mMixerStatusIgnoringFastTracks is also updated internally
3141 mMixerStatus = prepareTracks_l(&tracksToRemove);
3142
Andy Hungdae27702016-10-31 14:01:16 -07003143 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003144
Eric Laurent81784c32012-11-19 14:55:58 -08003145 // prevent any changes in effect chain list and in each effect chain
3146 // during mixing and effect process as the audio buffers could be deleted
3147 // or modified if an effect is created or deleted
3148 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003149 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003150
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 if (mBytesRemaining == 0) {
3152 mCurrentWriteLength = 0;
3153 if (mMixerStatus == MIXER_TRACKS_READY) {
3154 // threadLoop_mix() sets mCurrentWriteLength
3155 threadLoop_mix();
3156 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3157 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003158 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003159 // must be written to HAL
3160 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003161 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003162 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003163 }
3164 }
Andy Hung98ef9782014-03-04 14:46:50 -08003165 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003166 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003167 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3168 // or mSinkBuffer (if there are no effects).
3169 //
3170 // This is done pre-effects computation; if effects change to
3171 // support higher precision, this needs to move.
3172 //
3173 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003174 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003175 if (mMixerBufferValid) {
3176 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3177 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3178
Andy Hung2ddee192015-12-18 17:34:44 -08003179 // mono blend occurs for mixer threads only (not direct or offloaded)
3180 // and is handled here if we're going directly to the sink.
3181 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003182 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3183 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003184 }
3185
Andy Hung98ef9782014-03-04 14:46:50 -08003186 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3187 mNormalFrameCount * mChannelCount);
3188 }
3189
Eric Laurentbfb1b832013-01-07 09:53:42 -08003190 mBytesRemaining = mCurrentWriteLength;
3191 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003192 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3193 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3194 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3195 mBytesWritten += mBytesRemaining;
3196 mFramesWritten += framesRemaining;
3197 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003198 mBytesRemaining = 0;
3199 }
Eric Laurent81784c32012-11-19 14:55:58 -08003200
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003202 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003203 for (size_t i = 0; i < effectChains.size(); i ++) {
3204 effectChains[i]->process_l();
3205 }
Eric Laurent81784c32012-11-19 14:55:58 -08003206 }
3207 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003208 // Process effect chains for offloaded thread even if no audio
3209 // was read from audio track: process only updates effect state
3210 // and thus does have to be synchronized with audio writes but may have
3211 // to be called while waiting for async write callback
3212 if (mType == OFFLOAD) {
3213 for (size_t i = 0; i < effectChains.size(); i ++) {
3214 effectChains[i]->process_l();
3215 }
3216 }
Eric Laurent81784c32012-11-19 14:55:58 -08003217
Andy Hung98ef9782014-03-04 14:46:50 -08003218 // Only if the Effects buffer is enabled and there is data in the
3219 // Effects buffer (buffer valid), we need to
3220 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003221 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003222 if (mEffectBufferValid) {
3223 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003224
3225 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003226 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3227 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003228 }
3229
Andy Hung98ef9782014-03-04 14:46:50 -08003230 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3231 mNormalFrameCount * mChannelCount);
3232 }
3233
Eric Laurent81784c32012-11-19 14:55:58 -08003234 // enable changes in effect chain
3235 unlockEffectChains(effectChains);
3236
Eric Laurentbfb1b832013-01-07 09:53:42 -08003237 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003238 // mSleepTimeUs == 0 means we must write to audio hardware
3239 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003240 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003241 // We save lastWriteFinished here, as previousLastWriteFinished,
3242 // for throttling. On thread start, previousLastWriteFinished will be
3243 // set to -1, which properly results in no throttling after the first write.
3244 nsecs_t previousLastWriteFinished = lastWriteFinished;
3245 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003246 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003247 // FIXME rewrite to reduce number of system calls
3248 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003249 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003250 lastWriteFinished = systemTime();
3251 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 if (ret < 0) {
3253 mBytesRemaining = 0;
3254 } else {
3255 mBytesWritten += ret;
3256 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003257 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 }
3259 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3260 (mMixerStatus == MIXER_DRAIN_ALL)) {
3261 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003262 }
Andy Hung08fb1742015-05-31 23:22:10 -07003263 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003264 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003265 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003266 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003267 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003268 ATRACE_NAME("underrun");
3269 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003270 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003271 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003272 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 }
Andy Hung08fb1742015-05-31 23:22:10 -07003274
3275 if (mThreadThrottle
3276 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3277 && ret > 0) { // we wrote something
3278 // Limit MixerThread data processing to no more than twice the
3279 // expected processing rate.
3280 //
3281 // This helps prevent underruns with NuPlayer and other applications
3282 // which may set up buffers that are close to the minimum size, or use
3283 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3284 //
3285 // The throttle smooths out sudden large data drains from the device,
3286 // e.g. when it comes out of standby, which often causes problems with
3287 // (1) mixer threads without a fast mixer (which has its own warm-up)
3288 // (2) minimum buffer sized tracks (even if the track is full,
3289 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003290 //
3291 // Total time spent in last processing cycle equals time spent in
3292 // 1. threadLoop_write, as well as time spent in
3293 // 2. threadLoop_mix (significant for heavy mixing, especially
3294 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003295
Andy Hung69488c42016-05-16 18:43:33 -07003296 // it's OK if deltaMs is an overestimate.
3297 const int32_t deltaMs =
3298 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003299 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3300 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3301 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003302 // notify of throttle start on verbose log
3303 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3304 "mixer(%p) throttle begin:"
3305 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003306 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003307 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003308 // Throttle must be attributed to the previous mixer loop's write time
3309 // to allow back-to-back throttling.
3310 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003311 } else {
3312 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3313 if (diff > 0) {
3314 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003315 // but prevent spamming for bluetooth
3316 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3317 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003318 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3319 }
Andy Hung08fb1742015-05-31 23:22:10 -07003320 }
3321 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003322 }
Eric Laurent81784c32012-11-19 14:55:58 -08003323
Eric Laurentbfb1b832013-01-07 09:53:42 -08003324 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003325 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003326 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003327 // suspended requires accurate metering of sleep time.
3328 if (isSuspended()) {
3329 // advance by expected sleepTime
3330 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3331 const nsecs_t nowNs = systemTime();
3332
3333 // compute expected next time vs current time.
3334 // (negative deltas are treated as delays).
3335 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3336 if (deltaNs < -kMaxNextBufferDelayNs) {
3337 // Delays longer than the max allowed trigger a reset.
3338 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3339 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3340 timeLoopNextNs = nowNs + deltaNs;
3341 } else if (deltaNs < 0) {
3342 // Delays within the max delay allowed: zero the delta/sleepTime
3343 // to help the system catch up in the next iteration(s)
3344 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3345 deltaNs = 0;
3346 }
3347 // update sleep time (which is >= 0)
3348 mSleepTimeUs = deltaNs / 1000;
3349 }
Eric Laurente93cc032016-05-05 10:15:10 -07003350 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3351 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003352 }
Glenn Kastene7754022014-10-31 12:11:26 -07003353 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003354 }
Eric Laurent81784c32012-11-19 14:55:58 -08003355 }
3356
3357 // Finally let go of removed track(s), without the lock held
3358 // since we can't guarantee the destructors won't acquire that
3359 // same lock. This will also mutate and push a new fast mixer state.
3360 threadLoop_removeTracks(tracksToRemove);
3361 tracksToRemove.clear();
3362
3363 // FIXME I don't understand the need for this here;
3364 // it was in the original code but maybe the
3365 // assignment in saveOutputTracks() makes this unnecessary?
3366 clearOutputTracks();
3367
3368 // Effect chains will be actually deleted here if they were removed from
3369 // mEffectChains list during mixing or effects processing
3370 effectChains.clear();
3371
3372 // FIXME Note that the above .clear() is no longer necessary since effectChains
3373 // is now local to this block, but will keep it for now (at least until merge done).
3374 }
3375
Eric Laurentbfb1b832013-01-07 09:53:42 -08003376 threadLoop_exit();
3377
Eric Laurentcf817a22014-08-04 20:36:31 -07003378 if (!mStandby) {
3379 threadLoop_standby();
3380 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003381 }
3382
3383 releaseWakeLock();
3384
3385 ALOGV("Thread %p type %d exiting", this, mType);
3386 return false;
3387}
3388
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389// removeTracks_l() must be called with ThreadBase::mLock held
3390void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3391{
3392 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003393 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003394 for (size_t i=0 ; i<count ; i++) {
3395 const sp<Track>& track = tracksToRemove.itemAt(i);
3396 mActiveTracks.remove(track);
3397 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3398 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3399 if (chain != 0) {
3400 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3401 track->sessionId());
3402 chain->decActiveTrackCnt();
3403 }
3404 if (track->isTerminated()) {
3405 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003406 } else { // inactive but not terminated
3407 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07003408 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08003409 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003410 }
3411 }
3412 }
3413
3414}
Eric Laurent81784c32012-11-19 14:55:58 -08003415
Eric Laurentaccc1472013-09-20 09:36:34 -07003416status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3417{
3418 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003419 ExtendedTimestamp ets;
3420 status_t status = mNormalSink->getTimestamp(ets);
3421 if (status == NO_ERROR) {
3422 status = ets.getBestTimestamp(&timestamp);
3423 }
3424 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003425 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003426 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003427 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003428 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003429 timestamp.mPosition = (uint32_t)position64;
3430 return NO_ERROR;
3431 }
3432 }
3433 return INVALID_OPERATION;
3434}
Eric Laurent1c333e22014-05-20 10:48:17 -07003435
Eric Laurent054d9d32015-04-24 08:48:48 -07003436status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3437 audio_patch_handle_t *handle)
3438{
Andy Hungf60abce2016-08-26 11:37:54 -07003439 status_t status;
3440 if (property_get_bool("af.patch_park", false /* default_value */)) {
3441 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3442 // or if HAL does not properly lock against access.
3443 AutoPark<FastMixer> park(mFastMixer);
3444 status = PlaybackThread::createAudioPatch_l(patch, handle);
3445 } else {
3446 status = PlaybackThread::createAudioPatch_l(patch, handle);
3447 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003448 return status;
3449}
3450
Eric Laurent1c333e22014-05-20 10:48:17 -07003451status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3452 audio_patch_handle_t *handle)
3453{
3454 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003455
3456 // store new device and send to effects
3457 audio_devices_t type = AUDIO_DEVICE_NONE;
3458 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3459 type |= patch->sinks[i].ext.device.type;
3460 }
3461
3462#ifdef ADD_BATTERY_DATA
3463 // when changing the audio output device, call addBatteryData to notify
3464 // the change
3465 if (mOutDevice != type) {
3466 uint32_t params = 0;
3467 // check whether speaker is on
3468 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3469 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003470 }
3471
Eric Laurent054d9d32015-04-24 08:48:48 -07003472 audio_devices_t deviceWithoutSpeaker
3473 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3474 // check if any other device (except speaker) is on
3475 if (type & deviceWithoutSpeaker) {
3476 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3477 }
3478
3479 if (params != 0) {
3480 addBatteryData(params);
3481 }
3482 }
3483#endif
3484
3485 for (size_t i = 0; i < mEffectChains.size(); i++) {
3486 mEffectChains[i]->setDevice_l(type);
3487 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003488
3489 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3490 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3491 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003492 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003493 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003494
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003495 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003496 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3497 status = hwDevice->createAudioPatch(patch->num_sources,
3498 patch->sources,
3499 patch->num_sinks,
3500 patch->sinks,
3501 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003502 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003503 char *address;
3504 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3505 //FIXME: we only support address on first sink with HAL version < 3.0
3506 address = audio_device_address_to_parameter(
3507 patch->sinks[0].ext.device.type,
3508 patch->sinks[0].ext.device.address);
3509 } else {
3510 address = (char *)calloc(1, 1);
3511 }
3512 AudioParameter param = AudioParameter(String8(address));
3513 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003514 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003515 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003516 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003517 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003518 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003519 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003520 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3521 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003522 return status;
3523}
3524
Eric Laurent054d9d32015-04-24 08:48:48 -07003525status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3526{
Andy Hungf60abce2016-08-26 11:37:54 -07003527 status_t status;
3528 if (property_get_bool("af.patch_park", false /* default_value */)) {
3529 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3530 // or if HAL does not properly lock against access.
3531 AutoPark<FastMixer> park(mFastMixer);
3532 status = PlaybackThread::releaseAudioPatch_l(handle);
3533 } else {
3534 status = PlaybackThread::releaseAudioPatch_l(handle);
3535 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003536 return status;
3537}
3538
Eric Laurent1c333e22014-05-20 10:48:17 -07003539status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3540{
3541 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003542
3543 mOutDevice = AUDIO_DEVICE_NONE;
3544
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003545 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003546 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3547 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003548 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003549 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003550 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003551 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003552 }
3553 return status;
3554}
3555
Eric Laurent83b88082014-06-20 18:31:16 -07003556void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3557{
3558 Mutex::Autolock _l(mLock);
3559 mTracks.add(track);
3560}
3561
3562void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3563{
3564 Mutex::Autolock _l(mLock);
3565 destroyTrack_l(track);
3566}
3567
3568void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3569{
3570 ThreadBase::getAudioPortConfig(config);
3571 config->role = AUDIO_PORT_ROLE_SOURCE;
3572 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3573 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3574}
3575
Eric Laurent81784c32012-11-19 14:55:58 -08003576// ----------------------------------------------------------------------------
3577
3578AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003579 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3580 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003581 // mAudioMixer below
3582 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003583 mFastMixerFutex(0),
3584 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003585 // mOutputSink below
3586 // mPipeSink below
3587 // mNormalSink below
3588{
3589 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003590 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3591 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003592 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3593 mNormalFrameCount);
3594 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3595
Andy Hungfbfc3952015-01-15 13:33:51 -08003596 if (type == DUPLICATING) {
3597 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3598 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3599 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3600 return;
3601 }
Eric Laurent81784c32012-11-19 14:55:58 -08003602 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003603 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003604 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003605 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003606#if !LOG_NDEBUG
3607 ssize_t index =
3608#else
3609 (void)
3610#endif
3611 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003612 ALOG_ASSERT(index == 0);
3613
3614 // initialize fast mixer depending on configuration
3615 bool initFastMixer;
3616 switch (kUseFastMixer) {
3617 case FastMixer_Never:
3618 initFastMixer = false;
3619 break;
3620 case FastMixer_Always:
3621 initFastMixer = true;
3622 break;
3623 case FastMixer_Static:
3624 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003625 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3626 // where the period is less than an experimentally determined threshold that can be
3627 // scheduled reliably with CFS. However, the BT A2DP HAL is
3628 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3629 initFastMixer = mFrameCount < mNormalFrameCount
3630 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003631 break;
3632 }
Andy Hungfda69402017-02-15 14:33:12 -08003633 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3634 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3635 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003636 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003637 audio_format_t fastMixerFormat;
3638 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3639 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3640 } else {
3641 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3642 }
3643 if (mFormat != fastMixerFormat) {
3644 // change our Sink format to accept our intermediate precision
3645 mFormat = fastMixerFormat;
3646 free(mSinkBuffer);
3647 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3648 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3649 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3650 }
Eric Laurent81784c32012-11-19 14:55:58 -08003651
3652 // create a MonoPipe to connect our submix to FastMixer
3653 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003654#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003655 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003656#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003657 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003658 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003659 format.mFormat = fastMixerFormat;
3660 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3661
Eric Laurent81784c32012-11-19 14:55:58 -08003662 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3663 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3664 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3665 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3666 const NBAIO_Format offers[1] = {format};
3667 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003668#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003669 ssize_t index =
3670#else
3671 (void)
3672#endif
3673 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003674 ALOG_ASSERT(index == 0);
3675 monoPipe->setAvgFrames((mScreenState & 1) ?
3676 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3677 mPipeSink = monoPipe;
3678
Glenn Kasten46909e72013-02-26 09:20:22 -08003679#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003680 if (mTeeSinkOutputEnabled) {
3681 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003682 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3683 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003684 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003685 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003686 ALOG_ASSERT(index == 0);
3687 mTeeSink = teeSink;
3688 PipeReader *teeSource = new PipeReader(*teeSink);
3689 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003690 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003691 ALOG_ASSERT(index == 0);
3692 mTeeSource = teeSource;
3693 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003694#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003695
3696 // create fast mixer and configure it initially with just one fast track for our submix
3697 mFastMixer = new FastMixer();
3698 FastMixerStateQueue *sq = mFastMixer->sq();
3699#ifdef STATE_QUEUE_DUMP
3700 sq->setObserverDump(&mStateQueueObserverDump);
3701 sq->setMutatorDump(&mStateQueueMutatorDump);
3702#endif
3703 FastMixerState *state = sq->begin();
3704 FastTrack *fastTrack = &state->mFastTracks[0];
3705 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3706 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3707 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003708 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3709 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003710 fastTrack->mGeneration++;
3711 state->mFastTracksGen++;
3712 state->mTrackMask = 1;
3713 // fast mixer will use the HAL output sink
3714 state->mOutputSink = mOutputSink.get();
3715 state->mOutputSinkGen++;
3716 state->mFrameCount = mFrameCount;
3717 state->mCommand = FastMixerState::COLD_IDLE;
3718 // already done in constructor initialization list
3719 //mFastMixerFutex = 0;
3720 state->mColdFutexAddr = &mFastMixerFutex;
3721 state->mColdGen++;
3722 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003723#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003724 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003725#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003726 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3727 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003728 sq->end();
3729 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3730
3731 // start the fast mixer
3732 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3733 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003734 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003735 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003736
3737#ifdef AUDIO_WATCHDOG
3738 // create and start the watchdog
3739 mAudioWatchdog = new AudioWatchdog();
3740 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3741 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3742 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003743 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003744#endif
3745
Eric Laurent81784c32012-11-19 14:55:58 -08003746 }
3747
3748 switch (kUseFastMixer) {
3749 case FastMixer_Never:
3750 case FastMixer_Dynamic:
3751 mNormalSink = mOutputSink;
3752 break;
3753 case FastMixer_Always:
3754 mNormalSink = mPipeSink;
3755 break;
3756 case FastMixer_Static:
3757 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3758 break;
3759 }
3760}
3761
3762AudioFlinger::MixerThread::~MixerThread()
3763{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003764 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003765 FastMixerStateQueue *sq = mFastMixer->sq();
3766 FastMixerState *state = sq->begin();
3767 if (state->mCommand == FastMixerState::COLD_IDLE) {
3768 int32_t old = android_atomic_inc(&mFastMixerFutex);
3769 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003770 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003771 }
3772 }
3773 state->mCommand = FastMixerState::EXIT;
3774 sq->end();
3775 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3776 mFastMixer->join();
3777 // Though the fast mixer thread has exited, it's state queue is still valid.
3778 // We'll use that extract the final state which contains one remaining fast track
3779 // corresponding to our sub-mix.
3780 state = sq->begin();
3781 ALOG_ASSERT(state->mTrackMask == 1);
3782 FastTrack *fastTrack = &state->mFastTracks[0];
3783 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3784 delete fastTrack->mBufferProvider;
3785 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003786 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003787#ifdef AUDIO_WATCHDOG
3788 if (mAudioWatchdog != 0) {
3789 mAudioWatchdog->requestExit();
3790 mAudioWatchdog->requestExitAndWait();
3791 mAudioWatchdog.clear();
3792 }
3793#endif
3794 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003795 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003796 delete mAudioMixer;
3797}
3798
3799
3800uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3801{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003802 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003803 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3804 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3805 }
3806 return latency;
3807}
3808
3809
3810void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3811{
3812 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3813}
3814
Eric Laurentbfb1b832013-01-07 09:53:42 -08003815ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003816{
3817 // FIXME we should only do one push per cycle; confirm this is true
3818 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003819 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003820 FastMixerStateQueue *sq = mFastMixer->sq();
3821 FastMixerState *state = sq->begin();
3822 if (state->mCommand != FastMixerState::MIX_WRITE &&
3823 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3824 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003825
3826 // FIXME workaround for first HAL write being CPU bound on some devices
3827 ATRACE_BEGIN("write");
3828 mOutput->write((char *)mSinkBuffer, 0);
3829 ATRACE_END();
3830
Eric Laurent81784c32012-11-19 14:55:58 -08003831 int32_t old = android_atomic_inc(&mFastMixerFutex);
3832 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003833 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003834 }
3835#ifdef AUDIO_WATCHDOG
3836 if (mAudioWatchdog != 0) {
3837 mAudioWatchdog->resume();
3838 }
3839#endif
3840 }
3841 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003842#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003843 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003844 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003845#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003846 sq->end();
3847 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3848 if (kUseFastMixer == FastMixer_Dynamic) {
3849 mNormalSink = mPipeSink;
3850 }
3851 } else {
3852 sq->end(false /*didModify*/);
3853 }
3854 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003855 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003856}
3857
3858void AudioFlinger::MixerThread::threadLoop_standby()
3859{
3860 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003861 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003862 FastMixerStateQueue *sq = mFastMixer->sq();
3863 FastMixerState *state = sq->begin();
3864 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003865 // Report any frames trapped in the Monopipe
3866 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3867 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3868 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3869 "monoPipeWritten:%lld monoPipeLeft:%lld",
3870 (long long)mFramesWritten, (long long)mSuspendedFrames,
3871 (long long)mPipeSink->framesWritten(), pipeFrames);
3872 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3873
Eric Laurent81784c32012-11-19 14:55:58 -08003874 state->mCommand = FastMixerState::COLD_IDLE;
3875 state->mColdFutexAddr = &mFastMixerFutex;
3876 state->mColdGen++;
3877 mFastMixerFutex = 0;
3878 sq->end();
3879 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3880 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3881 if (kUseFastMixer == FastMixer_Dynamic) {
3882 mNormalSink = mOutputSink;
3883 }
3884#ifdef AUDIO_WATCHDOG
3885 if (mAudioWatchdog != 0) {
3886 mAudioWatchdog->pause();
3887 }
3888#endif
3889 } else {
3890 sq->end(false /*didModify*/);
3891 }
3892 }
3893 PlaybackThread::threadLoop_standby();
3894}
3895
Eric Laurentbfb1b832013-01-07 09:53:42 -08003896bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3897{
3898 return false;
3899}
3900
3901bool AudioFlinger::PlaybackThread::shouldStandby_l()
3902{
3903 return !mStandby;
3904}
3905
3906bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3907{
3908 Mutex::Autolock _l(mLock);
3909 return waitingAsyncCallback_l();
3910}
3911
Eric Laurent81784c32012-11-19 14:55:58 -08003912// shared by MIXER and DIRECT, overridden by DUPLICATING
3913void AudioFlinger::PlaybackThread::threadLoop_standby()
3914{
3915 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003916 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003917 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003918 // discard any pending drain or write ack by incrementing sequence
3919 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3920 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003921 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003922 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3923 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003924 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003925 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003926}
3927
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003928void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3929{
3930 ALOGV("signal playback thread");
3931 broadcast_l();
3932}
3933
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003934void AudioFlinger::PlaybackThread::onAsyncError()
3935{
3936 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3937 invalidateTracks((audio_stream_type_t)i);
3938 }
3939}
3940
Eric Laurent81784c32012-11-19 14:55:58 -08003941void AudioFlinger::MixerThread::threadLoop_mix()
3942{
Eric Laurent81784c32012-11-19 14:55:58 -08003943 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003944 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003945 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003946 // increase sleep time progressively when application underrun condition clears.
3947 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3948 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3949 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003950 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003951 sleepTimeShift--;
3952 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003953 mSleepTimeUs = 0;
3954 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003955 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003956
Eric Laurent81784c32012-11-19 14:55:58 -08003957}
3958
3959void AudioFlinger::MixerThread::threadLoop_sleepTime()
3960{
3961 // If no tracks are ready, sleep once for the duration of an output
3962 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003963 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003964 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003965 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3966 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3967 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003968 }
3969 // reduce sleep time in case of consecutive application underruns to avoid
3970 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3971 // duration we would end up writing less data than needed by the audio HAL if
3972 // the condition persists.
3973 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3974 sleepTimeShift++;
3975 }
3976 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003977 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003978 }
3979 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003980 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3981 // before effects processing or output.
3982 if (mMixerBufferValid) {
3983 memset(mMixerBuffer, 0, mMixerBufferSize);
3984 } else {
3985 memset(mSinkBuffer, 0, mSinkBufferSize);
3986 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003987 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003988 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3989 "anticipated start");
3990 }
3991 // TODO add standby time extension fct of effect tail
3992}
3993
3994// prepareTracks_l() must be called with ThreadBase::mLock held
3995AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3996 Vector< sp<Track> > *tracksToRemove)
3997{
3998
3999 mixer_state mixerStatus = MIXER_IDLE;
4000 // find out which tracks need to be processed
4001 size_t count = mActiveTracks.size();
4002 size_t mixedTracks = 0;
4003 size_t tracksWithEffect = 0;
4004 // counts only _active_ fast tracks
4005 size_t fastTracks = 0;
4006 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4007
4008 float masterVolume = mMasterVolume;
4009 bool masterMute = mMasterMute;
4010
4011 if (masterMute) {
4012 masterVolume = 0;
4013 }
4014 // Delegate master volume control to effect in output mix effect chain if needed
4015 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4016 if (chain != 0) {
4017 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4018 chain->setVolume_l(&v, &v);
4019 masterVolume = (float)((v + (1 << 23)) >> 24);
4020 chain.clear();
4021 }
4022
4023 // prepare a new state to push
4024 FastMixerStateQueue *sq = NULL;
4025 FastMixerState *state = NULL;
4026 bool didModify = false;
4027 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004028 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004029 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004030 sq = mFastMixer->sq();
4031 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004032 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004033 }
4034
Andy Hung69aed5f2014-02-25 17:24:40 -08004035 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004036 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004037
Eric Laurent81784c32012-11-19 14:55:58 -08004038 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004039 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004040
4041 // this const just means the local variable doesn't change
4042 Track* const track = t.get();
4043
4044 // process fast tracks
4045 if (track->isFastTrack()) {
4046
4047 // It's theoretically possible (though unlikely) for a fast track to be created
4048 // and then removed within the same normal mix cycle. This is not a problem, as
4049 // the track never becomes active so it's fast mixer slot is never touched.
4050 // The converse, of removing an (active) track and then creating a new track
4051 // at the identical fast mixer slot within the same normal mix cycle,
4052 // is impossible because the slot isn't marked available until the end of each cycle.
4053 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004054 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004055 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4056 FastTrack *fastTrack = &state->mFastTracks[j];
4057
4058 // Determine whether the track is currently in underrun condition,
4059 // and whether it had a recent underrun.
4060 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4061 FastTrackUnderruns underruns = ftDump->mUnderruns;
4062 uint32_t recentFull = (underruns.mBitFields.mFull -
4063 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4064 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4065 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4066 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4067 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4068 uint32_t recentUnderruns = recentPartial + recentEmpty;
4069 track->mObservedUnderruns = underruns;
4070 // don't count underruns that occur while stopping or pausing
4071 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004072 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4073 recentUnderruns > 0) {
4074 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4075 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004076 } else {
4077 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004078 }
4079
4080 // This is similar to the state machine for normal tracks,
4081 // with a few modifications for fast tracks.
4082 bool isActive = true;
4083 switch (track->mState) {
4084 case TrackBase::STOPPING_1:
4085 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004086 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004087 track->mState = TrackBase::STOPPING_2;
4088 }
4089 break;
4090 case TrackBase::PAUSING:
4091 // ramp down is not yet implemented
4092 track->setPaused();
4093 break;
4094 case TrackBase::RESUMING:
4095 // ramp up is not yet implemented
4096 track->mState = TrackBase::ACTIVE;
4097 break;
4098 case TrackBase::ACTIVE:
4099 if (recentFull > 0 || recentPartial > 0) {
4100 // track has provided at least some frames recently: reset retry count
4101 track->mRetryCount = kMaxTrackRetries;
4102 }
4103 if (recentUnderruns == 0) {
4104 // no recent underruns: stay active
4105 break;
4106 }
4107 // there has recently been an underrun of some kind
4108 if (track->sharedBuffer() == 0) {
4109 // were any of the recent underruns "empty" (no frames available)?
4110 if (recentEmpty == 0) {
4111 // no, then ignore the partial underruns as they are allowed indefinitely
4112 break;
4113 }
4114 // there has recently been an "empty" underrun: decrement the retry counter
4115 if (--(track->mRetryCount) > 0) {
4116 break;
4117 }
4118 // indicate to client process that the track was disabled because of underrun;
4119 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004120 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004121 // remove from active list, but state remains ACTIVE [confusing but true]
4122 isActive = false;
4123 break;
4124 }
4125 // fall through
4126 case TrackBase::STOPPING_2:
4127 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004128 case TrackBase::STOPPED:
4129 case TrackBase::FLUSHED: // flush() while active
4130 // Check for presentation complete if track is inactive
4131 // We have consumed all the buffers of this track.
4132 // This would be incomplete if we auto-paused on underrun
4133 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004134 uint32_t latency = 0;
4135 status_t result = mOutput->stream->getLatency(&latency);
4136 ALOGE_IF(result != OK,
4137 "Error when retrieving output stream latency: %d", result);
4138 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004139 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004140 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4141 // track stays in active list until presentation is complete
4142 break;
4143 }
4144 }
4145 if (track->isStopping_2()) {
4146 track->mState = TrackBase::STOPPED;
4147 }
4148 if (track->isStopped()) {
4149 // Can't reset directly, as fast mixer is still polling this track
4150 // track->reset();
4151 // So instead mark this track as needing to be reset after push with ack
4152 resetMask |= 1 << i;
4153 }
4154 isActive = false;
4155 break;
4156 case TrackBase::IDLE:
4157 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004158 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004159 }
4160
4161 if (isActive) {
4162 // was it previously inactive?
4163 if (!(state->mTrackMask & (1 << j))) {
4164 ExtendedAudioBufferProvider *eabp = track;
4165 VolumeProvider *vp = track;
4166 fastTrack->mBufferProvider = eabp;
4167 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004168 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004169 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004170 fastTrack->mGeneration++;
4171 state->mTrackMask |= 1 << j;
4172 didModify = true;
4173 // no acknowledgement required for newly active tracks
4174 }
4175 // cache the combined master volume and stream type volume for fast mixer; this
4176 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004177 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004178 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004179 track->mCachedVolume = masterVolume
4180 * mStreamTypes[track->streamType()].volume
4181 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004182 ++fastTracks;
4183 } else {
4184 // was it previously active?
4185 if (state->mTrackMask & (1 << j)) {
4186 fastTrack->mBufferProvider = NULL;
4187 fastTrack->mGeneration++;
4188 state->mTrackMask &= ~(1 << j);
4189 didModify = true;
4190 // If any fast tracks were removed, we must wait for acknowledgement
4191 // because we're about to decrement the last sp<> on those tracks.
4192 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4193 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004194 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4195 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4196 j, track->mState, state->mTrackMask, recentUnderruns,
4197 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004198 }
4199 tracksToRemove->add(track);
4200 // Avoids a misleading display in dumpsys
4201 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4202 }
4203 continue;
4204 }
4205
4206 { // local variable scope to avoid goto warning
4207
4208 audio_track_cblk_t* cblk = track->cblk();
4209
4210 // The first time a track is added we wait
4211 // for all its buffers to be filled before processing it
4212 int name = track->name();
4213 // make sure that we have enough frames to mix one full buffer.
4214 // enforce this condition only once to enable draining the buffer in case the client
4215 // app does not call stop() and relies on underrun to stop:
4216 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4217 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004218 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004219 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004220 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004221
4222 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004223 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004224 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4225 // add frames already consumed but not yet released by the resampler
4226 // because mAudioTrackServerProxy->framesReady() will include these frames
4227 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4228
Eric Laurent81784c32012-11-19 14:55:58 -08004229 uint32_t minFrames = 1;
4230 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4231 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004232 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004233 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004234
4235 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004236 if (ATRACE_ENABLED()) {
4237 // I wish we had formatted trace names
4238 char traceName[16];
4239 strcpy(traceName, "nRdy");
4240 int name = track->name();
4241 if (AudioMixer::TRACK0 <= name &&
4242 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4243 name -= AudioMixer::TRACK0;
4244 traceName[4] = (name / 10) + '0';
4245 traceName[5] = (name % 10) + '0';
4246 } else {
4247 traceName[4] = '?';
4248 traceName[5] = '?';
4249 }
4250 traceName[6] = '\0';
4251 ATRACE_INT(traceName, framesReady);
4252 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004253 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004254 !track->isPaused() && !track->isTerminated())
4255 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004256 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004257
4258 mixedTracks++;
4259
Andy Hung69aed5f2014-02-25 17:24:40 -08004260 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4261 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004262 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004263 if (track->mainBuffer() != mSinkBuffer &&
4264 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004265 if (mEffectBufferEnabled) {
4266 mEffectBufferValid = true; // Later can set directly.
4267 }
Eric Laurent81784c32012-11-19 14:55:58 -08004268 chain = getEffectChain_l(track->sessionId());
4269 // Delegate volume control to effect in track effect chain if needed
4270 if (chain != 0) {
4271 tracksWithEffect++;
4272 } else {
4273 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4274 "session %d",
4275 name, track->sessionId());
4276 }
4277 }
4278
4279
4280 int param = AudioMixer::VOLUME;
4281 if (track->mFillingUpStatus == Track::FS_FILLED) {
4282 // no ramp for the first volume setting
4283 track->mFillingUpStatus = Track::FS_ACTIVE;
4284 if (track->mState == TrackBase::RESUMING) {
4285 track->mState = TrackBase::ACTIVE;
4286 param = AudioMixer::RAMP_VOLUME;
4287 }
4288 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004289 // FIXME should not make a decision based on mServer
4290 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004291 // If the track is stopped before the first frame was mixed,
4292 // do not apply ramp
4293 param = AudioMixer::RAMP_VOLUME;
4294 }
4295
4296 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004297 uint32_t vl, vr; // in U8.24 integer format
4298 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004299 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004300 vl = vr = 0;
4301 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004302 if (track->isPausing()) {
4303 track->setPaused();
4304 }
4305 } else {
4306
4307 // read original volumes with volume control
4308 float typeVolume = mStreamTypes[track->streamType()].volume;
4309 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004310 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004311 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004312 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4313 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004314 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004315 if (vlf > GAIN_FLOAT_UNITY) {
4316 ALOGV("Track left volume out of range: %.3g", vlf);
4317 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004318 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004319 if (vrf > GAIN_FLOAT_UNITY) {
4320 ALOGV("Track right volume out of range: %.3g", vrf);
4321 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004322 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004323 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004324 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004325 // now apply the master volume and stream type volume and shaper volume
4326 vlf *= v * vh;
4327 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004328 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004329 // then derive vl and vr as U8.24 versions for the effect chain
4330 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4331 vl = (uint32_t) (scaleto8_24 * vlf);
4332 vr = (uint32_t) (scaleto8_24 * vrf);
4333 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004334 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004335 // send level comes from shared memory and so may be corrupt
4336 if (sendLevel > MAX_GAIN_INT) {
4337 ALOGV("Track send level out of range: %04X", sendLevel);
4338 sendLevel = MAX_GAIN_INT;
4339 }
Andy Hung6be49402014-05-30 10:42:03 -07004340 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4341 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004342 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004343
Eric Laurent81784c32012-11-19 14:55:58 -08004344 // Delegate volume control to effect in track effect chain if needed
4345 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4346 // Do not ramp volume if volume is controlled by effect
4347 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004348 // Update remaining floating point volume levels
4349 vlf = (float)vl / (1 << 24);
4350 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004351 track->mHasVolumeController = true;
4352 } else {
4353 // force no volume ramp when volume controller was just disabled or removed
4354 // from effect chain to avoid volume spike
4355 if (track->mHasVolumeController) {
4356 param = AudioMixer::VOLUME;
4357 }
4358 track->mHasVolumeController = false;
4359 }
4360
Eric Laurent81784c32012-11-19 14:55:58 -08004361 // XXX: these things DON'T need to be done each time
4362 mAudioMixer->setBufferProvider(name, track);
4363 mAudioMixer->enable(name);
4364
Andy Hung6be49402014-05-30 10:42:03 -07004365 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4366 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4367 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004368 mAudioMixer->setParameter(
4369 name,
4370 AudioMixer::TRACK,
4371 AudioMixer::FORMAT, (void *)track->format());
4372 mAudioMixer->setParameter(
4373 name,
4374 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004375 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004376 mAudioMixer->setParameter(
4377 name,
4378 AudioMixer::TRACK,
4379 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004380 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004381 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004382 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004383 if (reqSampleRate == 0) {
4384 reqSampleRate = mSampleRate;
4385 } else if (reqSampleRate > maxSampleRate) {
4386 reqSampleRate = maxSampleRate;
4387 }
Eric Laurent81784c32012-11-19 14:55:58 -08004388 mAudioMixer->setParameter(
4389 name,
4390 AudioMixer::RESAMPLE,
4391 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004392 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004393
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004394 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004395 mAudioMixer->setParameter(
4396 name,
4397 AudioMixer::TIMESTRETCH,
4398 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004399 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004400
Andy Hung69aed5f2014-02-25 17:24:40 -08004401 /*
4402 * Select the appropriate output buffer for the track.
4403 *
Andy Hung98ef9782014-03-04 14:46:50 -08004404 * Tracks with effects go into their own effects chain buffer
4405 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004406 *
4407 * Other tracks can use mMixerBuffer for higher precision
4408 * channel accumulation. If this buffer is enabled
4409 * (mMixerBufferEnabled true), then selected tracks will accumulate
4410 * into it.
4411 *
4412 */
4413 if (mMixerBufferEnabled
4414 && (track->mainBuffer() == mSinkBuffer
4415 || track->mainBuffer() == mMixerBuffer)) {
4416 mAudioMixer->setParameter(
4417 name,
4418 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004419 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004420 mAudioMixer->setParameter(
4421 name,
4422 AudioMixer::TRACK,
4423 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4424 // TODO: override track->mainBuffer()?
4425 mMixerBufferValid = true;
4426 } else {
4427 mAudioMixer->setParameter(
4428 name,
4429 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004430 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004431 mAudioMixer->setParameter(
4432 name,
4433 AudioMixer::TRACK,
4434 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4435 }
Eric Laurent81784c32012-11-19 14:55:58 -08004436 mAudioMixer->setParameter(
4437 name,
4438 AudioMixer::TRACK,
4439 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4440
4441 // reset retry count
4442 track->mRetryCount = kMaxTrackRetries;
4443
4444 // If one track is ready, set the mixer ready if:
4445 // - the mixer was not ready during previous round OR
4446 // - no other track is not ready
4447 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4448 mixerStatus != MIXER_TRACKS_ENABLED) {
4449 mixerStatus = MIXER_TRACKS_READY;
4450 }
4451 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004452 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004453 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4454 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004455 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004456 } else {
4457 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004458 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004459
Eric Laurent81784c32012-11-19 14:55:58 -08004460 // clear effect chain input buffer if an active track underruns to avoid sending
4461 // previous audio buffer again to effects
4462 chain = getEffectChain_l(track->sessionId());
4463 if (chain != 0) {
4464 chain->clearInputBuffer();
4465 }
4466
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004467 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004468 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4469 track->isStopped() || track->isPaused()) {
4470 // We have consumed all the buffers of this track.
4471 // Remove it from the list of active tracks.
4472 // TODO: use actual buffer filling status instead of latency when available from
4473 // audio HAL
4474 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004475 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004476 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4477 if (track->isStopped()) {
4478 track->reset();
4479 }
4480 tracksToRemove->add(track);
4481 }
4482 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004483 // No buffers for this track. Give it a few chances to
4484 // fill a buffer, then remove it from active list.
4485 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004486 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004487 tracksToRemove->add(track);
4488 // indicate to client process that the track was disabled because of underrun;
4489 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004490 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004491 // If one track is not ready, mark the mixer also not ready if:
4492 // - the mixer was ready during previous round OR
4493 // - no other track is ready
4494 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4495 mixerStatus != MIXER_TRACKS_READY) {
4496 mixerStatus = MIXER_TRACKS_ENABLED;
4497 }
4498 }
4499 mAudioMixer->disable(name);
4500 }
4501
4502 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004503
4504 }
4505
4506 // Push the new FastMixer state if necessary
4507 bool pauseAudioWatchdog = false;
4508 if (didModify) {
4509 state->mFastTracksGen++;
4510 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4511 if (kUseFastMixer == FastMixer_Dynamic &&
4512 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4513 state->mCommand = FastMixerState::COLD_IDLE;
4514 state->mColdFutexAddr = &mFastMixerFutex;
4515 state->mColdGen++;
4516 mFastMixerFutex = 0;
4517 if (kUseFastMixer == FastMixer_Dynamic) {
4518 mNormalSink = mOutputSink;
4519 }
4520 // If we go into cold idle, need to wait for acknowledgement
4521 // so that fast mixer stops doing I/O.
4522 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4523 pauseAudioWatchdog = true;
4524 }
Eric Laurent81784c32012-11-19 14:55:58 -08004525 }
4526 if (sq != NULL) {
4527 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004528 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4529 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4530 // when bringing the output sink into standby.)
4531 //
4532 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4533 //
4534 // This occurs with BT suspend when we idle the FastMixer with
4535 // active tracks, which may be added or removed.
4536 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004537 }
4538#ifdef AUDIO_WATCHDOG
4539 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4540 mAudioWatchdog->pause();
4541 }
4542#endif
4543
4544 // Now perform the deferred reset on fast tracks that have stopped
4545 while (resetMask != 0) {
4546 size_t i = __builtin_ctz(resetMask);
4547 ALOG_ASSERT(i < count);
4548 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004549 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004550 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4551 track->reset();
4552 }
4553
4554 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004555 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004556
Eric Laurent97d547d2014-09-02 14:45:53 -07004557 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4558 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004559 }
4560
4561 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004562 // as long as there are effects we should clear the effects buffer, to avoid
4563 // passing a non-clean buffer to the effect chain
4564 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004565 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004566 // sink or mix buffer must be cleared if all tracks are connected to an
4567 // effect chain as in this case the mixer will not write to the sink or mix buffer
4568 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004569 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4570 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004571 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004572 if (mMixerBufferValid) {
4573 memset(mMixerBuffer, 0, mMixerBufferSize);
4574 // TODO: In testing, mSinkBuffer below need not be cleared because
4575 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4576 // after mixing.
4577 //
4578 // To enforce this guarantee:
4579 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4580 // (mixedTracks == 0 && fastTracks > 0))
4581 // must imply MIXER_TRACKS_READY.
4582 // Later, we may clear buffers regardless, and skip much of this logic.
4583 }
Andy Hung98ef9782014-03-04 14:46:50 -08004584 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004585 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004586 }
4587
4588 // if any fast tracks, then status is ready
4589 mMixerStatusIgnoringFastTracks = mixerStatus;
4590 if (fastTracks > 0) {
4591 mixerStatus = MIXER_TRACKS_READY;
4592 }
4593 return mixerStatus;
4594}
4595
Eric Laurentad7dd962016-09-22 12:38:37 -07004596// trackCountForUid_l() must be called with ThreadBase::mLock held
4597uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4598{
4599 uint32_t trackCount = 0;
4600 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004601 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004602 trackCount++;
4603 }
4604 }
4605 return trackCount;
4606}
4607
Eric Laurent81784c32012-11-19 14:55:58 -08004608// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004609int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004610 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004611{
Eric Laurentad7dd962016-09-22 12:38:37 -07004612 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4613 return -1;
4614 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004615 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004616}
4617
4618// deleteTrackName_l() must be called with ThreadBase::mLock held
4619void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4620{
4621 ALOGV("remove track (%d) and delete from mixer", name);
4622 mAudioMixer->deleteTrackName(name);
4623}
4624
Eric Laurent10351942014-05-08 18:49:52 -07004625// checkForNewParameter_l() must be called with ThreadBase::mLock held
4626bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4627 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004628{
Eric Laurent81784c32012-11-19 14:55:58 -08004629 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004630 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004631
Eric Laurent10351942014-05-08 18:49:52 -07004632 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004633
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004634 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004635
Eric Laurent10351942014-05-08 18:49:52 -07004636 AudioParameter param = AudioParameter(keyValuePair);
4637 int value;
4638 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4639 reconfig = true;
4640 }
4641 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004642 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004643 status = BAD_VALUE;
4644 } else {
4645 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004646 reconfig = true;
4647 }
Eric Laurent10351942014-05-08 18:49:52 -07004648 }
4649 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004650 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004651 status = BAD_VALUE;
4652 } else {
4653 // no need to save value, since it's constant
4654 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004655 }
Eric Laurent10351942014-05-08 18:49:52 -07004656 }
4657 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4658 // do not accept frame count changes if tracks are open as the track buffer
4659 // size depends on frame count and correct behavior would not be guaranteed
4660 // if frame count is changed after track creation
4661 if (!mTracks.isEmpty()) {
4662 status = INVALID_OPERATION;
4663 } else {
4664 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004665 }
Eric Laurent10351942014-05-08 18:49:52 -07004666 }
4667 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004668#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004669 // when changing the audio output device, call addBatteryData to notify
4670 // the change
4671 if (mOutDevice != value) {
4672 uint32_t params = 0;
4673 // check whether speaker is on
4674 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4675 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004676 }
Eric Laurent10351942014-05-08 18:49:52 -07004677
4678 audio_devices_t deviceWithoutSpeaker
4679 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4680 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004681 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004682 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4683 }
4684
4685 if (params != 0) {
4686 addBatteryData(params);
4687 }
4688 }
Eric Laurent81784c32012-11-19 14:55:58 -08004689#endif
4690
Eric Laurent10351942014-05-08 18:49:52 -07004691 // forward device change to effects that have requested to be
4692 // aware of attached audio device.
4693 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004694 a2dpDeviceChanged =
4695 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004696 mOutDevice = value;
4697 for (size_t i = 0; i < mEffectChains.size(); i++) {
4698 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004699 }
4700 }
Eric Laurent10351942014-05-08 18:49:52 -07004701 }
Eric Laurent81784c32012-11-19 14:55:58 -08004702
Eric Laurent10351942014-05-08 18:49:52 -07004703 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004704 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004705 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004706 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004707 mStandby = true;
4708 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004709 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004710 }
Eric Laurent10351942014-05-08 18:49:52 -07004711 if (status == NO_ERROR && reconfig) {
4712 readOutputParameters_l();
4713 delete mAudioMixer;
4714 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4715 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004716 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004717 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004718 if (name < 0) {
4719 break;
4720 }
4721 mTracks[i]->mName = name;
4722 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004723 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004724 }
Eric Laurent81784c32012-11-19 14:55:58 -08004725 }
4726
Eric Laurent42537be2016-01-08 17:16:42 -08004727 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004728}
4729
4730
4731void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4732{
Eric Laurent81784c32012-11-19 14:55:58 -08004733 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004734 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004735 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004736 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004737
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004738 if (hasFastMixer()) {
4739 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4740
4741 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4742 // while we are dumping it. It may be inconsistent, but it won't mutate!
4743 // This is a large object so we place it on the heap.
4744 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4745 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4746 copy->dump(fd);
4747 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004748
4749#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004750 // Similar for state queue
4751 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4752 observerCopy.dump(fd);
4753 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4754 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004755#endif
4756
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004757#ifdef AUDIO_WATCHDOG
4758 if (mAudioWatchdog != 0) {
4759 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4760 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4761 wdCopy.dump(fd);
4762 }
4763#endif
4764
4765 } else {
4766 dprintf(fd, " No FastMixer\n");
4767 }
4768
Glenn Kasten46909e72013-02-26 09:20:22 -08004769#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004770 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004771 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004772#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004773
Eric Laurent81784c32012-11-19 14:55:58 -08004774}
4775
4776uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4777{
4778 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4779}
4780
4781uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4782{
4783 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4784}
4785
4786void AudioFlinger::MixerThread::cacheParameters_l()
4787{
4788 PlaybackThread::cacheParameters_l();
4789
4790 // FIXME: Relaxed timing because of a certain device that can't meet latency
4791 // Should be reduced to 2x after the vendor fixes the driver issue
4792 // increase threshold again due to low power audio mode. The way this warning
4793 // threshold is calculated and its usefulness should be reconsidered anyway.
4794 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4795}
4796
4797// ----------------------------------------------------------------------------
4798
4799AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004800 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4801 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004802 // mLeftVolFloat, mRightVolFloat
4803{
4804}
4805
Eric Laurentbfb1b832013-01-07 09:53:42 -08004806AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4807 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004808 ThreadBase::type_t type, bool systemReady)
4809 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004810 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004811 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812{
4813}
4814
Eric Laurent81784c32012-11-19 14:55:58 -08004815AudioFlinger::DirectOutputThread::~DirectOutputThread()
4816{
4817}
4818
Eric Laurent5850c4c2016-11-10 13:04:31 -08004819void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004820{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004821 float left, right;
4822
4823 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4824 left = right = 0;
4825 } else {
4826 float typeVolume = mStreamTypes[track->streamType()].volume;
4827 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004828 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004829
Andy Hung10cbff12017-02-21 17:30:14 -08004830 // Get volumeshaper scaling
4831 std::pair<float /* volume */, bool /* active */>
4832 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004833 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004834 v *= vh.first;
4835 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004836
Glenn Kastenc56f3422014-03-21 17:53:17 -07004837 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4838 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4839 if (left > GAIN_FLOAT_UNITY) {
4840 left = GAIN_FLOAT_UNITY;
4841 }
4842 left *= v;
4843 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4844 if (right > GAIN_FLOAT_UNITY) {
4845 right = GAIN_FLOAT_UNITY;
4846 }
4847 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004848 }
4849
4850 if (lastTrack) {
4851 if (left != mLeftVolFloat || right != mRightVolFloat) {
4852 mLeftVolFloat = left;
4853 mRightVolFloat = right;
4854
4855 // Convert volumes from float to 8.24
4856 uint32_t vl = (uint32_t)(left * (1 << 24));
4857 uint32_t vr = (uint32_t)(right * (1 << 24));
4858
4859 // Delegate volume control to effect in track effect chain if needed
4860 // only one effect chain can be present on DirectOutputThread, so if
4861 // there is one, the track is connected to it
4862 if (!mEffectChains.isEmpty()) {
4863 mEffectChains[0]->setVolume_l(&vl, &vr);
4864 left = (float)vl / (1 << 24);
4865 right = (float)vr / (1 << 24);
4866 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004867 status_t result = mOutput->stream->setVolume(left, right);
4868 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004869 }
4870 }
4871}
4872
Phil Burk43b4dcc2015-06-09 16:53:44 -07004873void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4874{
4875 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004876 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004877
Eric Laurent0f0631e2015-07-06 18:01:25 -07004878 if (previousTrack != 0 && latestTrack != 0) {
4879 if (mType == DIRECT) {
4880 if (previousTrack.get() != latestTrack.get()) {
4881 mFlushPending = true;
4882 }
4883 } else /* mType == OFFLOAD */ {
4884 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4885 mFlushPending = true;
4886 }
4887 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004888 }
4889 PlaybackThread::onAddNewTrack_l();
4890}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004891
Eric Laurent81784c32012-11-19 14:55:58 -08004892AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4893 Vector< sp<Track> > *tracksToRemove
4894)
4895{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004896 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004897 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004898 bool doHwPause = false;
4899 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004900
4901 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004902 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004903 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004904 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004905 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004906 continue;
4907 }
4908
Eric Laurent5850c4c2016-11-10 13:04:31 -08004909 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004910#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004911 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004912#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004913 // Only consider last track started for volume and mixer state control.
4914 // In theory an older track could underrun and restart after the new one starts
4915 // but as we only care about the transition phase between two tracks on a
4916 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004917 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004918 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004919
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004920 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004921 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004922 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004923 doHwPause = true;
4924 mHwPaused = true;
4925 }
4926 tracksToRemove->add(track);
4927 } else if (track->isFlushPending()) {
4928 track->flushAck();
4929 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004930 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004931 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004932 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004933 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004934 if (last) {
4935 mLeftVolFloat = mRightVolFloat = -1.0;
4936 if (mHwPaused) {
4937 doHwResume = true;
4938 mHwPaused = false;
4939 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 }
4941 }
4942
Eric Laurent81784c32012-11-19 14:55:58 -08004943 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004944 // for all its buffers to be filled before processing it.
4945 // Allow draining the buffer in case the client
4946 // app does not call stop() and relies on underrun to stop:
4947 // hence the test on (track->mRetryCount > 1).
4948 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004949 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004950 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004951 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004952 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004953 minFrames = mNormalFrameCount;
4954 } else {
4955 minFrames = 1;
4956 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004957
Eric Laurentab5cdba2014-06-09 17:22:27 -07004958 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4959 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004960 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004961 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004962
4963 if (track->mFillingUpStatus == Track::FS_FILLED) {
4964 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004965 if (last) {
4966 // make sure processVolume_l() will apply new volume even if 0
4967 mLeftVolFloat = mRightVolFloat = -1.0;
4968 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004969 if (!mHwSupportsPause) {
4970 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004971 }
4972 }
4973
4974 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004975 processVolume_l(track, last);
4976 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004977 sp<Track> previousTrack = mPreviousTrack.promote();
4978 if (previousTrack != 0) {
4979 if (track != previousTrack.get()) {
4980 // Flush any data still being written from last track
4981 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004982 // Invalidate previous track to force a seek when resuming.
4983 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004984 }
4985 }
4986 mPreviousTrack = track;
4987
Eric Laurentd595b7c2013-04-03 17:27:56 -07004988 // reset retry count
4989 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004990 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004991 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004992 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004993 doHwResume = true;
4994 mHwPaused = false;
4995 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004996 }
Eric Laurent81784c32012-11-19 14:55:58 -08004997 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004998 // clear effect chain input buffer if the last active track started underruns
4999 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005000 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005001 mEffectChains[0]->clearInputBuffer();
5002 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005003 if (track->isStopping_1()) {
5004 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005005 if (last && mHwPaused) {
5006 doHwResume = true;
5007 mHwPaused = false;
5008 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005009 }
5010 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5011 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005012 // We have consumed all the buffers of this track.
5013 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005014 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005015 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005016 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5017 } else {
5018 audioHALFrames = 0;
5019 }
5020
Andy Hung818e7a32016-02-16 18:08:07 -08005021 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005022 if (mStandby || !last ||
5023 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005024 if (track->isStopping_2()) {
5025 track->mState = TrackBase::STOPPED;
5026 }
Eric Laurent81784c32012-11-19 14:55:58 -08005027 if (track->isStopped()) {
5028 track->reset();
5029 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005030 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005031 }
5032 } else {
5033 // No buffers for this track. Give it a few chances to
5034 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005035 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005036 if (--(track->mRetryCount) <= 0) {
5037 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005038 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005039 // indicate to client process that the track was disabled because of underrun;
5040 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005041 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005042 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005043 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5044 "minFrames = %u, mFormat = %#x",
5045 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005046 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005047 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005048 doHwPause = true;
5049 mHwPaused = true;
5050 }
Eric Laurent81784c32012-11-19 14:55:58 -08005051 }
5052 }
5053 }
5054 }
5055
Eric Laurentd1f69b02014-12-15 14:33:13 -08005056 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005057 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005058 for (size_t i = 0; i < mTracks.size(); i++) {
5059 if (mTracks[i]->isFlushPending()) {
5060 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005061 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 }
5063 }
5064 }
5065
5066 // make sure the pause/flush/resume sequence is executed in the right order.
5067 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5068 // before flush and then resume HW. This can happen in case of pause/flush/resume
5069 // if resume is received before pause is executed.
5070 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005071 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005072 status_t result = mOutput->stream->pause();
5073 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005074 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005075 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005076 flushHw_l();
5077 }
5078 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005079 status_t result = mOutput->stream->resume();
5080 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005081 }
Eric Laurent81784c32012-11-19 14:55:58 -08005082 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005083 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005084
5085 return mixerStatus;
5086}
5087
5088void AudioFlinger::DirectOutputThread::threadLoop_mix()
5089{
Eric Laurent81784c32012-11-19 14:55:58 -08005090 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005091 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005092 // output audio to hardware
5093 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005094 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005095 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005096 status_t status = mActiveTrack->getNextBuffer(&buffer);
5097 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005098 // no need to pad with 0 for compressed audio
5099 if (audio_has_proportional_frames(mFormat)) {
5100 memset(curBuf, 0, frameCount * mFrameSize);
5101 }
Eric Laurent81784c32012-11-19 14:55:58 -08005102 break;
5103 }
5104 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5105 frameCount -= buffer.frameCount;
5106 curBuf += buffer.frameCount * mFrameSize;
5107 mActiveTrack->releaseBuffer(&buffer);
5108 }
Andy Hung2098f272014-02-27 14:00:06 -08005109 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005110 mSleepTimeUs = 0;
5111 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005112 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005113}
5114
5115void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5116{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005117 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005118 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005119 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005120 return;
5121 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005122 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005123 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005124 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005125 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005126 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005127 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005128 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005129 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005130 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005131 }
5132}
5133
Eric Laurentd1f69b02014-12-15 14:33:13 -08005134void AudioFlinger::DirectOutputThread::threadLoop_exit()
5135{
5136 {
5137 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005138 for (size_t i = 0; i < mTracks.size(); i++) {
5139 if (mTracks[i]->isFlushPending()) {
5140 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005141 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005142 }
5143 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005144 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005145 flushHw_l();
5146 }
5147 }
5148 PlaybackThread::threadLoop_exit();
5149}
5150
5151// must be called with thread mutex locked
5152bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5153{
5154 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005155 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005156
vivek mehta9cd7ad12016-03-17 00:18:29 -07005157 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5158 return !mStandby;
5159 }
5160
Eric Laurentd1f69b02014-12-15 14:33:13 -08005161 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5162 // after a timeout and we will enter standby then.
5163 if (mTracks.size() > 0) {
5164 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005165 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5166 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005167 }
5168
Eric Laurent5cff4032015-05-26 13:49:58 -07005169 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005170}
5171
Eric Laurent81784c32012-11-19 14:55:58 -08005172// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005173int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005174 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005175{
Eric Laurentad7dd962016-09-22 12:38:37 -07005176 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5177 return -1;
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179 return 0;
5180}
5181
5182// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005183void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005184{
5185}
5186
Eric Laurent10351942014-05-08 18:49:52 -07005187// checkForNewParameter_l() must be called with ThreadBase::mLock held
5188bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5189 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005190{
5191 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005192 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005193
Eric Laurent10351942014-05-08 18:49:52 -07005194 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005195
Eric Laurent10351942014-05-08 18:49:52 -07005196 AudioParameter param = AudioParameter(keyValuePair);
5197 int value;
5198 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5199 // forward device change to effects that have requested to be
5200 // aware of attached audio device.
5201 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005202 a2dpDeviceChanged =
5203 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005204 mOutDevice = value;
5205 for (size_t i = 0; i < mEffectChains.size(); i++) {
5206 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005207 }
5208 }
Eric Laurent81784c32012-11-19 14:55:58 -08005209 }
Eric Laurent10351942014-05-08 18:49:52 -07005210 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5211 // do not accept frame count changes if tracks are open as the track buffer
5212 // size depends on frame count and correct behavior would not be garantied
5213 // if frame count is changed after track creation
5214 if (!mTracks.isEmpty()) {
5215 status = INVALID_OPERATION;
5216 } else {
5217 reconfig = true;
5218 }
5219 }
5220 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005221 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005222 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005223 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005224 mStandby = true;
5225 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005226 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005227 }
5228 if (status == NO_ERROR && reconfig) {
5229 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005230 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005231 }
5232 }
5233
Eric Laurent42537be2016-01-08 17:16:42 -08005234 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005235}
5236
5237uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5238{
5239 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005240 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005241 time = PlaybackThread::activeSleepTimeUs();
5242 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005243 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005244 }
5245 return time;
5246}
5247
5248uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5249{
5250 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005251 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005252 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5253 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005254 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005255 }
5256 return time;
5257}
5258
5259uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5260{
5261 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005262 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005263 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5264 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005265 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005266 }
5267 return time;
5268}
5269
5270void AudioFlinger::DirectOutputThread::cacheParameters_l()
5271{
5272 PlaybackThread::cacheParameters_l();
5273
5274 // use shorter standby delay as on normal output to release
5275 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005276 // no delay on outputs with HW A/V sync
5277 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005278 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005279 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005280 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005281 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005282 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005283 }
Eric Laurent81784c32012-11-19 14:55:58 -08005284}
5285
Eric Laurente659ef42014-09-29 13:06:46 -07005286void AudioFlinger::DirectOutputThread::flushHw_l()
5287{
Phil Burk062e67a2015-02-11 13:40:50 -08005288 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005289 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005290 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005291}
5292
Andy Hung10cbff12017-02-21 17:30:14 -08005293int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5294 // If a VolumeShaper is active, we must wake up periodically to update volume.
5295 const int64_t NS_PER_MS = 1000000;
5296 return mVolumeShaperActive ?
5297 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5298}
5299
Eric Laurent81784c32012-11-19 14:55:58 -08005300// ----------------------------------------------------------------------------
5301
Eric Laurentbfb1b832013-01-07 09:53:42 -08005302AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005303 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005304 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005305 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005306 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005307 mDrainSequence(0),
5308 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309{
5310}
5311
5312AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5313{
5314}
5315
5316void AudioFlinger::AsyncCallbackThread::onFirstRef()
5317{
5318 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5319}
5320
5321bool AudioFlinger::AsyncCallbackThread::threadLoop()
5322{
5323 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005324 uint32_t writeAckSequence;
5325 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005326 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005327
5328 {
5329 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005330 while (!((mWriteAckSequence & 1) ||
5331 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005332 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005333 exitPending())) {
5334 mWaitWorkCV.wait(mLock);
5335 }
5336
Eric Laurentbfb1b832013-01-07 09:53:42 -08005337 if (exitPending()) {
5338 break;
5339 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005340 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5341 mWriteAckSequence, mDrainSequence);
5342 writeAckSequence = mWriteAckSequence;
5343 mWriteAckSequence &= ~1;
5344 drainSequence = mDrainSequence;
5345 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005346 asyncError = mAsyncError;
5347 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005348 }
5349 {
Eric Laurent4de95592013-09-26 15:28:21 -07005350 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5351 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005352 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005353 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005354 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005355 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005356 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005358 if (asyncError) {
5359 playbackThread->onAsyncError();
5360 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361 }
5362 }
5363 }
5364 return false;
5365}
5366
5367void AudioFlinger::AsyncCallbackThread::exit()
5368{
5369 ALOGV("AsyncCallbackThread::exit");
5370 Mutex::Autolock _l(mLock);
5371 requestExit();
5372 mWaitWorkCV.broadcast();
5373}
5374
Eric Laurent3b4529e2013-09-05 18:09:19 -07005375void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005376{
5377 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005378 // bit 0 is cleared
5379 mWriteAckSequence = sequence << 1;
5380}
5381
5382void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5383{
5384 Mutex::Autolock _l(mLock);
5385 // ignore unexpected callbacks
5386 if (mWriteAckSequence & 2) {
5387 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005388 mWaitWorkCV.signal();
5389 }
5390}
5391
Eric Laurent3b4529e2013-09-05 18:09:19 -07005392void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005393{
5394 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005395 // bit 0 is cleared
5396 mDrainSequence = sequence << 1;
5397}
5398
5399void AudioFlinger::AsyncCallbackThread::resetDraining()
5400{
5401 Mutex::Autolock _l(mLock);
5402 // ignore unexpected callbacks
5403 if (mDrainSequence & 2) {
5404 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005405 mWaitWorkCV.signal();
5406 }
5407}
5408
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005409void AudioFlinger::AsyncCallbackThread::setAsyncError()
5410{
5411 Mutex::Autolock _l(mLock);
5412 mAsyncError = true;
5413 mWaitWorkCV.signal();
5414}
5415
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416
5417// ----------------------------------------------------------------------------
5418AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005419 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5420 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005421 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5422 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005423{
Eric Laurentfd477972013-10-25 18:10:40 -07005424 //FIXME: mStandby should be set to true by ThreadBase constructor
5425 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005426 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427}
5428
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429void AudioFlinger::OffloadThread::threadLoop_exit()
5430{
5431 if (mFlushPending || mHwPaused) {
5432 // If a flush is pending or track was paused, just discard buffered data
5433 flushHw_l();
5434 } else {
5435 mMixerStatus = MIXER_DRAIN_ALL;
5436 threadLoop_drain();
5437 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005438 if (mUseAsyncWrite) {
5439 ALOG_ASSERT(mCallbackThread != 0);
5440 mCallbackThread->exit();
5441 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442 PlaybackThread::threadLoop_exit();
5443}
5444
5445AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5446 Vector< sp<Track> > *tracksToRemove
5447)
5448{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005449 size_t count = mActiveTracks.size();
5450
5451 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005452 bool doHwPause = false;
5453 bool doHwResume = false;
5454
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005455 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005456
Eric Laurentbfb1b832013-01-07 09:53:42 -08005457 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005458 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005459 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005460#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005461 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005462#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005463 // Only consider last track started for volume and mixer state control.
5464 // In theory an older track could underrun and restart after the new one starts
5465 // but as we only care about the transition phase between two tracks on a
5466 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005467 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005468 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005469
Haynes Mathew George7844f672014-01-15 12:32:55 -08005470 if (track->isInvalid()) {
5471 ALOGW("An invalidated track shouldn't be in active list");
5472 tracksToRemove->add(track);
5473 continue;
5474 }
5475
5476 if (track->mState == TrackBase::IDLE) {
5477 ALOGW("An idle track shouldn't be in active list");
5478 continue;
5479 }
5480
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481 if (track->isPausing()) {
5482 track->setPaused();
5483 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005484 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005485 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486 mHwPaused = true;
5487 }
5488 // If we were part way through writing the mixbuffer to
5489 // the HAL we must save this until we resume
5490 // BUG - this will be wrong if a different track is made active,
5491 // in that case we want to discard the pending data in the
5492 // mixbuffer and tell the client to present it again when the
5493 // track is resumed
5494 mPausedWriteLength = mCurrentWriteLength;
5495 mPausedBytesRemaining = mBytesRemaining;
5496 mBytesRemaining = 0; // stop writing
5497 }
5498 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005499 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005500 if (track->isStopping_1()) {
5501 track->mRetryCount = kMaxTrackStopRetriesOffload;
5502 } else {
5503 track->mRetryCount = kMaxTrackRetriesOffload;
5504 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005505 track->flushAck();
5506 if (last) {
5507 mFlushPending = true;
5508 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005509 } else if (track->isResumePending()){
5510 track->resumeAck();
5511 if (last) {
5512 if (mPausedBytesRemaining) {
5513 // Need to continue write that was interrupted
5514 mCurrentWriteLength = mPausedWriteLength;
5515 mBytesRemaining = mPausedBytesRemaining;
5516 mPausedBytesRemaining = 0;
5517 }
5518 if (mHwPaused) {
5519 doHwResume = true;
5520 mHwPaused = false;
5521 // threadLoop_mix() will handle the case that we need to
5522 // resume an interrupted write
5523 }
5524 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005525 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005526
Eric Laurent3df841a2016-07-15 15:15:40 -07005527 mLeftVolFloat = mRightVolFloat = -1.0;
5528
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005529 // Do not handle new data in this iteration even if track->framesReady()
5530 mixerStatus = MIXER_TRACKS_ENABLED;
5531 }
5532 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005533 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005534 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535 if (track->mFillingUpStatus == Track::FS_FILLED) {
5536 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005537 if (last) {
5538 // make sure processVolume_l() will apply new volume even if 0
5539 mLeftVolFloat = mRightVolFloat = -1.0;
5540 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541 }
5542
5543 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005544 sp<Track> previousTrack = mPreviousTrack.promote();
5545 if (previousTrack != 0) {
5546 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005547 // Flush any data still being written from last track
5548 mBytesRemaining = 0;
5549 if (mPausedBytesRemaining) {
5550 // Last track was paused so we also need to flush saved
5551 // mixbuffer state and invalidate track so that it will
5552 // re-submit that unwritten data when it is next resumed
5553 mPausedBytesRemaining = 0;
5554 // Invalidate is a bit drastic - would be more efficient
5555 // to have a flag to tell client that some of the
5556 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005557 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005558 }
5559 // flush data already sent to the DSP if changing audio session as audio
5560 // comes from a different source. Also invalidate previous track to force a
5561 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005562 if (previousTrack->sessionId() != track->sessionId()) {
5563 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005564 }
5565 }
5566 }
5567 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005568 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005569 if (track->isStopping_1()) {
5570 track->mRetryCount = kMaxTrackStopRetriesOffload;
5571 } else {
5572 track->mRetryCount = kMaxTrackRetriesOffload;
5573 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005574 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 mixerStatus = MIXER_TRACKS_READY;
5576 }
5577 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005578 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005579 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005580 if (--(track->mRetryCount) <= 0) {
5581 // Hardware buffer can hold a large amount of audio so we must
5582 // wait for all current track's data to drain before we say
5583 // that the track is stopped.
5584 if (mBytesRemaining == 0) {
5585 // Only start draining when all data in mixbuffer
5586 // has been written
5587 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5588 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5589 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5590 if (last && !mStandby) {
5591 // do not modify drain sequence if we are already draining. This happens
5592 // when resuming from pause after drain.
5593 if ((mDrainSequence & 1) == 0) {
5594 mSleepTimeUs = 0;
5595 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5596 mixerStatus = MIXER_DRAIN_TRACK;
5597 mDrainSequence += 2;
5598 }
5599 if (mHwPaused) {
5600 // It is possible to move from PAUSED to STOPPING_1 without
5601 // a resume so we must ensure hardware is running
5602 doHwResume = true;
5603 mHwPaused = false;
5604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005605 }
5606 }
Eric Laurente93cc032016-05-05 10:15:10 -07005607 } else if (last) {
5608 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5609 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005610 }
5611 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005612 // Drain has completed or we are in standby, signal presentation complete
5613 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005614 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005615 uint32_t latency = 0;
5616 status_t result = mOutput->stream->getLatency(&latency);
5617 ALOGE_IF(result != OK,
5618 "Error when retrieving output stream latency: %d", result);
5619 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005620 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005621 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005622 track->presentationComplete(framesWritten, audioHALFrames);
5623 track->reset();
5624 tracksToRemove->add(track);
5625 }
5626 } else {
5627 // No buffers for this track. Give it a few chances to
5628 // fill a buffer, then remove it from active list.
5629 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005630 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005631 uint64_t position = 0;
5632 struct timespec unused;
5633 // The running check restarts the retry counter at least once.
5634 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5635 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5636 running = true;
5637 mOffloadUnderrunPosition = position;
5638 }
5639 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005640 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5641 (long long)position, (long long)mOffloadUnderrunPosition);
5642 }
5643 if (running) { // still running, give us more time.
5644 track->mRetryCount = kMaxTrackRetriesOffload;
5645 } else {
5646 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5647 track->name());
5648 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005649 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005650 // it will then automatically call start() when data is available
5651 track->disable();
5652 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005653 } else if (last){
5654 mixerStatus = MIXER_TRACKS_ENABLED;
5655 }
5656 }
5657 }
5658 // compute volume for this track
5659 processVolume_l(track, last);
5660 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005661
Eric Laurentea0fade2013-10-04 16:23:48 -07005662 // make sure the pause/flush/resume sequence is executed in the right order.
5663 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5664 // before flush and then resume HW. This can happen in case of pause/flush/resume
5665 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005666 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005667 status_t result = mOutput->stream->pause();
5668 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005669 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005670 if (mFlushPending) {
5671 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005672 }
Eric Laurentfd477972013-10-25 18:10:40 -07005673 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005674 status_t result = mOutput->stream->resume();
5675 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005676 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005677
Eric Laurentbfb1b832013-01-07 09:53:42 -08005678 // remove all the tracks that need to be...
5679 removeTracks_l(*tracksToRemove);
5680
5681 return mixerStatus;
5682}
5683
Eric Laurentbfb1b832013-01-07 09:53:42 -08005684// must be called with thread mutex locked
5685bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5686{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005687 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5688 mWriteAckSequence, mDrainSequence);
5689 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005690 return true;
5691 }
5692 return false;
5693}
5694
Eric Laurentbfb1b832013-01-07 09:53:42 -08005695bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5696{
5697 Mutex::Autolock _l(mLock);
5698 return waitingAsyncCallback_l();
5699}
5700
5701void AudioFlinger::OffloadThread::flushHw_l()
5702{
Eric Laurente659ef42014-09-29 13:06:46 -07005703 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704 // Flush anything still waiting in the mixbuffer
5705 mCurrentWriteLength = 0;
5706 mBytesRemaining = 0;
5707 mPausedWriteLength = 0;
5708 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005709 // reset bytes written count to reflect that DSP buffers are empty after flush.
5710 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005711 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005712
Eric Laurentbfb1b832013-01-07 09:53:42 -08005713 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005714 // discard any pending drain or write ack by incrementing sequence
5715 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5716 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005717 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005718 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5719 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005720 }
5721}
5722
Haynes Mathew George05317d22016-05-03 16:34:26 -07005723void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5724{
5725 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005726 if (PlaybackThread::invalidateTracks_l(streamType)) {
5727 mFlushPending = true;
5728 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005729}
5730
Eric Laurentbfb1b832013-01-07 09:53:42 -08005731// ----------------------------------------------------------------------------
5732
Eric Laurent81784c32012-11-19 14:55:58 -08005733AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005734 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005735 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005736 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005737 mWaitTimeMs(UINT_MAX)
5738{
5739 addOutputTrack(mainThread);
5740}
5741
5742AudioFlinger::DuplicatingThread::~DuplicatingThread()
5743{
5744 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5745 mOutputTracks[i]->destroy();
5746 }
5747}
5748
5749void AudioFlinger::DuplicatingThread::threadLoop_mix()
5750{
5751 // mix buffers...
5752 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005753 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005754 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005755 if (mMixerBufferValid) {
5756 memset(mMixerBuffer, 0, mMixerBufferSize);
5757 } else {
5758 memset(mSinkBuffer, 0, mSinkBufferSize);
5759 }
Eric Laurent81784c32012-11-19 14:55:58 -08005760 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005761 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005762 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005763 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005764 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005765}
5766
5767void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5768{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005769 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005770 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005771 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005772 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005773 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005774 }
5775 } else if (mBytesWritten != 0) {
5776 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5777 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005778 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005779 } else {
5780 // flush remaining overflow buffers in output tracks
5781 writeFrames = 0;
5782 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005783 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005784 }
5785}
5786
Eric Laurentbfb1b832013-01-07 09:53:42 -08005787ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005788{
5789 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005790 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005791 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005792 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005793 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005794}
5795
5796void AudioFlinger::DuplicatingThread::threadLoop_standby()
5797{
5798 // DuplicatingThread implements standby by stopping all tracks
5799 for (size_t i = 0; i < outputTracks.size(); i++) {
5800 outputTracks[i]->stop();
5801 }
5802}
5803
5804void AudioFlinger::DuplicatingThread::saveOutputTracks()
5805{
5806 outputTracks = mOutputTracks;
5807}
5808
5809void AudioFlinger::DuplicatingThread::clearOutputTracks()
5810{
5811 outputTracks.clear();
5812}
5813
5814void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5815{
5816 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005817 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5818 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5819 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5820 const size_t frameCount =
5821 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5822 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5823 // from different OutputTracks and their associated MixerThreads (e.g. one may
5824 // nearly empty and the other may be dropping data).
5825
5826 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005827 this,
5828 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005829 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005830 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005831 frameCount,
5832 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005833 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5834 if (status != NO_ERROR) {
5835 ALOGE("addOutputTrack() initCheck failed %d", status);
5836 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005837 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005838 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5839 mOutputTracks.add(outputTrack);
5840 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5841 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005842}
5843
5844void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5845{
5846 Mutex::Autolock _l(mLock);
5847 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5848 if (mOutputTracks[i]->thread() == thread) {
5849 mOutputTracks[i]->destroy();
5850 mOutputTracks.removeAt(i);
5851 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005852 if (thread->getOutput() == mOutput) {
5853 mOutput = NULL;
5854 }
Eric Laurent81784c32012-11-19 14:55:58 -08005855 return;
5856 }
5857 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005858 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005859}
5860
5861// caller must hold mLock
5862void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5863{
5864 mWaitTimeMs = UINT_MAX;
5865 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5866 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5867 if (strong != 0) {
5868 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5869 if (waitTimeMs < mWaitTimeMs) {
5870 mWaitTimeMs = waitTimeMs;
5871 }
5872 }
5873 }
5874}
5875
5876
5877bool AudioFlinger::DuplicatingThread::outputsReady(
5878 const SortedVector< sp<OutputTrack> > &outputTracks)
5879{
5880 for (size_t i = 0; i < outputTracks.size(); i++) {
5881 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5882 if (thread == 0) {
5883 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5884 outputTracks[i].get());
5885 return false;
5886 }
5887 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5888 // see note at standby() declaration
5889 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5890 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5891 thread.get());
5892 return false;
5893 }
5894 }
5895 return true;
5896}
5897
5898uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5899{
5900 return (mWaitTimeMs * 1000) / 2;
5901}
5902
5903void AudioFlinger::DuplicatingThread::cacheParameters_l()
5904{
5905 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5906 updateWaitTime_l();
5907
5908 MixerThread::cacheParameters_l();
5909}
5910
Eric Laurent6acd1d42017-01-04 14:23:29 -08005911
Eric Laurent81784c32012-11-19 14:55:58 -08005912// ----------------------------------------------------------------------------
5913// Record
5914// ----------------------------------------------------------------------------
5915
5916AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5917 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005918 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005919 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005920 audio_devices_t inDevice,
5921 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005922#ifdef TEE_SINK
5923 , const sp<NBAIO_Sink>& teeSink
5924#endif
5925 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005926 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005927 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005928 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005929 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005930#ifdef TEE_SINK
5931 , mTeeSink(teeSink)
5932#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005933 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5934 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005935 // mFastCapture below
5936 , mFastCaptureFutex(0)
5937 // mInputSource
5938 // mPipeSink
5939 // mPipeSource
5940 , mPipeFramesP2(0)
5941 // mPipeMemory
5942 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005943 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07005944 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005945{
Glenn Kastend7dca052015-03-05 16:05:54 -08005946 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5947 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005948
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005949 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005950
5951 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005952 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005953 size_t numCounterOffers = 0;
5954 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005955#if !LOG_NDEBUG
5956 ssize_t index =
5957#else
5958 (void)
5959#endif
5960 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005961 ALOG_ASSERT(index == 0);
5962
5963 // initialize fast capture depending on configuration
5964 bool initFastCapture;
5965 switch (kUseFastCapture) {
5966 case FastCapture_Never:
5967 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005968 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005969 break;
5970 case FastCapture_Always:
5971 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005972 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005973 break;
5974 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005975 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005976 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
5977 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
5978 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005979 break;
5980 // case FastCapture_Dynamic:
5981 }
5982
5983 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005984 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005985 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005986 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5987 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005988 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005989 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005990 const sp<MemoryDealer> roHeap(readOnlyHeap());
5991 sp<IMemory> pipeMemory;
5992 if ((roHeap == 0) ||
5993 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005994 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
5995 ALOGE("not enough memory for pipe buffer size=%zu; "
5996 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
5997 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
5998 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005999 goto failed;
6000 }
6001 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6002 memset(pipeBuffer, 0, pipeSize);
6003 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6004 const NBAIO_Format offers[1] = {format};
6005 size_t numCounterOffers = 0;
6006 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6007 ALOG_ASSERT(index == 0);
6008 mPipeSink = pipe;
6009 PipeReader *pipeReader = new PipeReader(*pipe);
6010 numCounterOffers = 0;
6011 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6012 ALOG_ASSERT(index == 0);
6013 mPipeSource = pipeReader;
6014 mPipeFramesP2 = pipeFramesP2;
6015 mPipeMemory = pipeMemory;
6016
6017 // create fast capture
6018 mFastCapture = new FastCapture();
6019 FastCaptureStateQueue *sq = mFastCapture->sq();
6020#ifdef STATE_QUEUE_DUMP
6021 // FIXME
6022#endif
6023 FastCaptureState *state = sq->begin();
6024 state->mCblk = NULL;
6025 state->mInputSource = mInputSource.get();
6026 state->mInputSourceGen++;
6027 state->mPipeSink = pipe;
6028 state->mPipeSinkGen++;
6029 state->mFrameCount = mFrameCount;
6030 state->mCommand = FastCaptureState::COLD_IDLE;
6031 // already done in constructor initialization list
6032 //mFastCaptureFutex = 0;
6033 state->mColdFutexAddr = &mFastCaptureFutex;
6034 state->mColdGen++;
6035 state->mDumpState = &mFastCaptureDumpState;
6036#ifdef TEE_SINK
6037 // FIXME
6038#endif
6039 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6040 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6041 sq->end();
6042 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6043
6044 // start the fast capture
6045 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6046 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006047 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006048 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006049#ifdef AUDIO_WATCHDOG
6050 // FIXME
6051#endif
6052
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006053 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054 }
6055failed: ;
6056
6057 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006058}
6059
Eric Laurent81784c32012-11-19 14:55:58 -08006060AudioFlinger::RecordThread::~RecordThread()
6061{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006062 if (mFastCapture != 0) {
6063 FastCaptureStateQueue *sq = mFastCapture->sq();
6064 FastCaptureState *state = sq->begin();
6065 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6066 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6067 if (old == -1) {
6068 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6069 }
6070 }
6071 state->mCommand = FastCaptureState::EXIT;
6072 sq->end();
6073 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6074 mFastCapture->join();
6075 mFastCapture.clear();
6076 }
6077 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006078 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006079 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006080}
6081
6082void AudioFlinger::RecordThread::onFirstRef()
6083{
Glenn Kastend7dca052015-03-05 16:05:54 -08006084 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006085}
6086
Eric Laurent555530a2017-02-07 18:17:24 -08006087void AudioFlinger::RecordThread::preExit()
6088{
6089 ALOGV(" preExit()");
6090 Mutex::Autolock _l(mLock);
6091 for (size_t i = 0; i < mTracks.size(); i++) {
6092 sp<RecordTrack> track = mTracks[i];
6093 track->invalidate();
6094 }
6095 mActiveTracks.clear();
6096 mStartStopCond.broadcast();
6097}
6098
Eric Laurent81784c32012-11-19 14:55:58 -08006099bool AudioFlinger::RecordThread::threadLoop()
6100{
Eric Laurent81784c32012-11-19 14:55:58 -08006101 nsecs_t lastWarning = 0;
6102
6103 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006104
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006105reacquire_wakelock:
6106 sp<RecordTrack> activeTrack;
6107 {
6108 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006109 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006110 }
6111
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006112 // used to request a deferred sleep, to be executed later while mutex is unlocked
6113 uint32_t sleepUs = 0;
6114
6115 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006116 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006117 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006118
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006119 // activeTracks accumulates a copy of a subset of mActiveTracks
6120 Vector< sp<RecordTrack> > activeTracks;
6121
Glenn Kasten735f45f2014-08-18 15:51:59 -07006122 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006123 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006124
Glenn Kasten735f45f2014-08-18 15:51:59 -07006125 // reference to a fast track which is about to be removed
6126 sp<RecordTrack> fastTrackToRemove;
6127
Eric Laurent81784c32012-11-19 14:55:58 -08006128 { // scope for mLock
6129 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006130
Eric Laurent021cf962014-05-13 10:18:14 -07006131 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006132
Eric Laurent000a4192014-01-29 15:17:32 -08006133 // check exitPending here because checkForNewParameters_l() and
6134 // checkForNewParameters_l() can temporarily release mLock
6135 if (exitPending()) {
6136 break;
6137 }
6138
Eric Laurent5c25d562016-07-13 17:17:45 -07006139 // sleep with mutex unlocked
6140 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006141 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006142 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6143 ATRACE_END();
6144 sleepUs = 0;
6145 continue;
6146 }
6147
Glenn Kasten2b806402013-11-20 16:37:38 -08006148 // if no active track(s), then standby and release wakelock
6149 size_t size = mActiveTracks.size();
6150 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006151 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006152 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006153 releaseWakeLock_l();
6154 ALOGV("RecordThread: loop stopping");
6155 // go to sleep
6156 mWaitWorkCV.wait(mLock);
6157 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006158 goto reacquire_wakelock;
6159 }
6160
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006161 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006162 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006163 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006164
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006165 activeTrack = mActiveTracks[i];
6166 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006167 if (activeTrack->isFastTrack()) {
6168 ALOG_ASSERT(fastTrackToRemove == 0);
6169 fastTrackToRemove = activeTrack;
6170 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006171 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006172 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006173 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006174 continue;
6175 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176
6177 TrackBase::track_state activeTrackState = activeTrack->mState;
6178 switch (activeTrackState) {
6179
6180 case TrackBase::PAUSING:
6181 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 doBroadcast = true;
6183 size--;
6184 continue;
6185
6186 case TrackBase::STARTING_1:
6187 sleepUs = 10000;
6188 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006189 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006190 continue;
6191
6192 case TrackBase::STARTING_2:
6193 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006194 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006195 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006196 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006197 break;
6198
6199 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006200 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006201 break;
6202
6203 case TrackBase::IDLE:
6204 i++;
6205 continue;
6206
6207 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006208 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006209 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006210
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006211 activeTracks.add(activeTrack);
6212 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006214 if (activeTrack->isFastTrack()) {
6215 ALOG_ASSERT(!mFastTrackAvail);
6216 ALOG_ASSERT(fastTrack == 0);
6217 fastTrack = activeTrack;
6218 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006219 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006220
Andy Hungdae27702016-10-31 14:01:16 -07006221 mActiveTracks.updatePowerState(this);
6222
Eric Laurent5c25d562016-07-13 17:17:45 -07006223 if (allStopped) {
6224 standbyIfNotAlreadyInStandby();
6225 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006226 if (doBroadcast) {
6227 mStartStopCond.broadcast();
6228 }
6229
6230 // sleep if there are no active tracks to process
6231 if (activeTracks.size() == 0) {
6232 if (sleepUs == 0) {
6233 sleepUs = kRecordThreadSleepUs;
6234 }
6235 continue;
6236 }
6237 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006238
Eric Laurent81784c32012-11-19 14:55:58 -08006239 lockEffectChains_l(effectChains);
6240 }
6241
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006242 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006243
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006244 size_t size = effectChains.size();
6245 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006246 // thread mutex is not locked, but effect chain is locked
6247 effectChains[i]->process_l();
6248 }
6249
Glenn Kasten735f45f2014-08-18 15:51:59 -07006250 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006251 if (mFastCapture != 0) {
6252 FastCaptureStateQueue *sq = mFastCapture->sq();
6253 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006254 bool didModify = false;
6255 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006256 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6257 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6258 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6259 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6260 if (old == -1) {
6261 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6262 }
6263 }
6264 state->mCommand = FastCaptureState::READ_WRITE;
6265#if 0 // FIXME
6266 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006267 FastThreadDumpState::kSamplingNforLowRamDevice :
6268 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006269#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006270 didModify = true;
6271 }
6272 audio_track_cblk_t *cblkOld = state->mCblk;
6273 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6274 if (cblkNew != cblkOld) {
6275 state->mCblk = cblkNew;
6276 // block until acked if removing a fast track
6277 if (cblkOld != NULL) {
6278 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6279 }
6280 didModify = true;
6281 }
6282 sq->end(didModify);
6283 if (didModify) {
6284 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006285#if 0
6286 if (kUseFastCapture == FastCapture_Dynamic) {
6287 mNormalSource = mPipeSource;
6288 }
6289#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006290 }
6291 }
6292
Glenn Kasten735f45f2014-08-18 15:51:59 -07006293 // now run the fast track destructor with thread mutex unlocked
6294 fastTrackToRemove.clear();
6295
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006296 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6297 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6298 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6299 // If destination is non-contiguous, first read past the nominal end of buffer, then
6300 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006301
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006302 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006303 ssize_t framesRead;
6304
6305 // If an NBAIO source is present, use it to read the normal capture's data
6306 if (mPipeSource != 0) {
6307 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006308 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006309 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006310 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006311 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6312 // buffer size or at least for 20ms.
6313 size_t sleepFrames = max(
6314 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6315 if (framesRead <= (ssize_t) sleepFrames) {
6316 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6317 }
6318 if (framesRead < 0) {
6319 status_t status = (status_t) framesRead;
6320 switch (status) {
6321 case OVERRUN:
6322 ALOGW("overrun on read from pipe");
6323 framesRead = 0;
6324 break;
6325 case NEGOTIATE:
6326 ALOGE("re-negotiation is needed");
6327 framesRead = -1; // Will cause an attempt to recover.
6328 break;
6329 default:
6330 ALOGE("unknown error %d on read from pipe", status);
6331 break;
6332 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006333 }
6334 // otherwise use the HAL / AudioStreamIn directly
6335 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006336 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006337 size_t bytesRead;
6338 status_t result = mInput->stream->read(
6339 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006340 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006341 if (result < 0) {
6342 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006343 } else {
6344 framesRead = bytesRead / mFrameSize;
6345 }
6346 }
6347
Andy Hung3f0c9022016-01-15 17:49:46 -08006348 // Update server timestamp with server stats
6349 // systemTime() is optional if the hardware supports timestamps.
6350 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6351 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6352
6353 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006354 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006355 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006356 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006357 if (ret == NO_ERROR) {
6358 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6359 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6360 // Note: In general record buffers should tend to be empty in
6361 // a properly running pipeline.
6362 //
6363 // Also, it is not advantageous to call get_presentation_position during the read
6364 // as the read obtains a lock, preventing the timestamp call from executing.
6365 }
6366 }
6367 // Use this to track timestamp information
6368 // ALOGD("%s", mTimestamp.toString().c_str());
6369
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006370 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006371 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006372 // Force input into standby so that it tries to recover at next read attempt
6373 inputStandBy();
6374 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006375 }
6376 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006377 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006378 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006379 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006380
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006382 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006383 }
6384 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006385 {
6386 size_t part1 = mRsmpInFramesP2 - rear;
6387 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006388 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006389 (framesRead - part1) * mFrameSize);
6390 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006391 }
6392 rear = mRsmpInRear += framesRead;
6393
6394 size = activeTracks.size();
6395 // loop over each active track
6396 for (size_t i = 0; i < size; i++) {
6397 activeTrack = activeTracks[i];
6398
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006399 // skip fast tracks, as those are handled directly by FastCapture
6400 if (activeTrack->isFastTrack()) {
6401 continue;
6402 }
6403
Andy Hung73c02e42015-03-29 01:13:58 -07006404 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006405 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6406
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006407 enum {
6408 OVERRUN_UNKNOWN,
6409 OVERRUN_TRUE,
6410 OVERRUN_FALSE
6411 } overrun = OVERRUN_UNKNOWN;
6412
6413 // loop over getNextBuffer to handle circular sink
6414 for (;;) {
6415
6416 activeTrack->mSink.frameCount = ~0;
6417 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6418 size_t framesOut = activeTrack->mSink.frameCount;
6419 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6420
Andy Hung73c02e42015-03-29 01:13:58 -07006421 // check available frames and handle overrun conditions
6422 // if the record track isn't draining fast enough.
6423 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006424 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006425 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6426 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006427 overrun = OVERRUN_TRUE;
6428 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006429 if (framesOut == 0 || framesIn == 0) {
6430 break;
6431 }
6432
Andy Hung6770c6f2015-04-07 13:43:36 -07006433 // Don't allow framesOut to be larger than what is possible with resampling
6434 // from framesIn.
6435 // This isn't strictly necessary but helps limit buffer resizing in
6436 // RecordBufferConverter. TODO: remove when no longer needed.
6437 framesOut = min(framesOut,
6438 destinationFramesPossible(
6439 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006440 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6441 framesOut = activeTrack->mRecordBufferConverter->convert(
6442 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006443
6444 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6445 overrun = OVERRUN_FALSE;
6446 }
6447
6448 if (activeTrack->mFramesToDrop == 0) {
6449 if (framesOut > 0) {
6450 activeTrack->mSink.frameCount = framesOut;
6451 activeTrack->releaseBuffer(&activeTrack->mSink);
6452 }
6453 } else {
6454 // FIXME could do a partial drop of framesOut
6455 if (activeTrack->mFramesToDrop > 0) {
6456 activeTrack->mFramesToDrop -= framesOut;
6457 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006458 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006459 }
6460 } else {
6461 activeTrack->mFramesToDrop += framesOut;
6462 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6463 activeTrack->mSyncStartEvent->isCancelled()) {
6464 ALOGW("Synced record %s, session %d, trigger session %d",
6465 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6466 activeTrack->sessionId(),
6467 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006468 activeTrack->mSyncStartEvent->triggerSession() :
6469 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006470 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006471 }
6472 }
6473 }
6474
6475 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006477 }
6478 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006479
6480 switch (overrun) {
6481 case OVERRUN_TRUE:
6482 // client isn't retrieving buffers fast enough
6483 if (!activeTrack->setOverflow()) {
6484 nsecs_t now = systemTime();
6485 // FIXME should lastWarning per track?
6486 if ((now - lastWarning) > kWarningThrottleNs) {
6487 ALOGW("RecordThread: buffer overflow");
6488 lastWarning = now;
6489 }
6490 }
6491 break;
6492 case OVERRUN_FALSE:
6493 activeTrack->clearOverflow();
6494 break;
6495 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006496 break;
6497 }
6498
Andy Hung3f0c9022016-01-15 17:49:46 -08006499 // update frame information and push timestamp out
6500 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006501 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006502 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6503 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006504 }
6505
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006506unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006507 // enable changes in effect chain
6508 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006509 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006510 }
6511
Glenn Kasten93e471f2013-08-19 08:40:07 -07006512 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006513
6514 {
6515 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006516 for (size_t i = 0; i < mTracks.size(); i++) {
6517 sp<RecordTrack> track = mTracks[i];
6518 track->invalidate();
6519 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006520 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006521 mStartStopCond.broadcast();
6522 }
6523
6524 releaseWakeLock();
6525
6526 ALOGV("RecordThread %p exiting", this);
6527 return false;
6528}
6529
Glenn Kasten93e471f2013-08-19 08:40:07 -07006530void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006531{
6532 if (!mStandby) {
6533 inputStandBy();
6534 mStandby = true;
6535 }
6536}
6537
6538void AudioFlinger::RecordThread::inputStandBy()
6539{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006540 // Idle the fast capture if it's currently running
6541 if (mFastCapture != 0) {
6542 FastCaptureStateQueue *sq = mFastCapture->sq();
6543 FastCaptureState *state = sq->begin();
6544 if (!(state->mCommand & FastCaptureState::IDLE)) {
6545 state->mCommand = FastCaptureState::COLD_IDLE;
6546 state->mColdFutexAddr = &mFastCaptureFutex;
6547 state->mColdGen++;
6548 mFastCaptureFutex = 0;
6549 sq->end();
6550 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6551 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6552#if 0
6553 if (kUseFastCapture == FastCapture_Dynamic) {
6554 // FIXME
6555 }
6556#endif
6557#ifdef AUDIO_WATCHDOG
6558 // FIXME
6559#endif
6560 } else {
6561 sq->end(false /*didModify*/);
6562 }
6563 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006564 status_t result = mInput->stream->standby();
6565 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006566
6567 // If going into standby, flush the pipe source.
6568 if (mPipeSource.get() != nullptr) {
6569 const ssize_t flushed = mPipeSource->flush();
6570 if (flushed > 0) {
6571 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6572 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6573 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6574 }
6575 }
Eric Laurent81784c32012-11-19 14:55:58 -08006576}
6577
Glenn Kasten05997e22014-03-13 15:08:33 -07006578// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006579sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006580 const sp<AudioFlinger::Client>& client,
6581 uint32_t sampleRate,
6582 audio_format_t format,
6583 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006584 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006585 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006586 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006587 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006588 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006589 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006590 status_t *status,
6591 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006592{
Glenn Kasten74935e42013-12-19 08:56:45 -08006593 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006594 sp<RecordTrack> track;
6595 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006596 audio_input_flags_t inputFlags = mInput->flags;
6597
6598 // special case for FAST flag considered OK if fast capture is present
6599 if (hasFastCapture()) {
6600 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6601 }
6602
6603 // Check if requested flags are compatible with output stream flags
6604 if ((*flags & inputFlags) != *flags) {
6605 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6606 " input flags (%08x)",
6607 *flags, inputFlags);
6608 *flags = (audio_input_flags_t)(*flags & inputFlags);
6609 }
Eric Laurent81784c32012-11-19 14:55:58 -08006610
Glenn Kasten90e58b12013-07-31 16:16:02 -07006611 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006612 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006613 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006614 // we formerly checked for a callback handler (non-0 tid),
6615 // but that is no longer required for TRANSFER_OBTAIN mode
6616 //
Glenn Kasten74105912014-07-03 12:28:53 -07006617 // frame count is not specified, or is exactly the pipe depth
6618 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006619 // PCM data
6620 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006621 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006622 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006623 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006624 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006625 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006626 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006627 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006628 hasFastCapture() &&
6629 // there are sufficient fast track slots available
6630 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006631 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006632 // check compatibility with audio effects.
6633 Mutex::Autolock _l(mLock);
6634 // Do not accept FAST flag if the session has software effects
6635 sp<EffectChain> chain = getEffectChain_l(sessionId);
6636 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006637 audio_input_flags_t old = *flags;
6638 chain->checkInputFlagCompatibility(flags);
6639 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006640 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6641 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006642 }
6643 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006644 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006645 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6646 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006647 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006648 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6649 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006650 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006651 this, frameCount, mFrameCount, mPipeFramesP2,
6652 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006653 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006654 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006655 }
6656 }
6657
6658 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006659 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006660 // fast track: frame count is exactly the pipe depth
6661 frameCount = mPipeFramesP2;
6662 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6663 *notificationFrames = mFrameCount;
6664 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006665 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6666 // or 20 ms if there is a fast capture
6667 // TODO This could be a roundupRatio inline, and const
6668 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6669 * sampleRate + mSampleRate - 1) / mSampleRate;
6670 // minimum number of notification periods is at least kMinNotifications,
6671 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6672 static const size_t kMinNotifications = 3;
6673 static const uint32_t kMinMs = 30;
6674 // TODO This could be a roundupRatio inline
6675 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6676 // TODO This could be a roundupRatio inline
6677 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6678 maxNotificationFrames;
6679 const size_t minFrameCount = maxNotificationFrames *
6680 max(kMinNotifications, minNotificationsByMs);
6681 frameCount = max(frameCount, minFrameCount);
6682 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6683 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006684 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006685 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006686 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006687
Glenn Kasten15e57982013-09-24 11:52:37 -07006688 lStatus = initCheck();
6689 if (lStatus != NO_ERROR) {
6690 ALOGE("createRecordTrack_l() audio driver not initialized");
6691 goto Exit;
6692 }
Eric Laurent81784c32012-11-19 14:55:58 -08006693
6694 { // scope for mLock
6695 Mutex::Autolock _l(mLock);
6696
6697 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006698 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006699 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006700
Glenn Kasten03003332013-08-06 15:40:54 -07006701 lStatus = track->initCheck();
6702 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006703 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006704 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006705 goto Exit;
6706 }
6707 mTracks.add(track);
6708
Eric Laurent05067782016-06-01 18:27:28 -07006709 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006710 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6711 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6712 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006713 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006714 }
Eric Laurent81784c32012-11-19 14:55:58 -08006715 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006716
Eric Laurent81784c32012-11-19 14:55:58 -08006717 lStatus = NO_ERROR;
6718
6719Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006720 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006721 return track;
6722}
6723
6724status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6725 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006726 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006727{
6728 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6729 sp<ThreadBase> strongMe = this;
6730 status_t status = NO_ERROR;
6731
6732 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006733 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006734 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006735 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006736 triggerSession,
6737 recordTrack->sessionId(),
6738 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006739 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006740 // Sync event can be cancelled by the trigger session if the track is not in a
6741 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006742 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006743 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006744 } else {
6745 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006746 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006747 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006748 }
6749 }
6750
6751 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006752 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006753 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006754 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6755 if (recordTrack->mState == TrackBase::PAUSING) {
6756 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006757 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758 } else {
6759 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006760 }
6761 return status;
6762 }
6763
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006764 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6765 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6766 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006767 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006768 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006769 status_t status = NO_ERROR;
6770 if (recordTrack->isExternalTrack()) {
6771 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006772 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006773 mLock.lock();
6774 // FIXME should verify that recordTrack is still in mActiveTracks
6775 if (status != NO_ERROR) {
6776 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006777 recordTrack->clearSyncStartEvent();
6778 ALOGV("RecordThread::start error %d", status);
6779 return status;
6780 }
Eric Laurent81784c32012-11-19 14:55:58 -08006781 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006782 // Catch up with current buffer indices if thread is already running.
6783 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6784 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6785 // see previously buffered data before it called start(), but with greater risk of overrun.
6786
Andy Hung73c02e42015-03-29 01:13:58 -07006787 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006788 // clear any converter state as new data will be discontinuous
6789 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006790 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006791 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006792 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006793 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006794 ALOGV("Record failed to start");
6795 status = BAD_VALUE;
6796 goto startError;
6797 }
Eric Laurent81784c32012-11-19 14:55:58 -08006798 return status;
6799 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006800
Eric Laurent81784c32012-11-19 14:55:58 -08006801startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006802 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006803 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006804 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006805 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006806 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006807 return status;
6808}
6809
Eric Laurent81784c32012-11-19 14:55:58 -08006810void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6811{
6812 sp<SyncEvent> strongEvent = event.promote();
6813
6814 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006815 sp<RefBase> ptr = strongEvent->cookie().promote();
6816 if (ptr != 0) {
6817 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6818 recordTrack->handleSyncStartEvent(strongEvent);
6819 }
Eric Laurent81784c32012-11-19 14:55:58 -08006820 }
6821}
6822
Glenn Kastena8356f62013-07-25 14:37:52 -07006823bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006824 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006825 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006826 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006827 return false;
6828 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006829 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006830 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006831 // signal thread to stop
6832 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006833 // do not wait for mStartStopCond if exiting
6834 if (exitPending()) {
6835 return true;
6836 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006837 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006838 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006839 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006840 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006841 ALOGV("Record stopped OK");
6842 return true;
6843 }
6844 return false;
6845}
6846
Glenn Kasten0f11b512014-01-31 16:18:54 -08006847bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006848{
6849 return false;
6850}
6851
Glenn Kasten0f11b512014-01-31 16:18:54 -08006852status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006853{
6854#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6855 if (!isValidSyncEvent(event)) {
6856 return BAD_VALUE;
6857 }
6858
Glenn Kastend848eb42016-03-08 13:42:11 -08006859 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006860 status_t ret = NAME_NOT_FOUND;
6861
6862 Mutex::Autolock _l(mLock);
6863
6864 for (size_t i = 0; i < mTracks.size(); i++) {
6865 sp<RecordTrack> track = mTracks[i];
6866 if (eventSession == track->sessionId()) {
6867 (void) track->setSyncEvent(event);
6868 ret = NO_ERROR;
6869 }
6870 }
6871 return ret;
6872#else
6873 return BAD_VALUE;
6874#endif
6875}
6876
6877// destroyTrack_l() must be called with ThreadBase::mLock held
6878void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6879{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006880 track->terminate();
6881 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006882 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006883 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006884 removeTrack_l(track);
6885 }
6886}
6887
6888void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6889{
6890 mTracks.remove(track);
6891 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006892 if (track->isFastTrack()) {
6893 ALOG_ASSERT(!mFastTrackAvail);
6894 mFastTrackAvail = true;
6895 }
Eric Laurent81784c32012-11-19 14:55:58 -08006896}
6897
6898void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6899{
6900 dumpInternals(fd, args);
6901 dumpTracks(fd, args);
6902 dumpEffectChains(fd, args);
6903}
6904
6905void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6906{
Glenn Kasten44182c22015-03-05 17:12:23 -08006907 dumpBase(fd, args);
6908
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006909 AudioStreamIn *input = mInput;
6910 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6911 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6912 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006913 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006914 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006915 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006916 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006917 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006918
Glenn Kasten2f90c512015-12-02 11:40:09 -08006919 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6920 // while we are dumping it. It may be inconsistent, but it won't mutate!
6921 // This is a large object so we place it on the heap.
6922 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6923 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6924 copy->dump(fd);
6925 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006926}
6927
Glenn Kasten0f11b512014-01-31 16:18:54 -08006928void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006929{
6930 const size_t SIZE = 256;
6931 char buffer[SIZE];
6932 String8 result;
6933
Marco Nelissenb2208842014-02-07 14:00:50 -08006934 size_t numtracks = mTracks.size();
6935 size_t numactive = mActiveTracks.size();
6936 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006937 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006938 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006939 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006940 RecordTrack::appendDumpHeader(result);
6941 for (size_t i = 0; i < numtracks ; ++i) {
6942 sp<RecordTrack> track = mTracks[i];
6943 if (track != 0) {
6944 bool active = mActiveTracks.indexOf(track) >= 0;
6945 if (active) {
6946 numactiveseen++;
6947 }
6948 track->dump(buffer, SIZE, active);
6949 result.append(buffer);
6950 }
Eric Laurent81784c32012-11-19 14:55:58 -08006951 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006952 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006953 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006954 }
6955
Marco Nelissenb2208842014-02-07 14:00:50 -08006956 if (numactiveseen != numactive) {
6957 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6958 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006959 result.append(buffer);
6960 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006961 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006962 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006963 if (mTracks.indexOf(track) < 0) {
6964 track->dump(buffer, SIZE, true);
6965 result.append(buffer);
6966 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006967 }
Eric Laurent81784c32012-11-19 14:55:58 -08006968
6969 }
6970 write(fd, result.string(), result.size());
6971}
6972
Andy Hung73c02e42015-03-29 01:13:58 -07006973
6974void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6975{
6976 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6977 RecordThread *recordThread = (RecordThread *) threadBase.get();
6978 mRsmpInFront = recordThread->mRsmpInRear;
6979 mRsmpInUnrel = 0;
6980}
6981
6982void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6983 size_t *framesAvailable, bool *hasOverrun)
6984{
6985 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6986 RecordThread *recordThread = (RecordThread *) threadBase.get();
6987 const int32_t rear = recordThread->mRsmpInRear;
6988 const int32_t front = mRsmpInFront;
6989 const ssize_t filled = rear - front;
6990
6991 size_t framesIn;
6992 bool overrun = false;
6993 if (filled < 0) {
6994 // should not happen, but treat like a massive overrun and re-sync
6995 framesIn = 0;
6996 mRsmpInFront = rear;
6997 overrun = true;
6998 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
6999 framesIn = (size_t) filled;
7000 } else {
7001 // client is not keeping up with server, but give it latest data
7002 framesIn = recordThread->mRsmpInFrames;
7003 mRsmpInFront = /* front = */ rear - framesIn;
7004 overrun = true;
7005 }
7006 if (framesAvailable != NULL) {
7007 *framesAvailable = framesIn;
7008 }
7009 if (hasOverrun != NULL) {
7010 *hasOverrun = overrun;
7011 }
7012}
7013
Eric Laurent81784c32012-11-19 14:55:58 -08007014// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007015status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007016 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007017{
Andy Hung73c02e42015-03-29 01:13:58 -07007018 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007019 if (threadBase == 0) {
7020 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007021 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007022 return NOT_ENOUGH_DATA;
7023 }
7024 RecordThread *recordThread = (RecordThread *) threadBase.get();
7025 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007026 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007027 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007028 // FIXME should not be P2 (don't want to increase latency)
7029 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007030 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007031 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007032 front &= recordThread->mRsmpInFramesP2 - 1;
7033 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007034 if (part1 > (size_t) filled) {
7035 part1 = filled;
7036 }
7037 size_t ask = buffer->frameCount;
7038 ALOG_ASSERT(ask > 0);
7039 if (part1 > ask) {
7040 part1 = ask;
7041 }
7042 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007043 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007044 buffer->raw = NULL;
7045 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007046 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007047 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007048 }
7049
Andy Hung57446612015-04-19 23:56:46 -07007050 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007051 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007052 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007053 return NO_ERROR;
7054}
7055
7056// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007057void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7058 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007059{
Glenn Kasten85948432013-08-19 12:09:05 -07007060 size_t stepCount = buffer->frameCount;
7061 if (stepCount == 0) {
7062 return;
7063 }
Andy Hung73c02e42015-03-29 01:13:58 -07007064 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7065 mRsmpInUnrel -= stepCount;
7066 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007067 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007068 buffer->frameCount = 0;
7069}
7070
Eric Laurentd8365c52017-07-16 15:27:05 -07007071void AudioFlinger::RecordThread::checkBtNrec()
7072{
7073 Mutex::Autolock _l(mLock);
7074 checkBtNrec_l();
7075}
7076
7077void AudioFlinger::RecordThread::checkBtNrec_l()
7078{
7079 // disable AEC and NS if the device is a BT SCO headset supporting those
7080 // pre processings
7081 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7082 mAudioFlinger->btNrecIsOff();
7083 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7084 for (size_t i = 0; i < mEffectChains.size(); i++) {
7085 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7086 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7087 }
7088 }
7089}
7090
Andy Hung97a893e2015-03-29 01:03:07 -07007091
Eric Laurent10351942014-05-08 18:49:52 -07007092bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7093 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007094{
7095 bool reconfig = false;
7096
Eric Laurent10351942014-05-08 18:49:52 -07007097 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007098
Eric Laurent10351942014-05-08 18:49:52 -07007099 audio_format_t reqFormat = mFormat;
7100 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007101 // 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 -07007102 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7103
7104 AudioParameter param = AudioParameter(keyValuePair);
7105 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007106
7107 // scope for AutoPark extends to end of method
7108 AutoPark<FastCapture> park(mFastCapture);
7109
Eric Laurent10351942014-05-08 18:49:52 -07007110 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7111 // channel count change can be requested. Do we mandate the first client defines the
7112 // HAL sampling rate and channel count or do we allow changes on the fly?
7113 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7114 samplingRate = value;
7115 reconfig = true;
7116 }
7117 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007118 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007119 status = BAD_VALUE;
7120 } else {
7121 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007122 reconfig = true;
7123 }
Eric Laurent10351942014-05-08 18:49:52 -07007124 }
7125 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7126 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007127 if (!audio_is_input_channel(mask) ||
7128 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007129 status = BAD_VALUE;
7130 } else {
7131 channelMask = mask;
7132 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007133 }
Eric Laurent10351942014-05-08 18:49:52 -07007134 }
7135 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7136 // do not accept frame count changes if tracks are open as the track buffer
7137 // size depends on frame count and correct behavior would not be guaranteed
7138 // if frame count is changed after track creation
7139 if (mActiveTracks.size() > 0) {
7140 status = INVALID_OPERATION;
7141 } else {
7142 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007143 }
Eric Laurent10351942014-05-08 18:49:52 -07007144 }
7145 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7146 // forward device change to effects that have requested to be
7147 // aware of attached audio device.
7148 for (size_t i = 0; i < mEffectChains.size(); i++) {
7149 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007150 }
Eric Laurent81784c32012-11-19 14:55:58 -08007151
Eric Laurent10351942014-05-08 18:49:52 -07007152 // store input device and output device but do not forward output device to audio HAL.
7153 // Note that status is ignored by the caller for output device
7154 // (see AudioFlinger::setParameters()
7155 if (audio_is_output_devices(value)) {
7156 mOutDevice = value;
7157 status = BAD_VALUE;
7158 } else {
7159 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007160 if (value != AUDIO_DEVICE_NONE) {
7161 mPrevInDevice = value;
7162 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007163 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007164 }
Eric Laurent10351942014-05-08 18:49:52 -07007165 }
7166 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7167 mAudioSource != (audio_source_t)value) {
7168 // forward device change to effects that have requested to be
7169 // aware of attached audio device.
7170 for (size_t i = 0; i < mEffectChains.size(); i++) {
7171 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007172 }
Eric Laurent10351942014-05-08 18:49:52 -07007173 mAudioSource = (audio_source_t)value;
7174 }
Glenn Kastene198c362013-08-13 09:13:36 -07007175
Eric Laurent10351942014-05-08 18:49:52 -07007176 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007177 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007178 if (status == INVALID_OPERATION) {
7179 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007180 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007181 }
7182 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007183 if (status == BAD_VALUE) {
7184 uint32_t sRate;
7185 audio_channel_mask_t channelMask;
7186 audio_format_t format;
7187 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7188 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7189 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7190 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7191 status = NO_ERROR;
7192 }
Eric Laurent81784c32012-11-19 14:55:58 -08007193 }
Eric Laurent10351942014-05-08 18:49:52 -07007194 if (status == NO_ERROR) {
7195 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007196 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007197 }
7198 }
Eric Laurent81784c32012-11-19 14:55:58 -08007199 }
Eric Laurent10351942014-05-08 18:49:52 -07007200
Eric Laurent81784c32012-11-19 14:55:58 -08007201 return reconfig;
7202}
7203
7204String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7205{
Eric Laurent81784c32012-11-19 14:55:58 -08007206 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007207 if (initCheck() == NO_ERROR) {
7208 String8 out_s8;
7209 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7210 return out_s8;
7211 }
Eric Laurent81784c32012-11-19 14:55:58 -08007212 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007213 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007214}
7215
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007216void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007217 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7218
7219 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007220
7221 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007222 case AUDIO_INPUT_OPENED:
7223 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007224 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007225 desc->mChannelMask = mChannelMask;
7226 desc->mSamplingRate = mSampleRate;
7227 desc->mFormat = mFormat;
7228 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007229 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007230 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007231 break;
7232
Eric Laurent73e26b62015-04-27 16:55:58 -07007233 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007234 default:
7235 break;
7236 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007237 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007238}
7239
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007240void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007241{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007242 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7243 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007244 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007245 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007246 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007247 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7248 result = mInput->stream->getFrameSize(&mFrameSize);
7249 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7250 result = mInput->stream->getBufferSize(&mBufferSize);
7251 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007252 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007253 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7254 "mBufferSize=%lld, mFrameCount=%lld",
7255 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7256 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007257 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007258 // 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 -07007259 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007260 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007261 // A larger value should allow more old data to be read after a track calls start(),
7262 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007263 //
7264 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007265 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007266 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007267 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007268 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007269
7270 // TODO optimize audio capture buffer sizes ...
7271 // Here we calculate the size of the sliding buffer used as a source
7272 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7273 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7274 // be better to have it derived from the pipe depth in the long term.
7275 // The current value is higher than necessary. However it should not add to latency.
7276
Glenn Kasten85948432013-08-19 12:09:05 -07007277 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007278 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7279 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007280 // if posix_memalign fails, will segv here.
7281 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007282
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007283 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7284 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007285}
7286
Glenn Kasten5f972c02014-01-13 09:59:31 -08007287uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007288{
7289 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007290 uint32_t result;
7291 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7292 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007293 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007294 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007295}
7296
Eric Laurent4c415062016-06-17 16:14:16 -07007297// hasAudioSession_l() must be called with ThreadBase::mLock held
7298uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007299{
Eric Laurent81784c32012-11-19 14:55:58 -08007300 uint32_t result = 0;
7301 if (getEffectChain_l(sessionId) != 0) {
7302 result = EFFECT_SESSION;
7303 }
7304
7305 for (size_t i = 0; i < mTracks.size(); ++i) {
7306 if (sessionId == mTracks[i]->sessionId()) {
7307 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007308 if (mTracks[i]->isFastTrack()) {
7309 result |= FAST_SESSION;
7310 }
Eric Laurent81784c32012-11-19 14:55:58 -08007311 break;
7312 }
7313 }
7314
7315 return result;
7316}
7317
Glenn Kastend848eb42016-03-08 13:42:11 -08007318KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007319{
Glenn Kastend848eb42016-03-08 13:42:11 -08007320 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007321 Mutex::Autolock _l(mLock);
7322 for (size_t j = 0; j < mTracks.size(); ++j) {
7323 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007324 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007325 if (ids.indexOfKey(sessionId) < 0) {
7326 ids.add(sessionId, true);
7327 }
7328 }
7329 return ids;
7330}
7331
7332AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7333{
7334 Mutex::Autolock _l(mLock);
7335 AudioStreamIn *input = mInput;
7336 mInput = NULL;
7337 return input;
7338}
7339
7340// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007341sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007342{
7343 if (mInput == NULL) {
7344 return NULL;
7345 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007346 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007347}
7348
7349status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7350{
7351 // only one chain per input thread
7352 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007353 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007354 return INVALID_OPERATION;
7355 }
7356 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007357 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007358 chain->setInBuffer(NULL);
7359 chain->setOutBuffer(NULL);
7360
7361 checkSuspendOnAddEffectChain_l(chain);
7362
Eric Laurent1b928682014-10-02 19:41:47 -07007363 // make sure enabled pre processing effects state is communicated to the HAL as we
7364 // just moved them to a new input stream.
7365 chain->syncHalEffectsState();
7366
Eric Laurent81784c32012-11-19 14:55:58 -08007367 mEffectChains.add(chain);
7368
7369 return NO_ERROR;
7370}
7371
7372size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7373{
7374 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7375 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007376 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007377 chain.get(), mEffectChains.size(), this);
7378 if (mEffectChains.size() == 1) {
7379 mEffectChains.removeAt(0);
7380 }
7381 return 0;
7382}
7383
Eric Laurent1c333e22014-05-20 10:48:17 -07007384status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7385 audio_patch_handle_t *handle)
7386{
7387 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007388
7389 // store new device and send to effects
7390 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007391 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007392 for (size_t i = 0; i < mEffectChains.size(); i++) {
7393 mEffectChains[i]->setDevice_l(mInDevice);
7394 }
7395
Eric Laurentd8365c52017-07-16 15:27:05 -07007396 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007397
7398 // store new source and send to effects
7399 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7400 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007401 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007402 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007403 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007404 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007405
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007406 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007407 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7408 status = hwDevice->createAudioPatch(patch->num_sources,
7409 patch->sources,
7410 patch->num_sinks,
7411 patch->sinks,
7412 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007413 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007414 char *address;
7415 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7416 address = audio_device_address_to_parameter(
7417 patch->sources[0].ext.device.type,
7418 patch->sources[0].ext.device.address);
7419 } else {
7420 address = (char *)calloc(1, 1);
7421 }
7422 AudioParameter param = AudioParameter(String8(address));
7423 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007424 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007425 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007426 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007427 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007428 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007429 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007430 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007431
Eric Laurente8726fe2015-06-26 09:39:24 -07007432 if (mInDevice != mPrevInDevice) {
7433 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7434 mPrevInDevice = mInDevice;
7435 }
Eric Laurent296fb132015-05-01 11:38:42 -07007436
Eric Laurent1c333e22014-05-20 10:48:17 -07007437 return status;
7438}
7439
7440status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7441{
7442 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007443
7444 mInDevice = AUDIO_DEVICE_NONE;
7445
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007446 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007447 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7448 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007449 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007450 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007451 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007452 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007453 }
7454 return status;
7455}
7456
Eric Laurent83b88082014-06-20 18:31:16 -07007457void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7458{
7459 Mutex::Autolock _l(mLock);
7460 mTracks.add(record);
7461}
7462
7463void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7464{
7465 Mutex::Autolock _l(mLock);
7466 destroyTrack_l(record);
7467}
7468
7469void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7470{
7471 ThreadBase::getAudioPortConfig(config);
7472 config->role = AUDIO_PORT_ROLE_SINK;
7473 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7474 config->ext.mix.usecase.source = mAudioSource;
7475}
Eric Laurent1c333e22014-05-20 10:48:17 -07007476
Eric Laurent6acd1d42017-01-04 14:23:29 -08007477// ----------------------------------------------------------------------------
7478// Mmap
7479// ----------------------------------------------------------------------------
7480
7481AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7482 : mThread(thread)
7483{
7484}
7485
7486AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7487{
7488 MmapThread *thread = mThread.get();
7489 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007490 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007491 // and the thread removed from mMMapThreads list causing the thread destruction.
7492 mThread.clear();
7493 if (thread != nullptr) {
7494 thread->disconnect();
7495 }
7496}
7497
7498status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7499 struct audio_mmap_buffer_info *info)
7500{
7501 if (mThread == 0) {
7502 return NO_INIT;
7503 }
7504 return mThread->createMmapBuffer(minSizeFrames, info);
7505}
7506
7507status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7508{
7509 if (mThread == 0) {
7510 return NO_INIT;
7511 }
7512 return mThread->getMmapPosition(position);
7513}
7514
Eric Laurentcb4dae22017-07-01 19:39:32 -07007515status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007516 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007517
7518{
7519 if (mThread == 0) {
7520 return NO_INIT;
7521 }
7522 return mThread->start(client, handle);
7523}
7524
7525status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7526{
7527 if (mThread == 0) {
7528 return NO_INIT;
7529 }
7530 return mThread->stop(handle);
7531}
7532
Eric Laurent18b57012017-02-13 16:23:52 -08007533status_t AudioFlinger::MmapThreadHandle::standby()
7534{
7535 if (mThread == 0) {
7536 return NO_INIT;
7537 }
7538 return mThread->standby();
7539}
7540
Eric Laurent6acd1d42017-01-04 14:23:29 -08007541
7542AudioFlinger::MmapThread::MmapThread(
7543 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7544 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7545 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7546 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7547 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7548{
Eric Laurent18b57012017-02-13 16:23:52 -08007549 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007550 readHalParameters_l();
7551}
7552
7553AudioFlinger::MmapThread::~MmapThread()
7554{
Eric Laurent18b57012017-02-13 16:23:52 -08007555 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007556}
7557
7558void AudioFlinger::MmapThread::onFirstRef()
7559{
7560 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7561}
7562
7563void AudioFlinger::MmapThread::disconnect()
7564{
7565 for (const sp<MmapTrack> &t : mActiveTracks) {
7566 stop(t->portId());
7567 }
7568 // this will cause the destruction of this thread.
7569 if (isOutput()) {
7570 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7571 } else {
7572 AudioSystem::releaseInput(mId, mSessionId);
7573 }
7574}
7575
7576
7577void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7578 audio_stream_type_t streamType __unused,
7579 audio_session_t sessionId,
7580 const sp<MmapStreamCallback>& callback,
7581 audio_port_handle_t portId)
7582{
7583 mAttr = *attr;
7584 mSessionId = sessionId;
7585 mCallback = callback;
7586 mPortId = portId;
7587}
7588
7589status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7590 struct audio_mmap_buffer_info *info)
7591{
7592 if (mHalStream == 0) {
7593 return NO_INIT;
7594 }
Eric Laurent18b57012017-02-13 16:23:52 -08007595 mStandby = true;
7596 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007597 return mHalStream->createMmapBuffer(minSizeFrames, info);
7598}
7599
7600status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7601{
7602 if (mHalStream == 0) {
7603 return NO_INIT;
7604 }
7605 return mHalStream->getMmapPosition(position);
7606}
7607
Eric Laurentcb4dae22017-07-01 19:39:32 -07007608status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007609 audio_port_handle_t *handle)
7610{
Eric Laurentcb4dae22017-07-01 19:39:32 -07007611 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7612 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007613 if (mHalStream == 0) {
7614 return NO_INIT;
7615 }
7616
7617 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007618
Eric Laurentcb4dae22017-07-01 19:39:32 -07007619 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007620 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007621 ret = mHalStream->start();
7622 if (ret != NO_ERROR) {
7623 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7624 return ret;
7625 }
Eric Laurent18b57012017-02-13 16:23:52 -08007626 mStandby = false;
Eric Laurentcb4dae22017-07-01 19:39:32 -07007627 return NO_ERROR;
7628 }
7629
7630 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7631
7632 audio_io_handle_t io = mId;
7633 if (isOutput()) {
7634 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7635 config.sample_rate = mSampleRate;
7636 config.channel_mask = mChannelMask;
7637 config.format = mFormat;
7638 audio_stream_type_t stream = streamType();
7639 audio_output_flags_t flags =
7640 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7641 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7642 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7643 mSessionId,
7644 &stream,
7645 client.clientUid,
7646 &config,
7647 flags,
7648 &deviceId,
7649 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007650 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007651 audio_config_base_t config;
7652 config.sample_rate = mSampleRate;
7653 config.channel_mask = mChannelMask;
7654 config.format = mFormat;
7655 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7656 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7657 mSessionId,
7658 client.clientPid,
7659 client.clientUid,
7660 &config,
7661 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7662 &deviceId,
7663 &portId);
7664 }
7665 // APM should not chose a different input or output stream for the same set of attributes
7666 // and audo configuration
7667 if (ret != NO_ERROR || io != mId) {
7668 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7669 __FUNCTION__, ret, io, mId);
7670 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007671 }
7672
7673 if (isOutput()) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007674 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007675 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007676 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007677 }
7678
7679 // abort if start is rejected by audio policy manager
7680 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007681 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007682 if (mActiveTracks.size() != 0) {
7683 if (isOutput()) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007684 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007685 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007686 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007687 }
Eric Laurent18b57012017-02-13 16:23:52 -08007688 } else {
7689 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007690 }
7691 return PERMISSION_DENIED;
7692 }
7693
Eric Laurentcb4dae22017-07-01 19:39:32 -07007694 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007695 client.clientUid, portId);
7696
7697 mActiveTracks.add(track);
Eric Laurentcb4dae22017-07-01 19:39:32 -07007698 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007699 if (chain != 0) {
7700 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7701 chain->incTrackCnt();
7702 chain->incActiveTrackCnt();
7703 }
7704
7705 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007706 broadcast_l();
7707
Eric Laurentcb4dae22017-07-01 19:39:32 -07007708 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007709
7710 return NO_ERROR;
7711}
7712
7713status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7714{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007715 ALOGV("%s handle %d", __FUNCTION__, handle);
7716
7717 if (mHalStream == 0) {
7718 return NO_INIT;
7719 }
7720
Eric Laurentcb4dae22017-07-01 19:39:32 -07007721 if (handle == mPortId) {
7722 mHalStream->stop();
7723 return NO_ERROR;
7724 }
7725
Eric Laurent6acd1d42017-01-04 14:23:29 -08007726 sp<MmapTrack> track;
7727 for (const sp<MmapTrack> &t : mActiveTracks) {
7728 if (handle == t->portId()) {
7729 track = t;
7730 break;
7731 }
7732 }
7733 if (track == 0) {
7734 return BAD_VALUE;
7735 }
7736
7737 mActiveTracks.remove(track);
7738
7739 if (isOutput()) {
7740 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurentcb4dae22017-07-01 19:39:32 -07007741 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007742 } else {
7743 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurentcb4dae22017-07-01 19:39:32 -07007744 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007745 }
7746
7747 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7748 if (chain != 0) {
7749 chain->decActiveTrackCnt();
7750 chain->decTrackCnt();
7751 }
7752
7753 broadcast_l();
7754
Eric Laurent6acd1d42017-01-04 14:23:29 -08007755 return NO_ERROR;
7756}
7757
Eric Laurent18b57012017-02-13 16:23:52 -08007758status_t AudioFlinger::MmapThread::standby()
7759{
7760 ALOGV("%s", __FUNCTION__);
7761
7762 if (mHalStream == 0) {
7763 return NO_INIT;
7764 }
7765 if (mActiveTracks.size() != 0) {
7766 return INVALID_OPERATION;
7767 }
7768 mHalStream->standby();
7769 mStandby = true;
7770 releaseWakeLock();
7771 return NO_ERROR;
7772}
7773
Eric Laurent6acd1d42017-01-04 14:23:29 -08007774
7775void AudioFlinger::MmapThread::readHalParameters_l()
7776{
7777 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7778 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7779 mFormat = mHALFormat;
7780 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7781 result = mHalStream->getFrameSize(&mFrameSize);
7782 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7783 result = mHalStream->getBufferSize(&mBufferSize);
7784 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7785 mFrameCount = mBufferSize / mFrameSize;
7786}
7787
7788bool AudioFlinger::MmapThread::threadLoop()
7789{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007790 checkSilentMode_l();
7791
7792 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7793
7794 while (!exitPending())
7795 {
7796 Mutex::Autolock _l(mLock);
7797 Vector< sp<EffectChain> > effectChains;
7798
7799 if (mSignalPending) {
7800 // A signal was raised while we were unlocked
7801 mSignalPending = false;
7802 } else {
7803 if (mConfigEvents.isEmpty()) {
7804 // we're about to wait, flush the binder command buffer
7805 IPCThreadState::self()->flushCommands();
7806
7807 if (exitPending()) {
7808 break;
7809 }
7810
Eric Laurent6acd1d42017-01-04 14:23:29 -08007811 // wait until we have something to do...
7812 ALOGV("%s going to sleep", myName.string());
7813 mWaitWorkCV.wait(mLock);
7814 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007815
7816 checkSilentMode_l();
7817
7818 continue;
7819 }
7820 }
7821
7822 processConfigEvents_l();
7823
7824 processVolume_l();
7825
7826 checkInvalidTracks_l();
7827
7828 mActiveTracks.updatePowerState(this);
7829
7830 lockEffectChains_l(effectChains);
7831 for (size_t i = 0; i < effectChains.size(); i ++) {
7832 effectChains[i]->process_l();
7833 }
7834 // enable changes in effect chain
7835 unlockEffectChains(effectChains);
7836 // Effect chains will be actually deleted here if they were removed from
7837 // mEffectChains list during mixing or effects processing
7838 }
7839
7840 threadLoop_exit();
7841
7842 if (!mStandby) {
7843 threadLoop_standby();
7844 mStandby = true;
7845 }
7846
Eric Laurent6acd1d42017-01-04 14:23:29 -08007847 ALOGV("Thread %p type %d exiting", this, mType);
7848 return false;
7849}
7850
7851// checkForNewParameter_l() must be called with ThreadBase::mLock held
7852bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7853 status_t& status)
7854{
7855 AudioParameter param = AudioParameter(keyValuePair);
7856 int value;
7857 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7858 // forward device change to effects that have requested to be
7859 // aware of attached audio device.
7860 if (value != AUDIO_DEVICE_NONE) {
7861 mOutDevice = value;
7862 for (size_t i = 0; i < mEffectChains.size(); i++) {
7863 mEffectChains[i]->setDevice_l(mOutDevice);
7864 }
7865 }
7866 }
7867 status = mHalStream->setParameters(keyValuePair);
7868
7869 return false;
7870}
7871
7872String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7873{
7874 Mutex::Autolock _l(mLock);
7875 String8 out_s8;
7876 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7877 return out_s8;
7878 }
7879 return String8();
7880}
7881
7882void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7883 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7884
7885 desc->mIoHandle = mId;
7886
7887 switch (event) {
7888 case AUDIO_INPUT_OPENED:
7889 case AUDIO_INPUT_CONFIG_CHANGED:
7890 case AUDIO_OUTPUT_OPENED:
7891 case AUDIO_OUTPUT_CONFIG_CHANGED:
7892 desc->mPatch = mPatch;
7893 desc->mChannelMask = mChannelMask;
7894 desc->mSamplingRate = mSampleRate;
7895 desc->mFormat = mFormat;
7896 desc->mFrameCount = mFrameCount;
7897 desc->mFrameCountHAL = mFrameCount;
7898 desc->mLatency = 0;
7899 break;
7900
7901 case AUDIO_INPUT_CLOSED:
7902 case AUDIO_OUTPUT_CLOSED:
7903 default:
7904 break;
7905 }
7906 mAudioFlinger->ioConfigChanged(event, desc, pid);
7907}
7908
7909status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7910 audio_patch_handle_t *handle)
7911{
7912 status_t status = NO_ERROR;
7913
7914 // store new device and send to effects
7915 audio_devices_t type = AUDIO_DEVICE_NONE;
7916 audio_port_handle_t deviceId;
7917 if (isOutput()) {
7918 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7919 type |= patch->sinks[i].ext.device.type;
7920 }
7921 deviceId = patch->sinks[0].id;
7922 } else {
7923 type = patch->sources[0].ext.device.type;
7924 deviceId = patch->sources[0].id;
7925 }
7926
7927 for (size_t i = 0; i < mEffectChains.size(); i++) {
7928 mEffectChains[i]->setDevice_l(type);
7929 }
7930
7931 if (isOutput()) {
7932 mOutDevice = type;
7933 } else {
7934 mInDevice = type;
7935 // store new source and send to effects
7936 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7937 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7938 for (size_t i = 0; i < mEffectChains.size(); i++) {
7939 mEffectChains[i]->setAudioSource_l(mAudioSource);
7940 }
7941 }
7942 }
7943
7944 if (mAudioHwDev->supportsAudioPatches()) {
7945 status = mHalDevice->createAudioPatch(patch->num_sources,
7946 patch->sources,
7947 patch->num_sinks,
7948 patch->sinks,
7949 handle);
7950 } else {
7951 char *address;
7952 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7953 //FIXME: we only support address on first sink with HAL version < 3.0
7954 address = audio_device_address_to_parameter(
7955 patch->sinks[0].ext.device.type,
7956 patch->sinks[0].ext.device.address);
7957 } else {
7958 address = (char *)calloc(1, 1);
7959 }
7960 AudioParameter param = AudioParameter(String8(address));
7961 free(address);
7962 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7963 if (!isOutput()) {
7964 param.addInt(String8(AudioParameter::keyInputSource),
7965 (int)patch->sinks[0].ext.mix.usecase.source);
7966 }
7967 status = mHalStream->setParameters(param.toString());
7968 *handle = AUDIO_PATCH_HANDLE_NONE;
7969 }
7970
7971 if (isOutput() && mPrevOutDevice != mOutDevice) {
7972 mPrevOutDevice = type;
7973 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007974 sp<MmapStreamCallback> callback = mCallback.promote();
7975 if (callback != 0) {
7976 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007977 }
7978 }
7979 if (!isOutput() && mPrevInDevice != mInDevice) {
7980 mPrevInDevice = type;
7981 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007982 sp<MmapStreamCallback> callback = mCallback.promote();
7983 if (callback != 0) {
7984 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007985 }
7986 }
7987 return status;
7988}
7989
7990status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7991{
7992 status_t status = NO_ERROR;
7993
7994 mInDevice = AUDIO_DEVICE_NONE;
7995
7996 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
7997 supportsAudioPatches : false;
7998
7999 if (supportsAudioPatches) {
8000 status = mHalDevice->releaseAudioPatch(handle);
8001 } else {
8002 AudioParameter param;
8003 param.addInt(String8(AudioParameter::keyRouting), 0);
8004 status = mHalStream->setParameters(param.toString());
8005 }
8006 return status;
8007}
8008
8009void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8010{
8011 ThreadBase::getAudioPortConfig(config);
8012 if (isOutput()) {
8013 config->role = AUDIO_PORT_ROLE_SOURCE;
8014 config->ext.mix.hw_module = mAudioHwDev->handle();
8015 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8016 } else {
8017 config->role = AUDIO_PORT_ROLE_SINK;
8018 config->ext.mix.hw_module = mAudioHwDev->handle();
8019 config->ext.mix.usecase.source = mAudioSource;
8020 }
8021}
8022
8023status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8024{
8025 audio_session_t session = chain->sessionId();
8026
8027 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8028 // Attach all tracks with same session ID to this chain.
8029 // indicate all active tracks in the chain
8030 for (const sp<MmapTrack> &track : mActiveTracks) {
8031 if (session == track->sessionId()) {
8032 chain->incTrackCnt();
8033 chain->incActiveTrackCnt();
8034 }
8035 }
8036
8037 chain->setThread(this);
8038 chain->setInBuffer(nullptr);
8039 chain->setOutBuffer(nullptr);
8040 chain->syncHalEffectsState();
8041
8042 mEffectChains.add(chain);
8043 checkSuspendOnAddEffectChain_l(chain);
8044 return NO_ERROR;
8045}
8046
8047size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8048{
8049 audio_session_t session = chain->sessionId();
8050
8051 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8052
8053 for (size_t i = 0; i < mEffectChains.size(); i++) {
8054 if (chain == mEffectChains[i]) {
8055 mEffectChains.removeAt(i);
8056 // detach all active tracks from the chain
8057 // detach all tracks with same session ID from this chain
8058 for (const sp<MmapTrack> &track : mActiveTracks) {
8059 if (session == track->sessionId()) {
8060 chain->decActiveTrackCnt();
8061 chain->decTrackCnt();
8062 }
8063 }
8064 break;
8065 }
8066 }
8067 return mEffectChains.size();
8068}
8069
8070// hasAudioSession_l() must be called with ThreadBase::mLock held
8071uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8072{
8073 uint32_t result = 0;
8074 if (getEffectChain_l(sessionId) != 0) {
8075 result = EFFECT_SESSION;
8076 }
8077
8078 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8079 sp<MmapTrack> track = mActiveTracks[i];
8080 if (sessionId == track->sessionId()) {
8081 result |= TRACK_SESSION;
8082 if (track->isFastTrack()) {
8083 result |= FAST_SESSION;
8084 }
8085 break;
8086 }
8087 }
8088
8089 return result;
8090}
8091
8092void AudioFlinger::MmapThread::threadLoop_standby()
8093{
8094 mHalStream->standby();
8095}
8096
8097void AudioFlinger::MmapThread::threadLoop_exit()
8098{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008099 sp<MmapStreamCallback> callback = mCallback.promote();
8100 if (callback != 0) {
8101 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008102 }
8103}
8104
8105status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8106{
8107 return BAD_VALUE;
8108}
8109
8110bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8111{
8112 return false;
8113}
8114
8115status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8116 const effect_descriptor_t *desc, audio_session_t sessionId)
8117{
8118 // No global effect sessions on mmap threads
8119 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8120 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8121 desc->name, mThreadName);
8122 return BAD_VALUE;
8123 }
8124
8125 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8126 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8127 desc->name);
8128 return BAD_VALUE;
8129 }
8130 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008131 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8132 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008133 return BAD_VALUE;
8134 }
8135
8136 // Only allow effects without processing load or latency
8137 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8138 return BAD_VALUE;
8139 }
8140
8141 return NO_ERROR;
8142
8143}
8144
8145void AudioFlinger::MmapThread::checkInvalidTracks_l()
8146{
8147 for (const sp<MmapTrack> &track : mActiveTracks) {
8148 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008149 sp<MmapStreamCallback> callback = mCallback.promote();
8150 if (callback != 0) {
8151 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008152 }
8153 break;
8154 }
8155 }
8156}
8157
8158void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8159{
8160 dumpInternals(fd, args);
8161 dumpTracks(fd, args);
8162 dumpEffectChains(fd, args);
8163}
8164
8165void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8166{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008167 dumpBase(fd, args);
8168
8169 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8170 mAttr.content_type, mAttr.usage, mAttr.source);
8171 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8172 if (mActiveTracks.size() == 0) {
8173 dprintf(fd, " No active clients\n");
8174 }
8175}
8176
8177void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8178{
8179 const size_t SIZE = 256;
8180 char buffer[SIZE];
8181 String8 result;
8182
8183 size_t numtracks = mActiveTracks.size();
8184 dprintf(fd, " %zu Tracks", numtracks);
8185 if (numtracks) {
8186 MmapTrack::appendDumpHeader(result);
8187 for (size_t i = 0; i < numtracks ; ++i) {
8188 sp<MmapTrack> track = mActiveTracks[i];
8189 track->dump(buffer, SIZE);
8190 result.append(buffer);
8191 }
8192 } else {
8193 dprintf(fd, "\n");
8194 }
8195 write(fd, result.string(), result.size());
8196}
8197
8198AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8199 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8200 AudioHwDevice *hwDev, AudioStreamOut *output,
8201 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8202 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8203 mStreamType(AUDIO_STREAM_MUSIC),
8204 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8205{
8206 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8207 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8208 mMasterVolume = audioFlinger->masterVolume_l();
8209 mMasterMute = audioFlinger->masterMute_l();
8210 if (mAudioHwDev) {
8211 if (mAudioHwDev->canSetMasterVolume()) {
8212 mMasterVolume = 1.0;
8213 }
8214
8215 if (mAudioHwDev->canSetMasterMute()) {
8216 mMasterMute = false;
8217 }
8218 }
8219}
8220
8221void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8222 audio_stream_type_t streamType,
8223 audio_session_t sessionId,
8224 const sp<MmapStreamCallback>& callback,
8225 audio_port_handle_t portId)
8226{
8227 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8228 mStreamType = streamType;
8229}
8230
8231AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8232{
8233 Mutex::Autolock _l(mLock);
8234 AudioStreamOut *output = mOutput;
8235 mOutput = NULL;
8236 return output;
8237}
8238
8239void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8240{
8241 Mutex::Autolock _l(mLock);
8242 // Don't apply master volume in SW if our HAL can do it for us.
8243 if (mAudioHwDev &&
8244 mAudioHwDev->canSetMasterVolume()) {
8245 mMasterVolume = 1.0;
8246 } else {
8247 mMasterVolume = value;
8248 }
8249}
8250
8251void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8252{
8253 Mutex::Autolock _l(mLock);
8254 // Don't apply master mute in SW if our HAL can do it for us.
8255 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8256 mMasterMute = false;
8257 } else {
8258 mMasterMute = muted;
8259 }
8260}
8261
8262void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8263{
8264 Mutex::Autolock _l(mLock);
8265 if (stream == mStreamType) {
8266 mStreamVolume = value;
8267 broadcast_l();
8268 }
8269}
8270
8271float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8272{
8273 Mutex::Autolock _l(mLock);
8274 if (stream == mStreamType) {
8275 return mStreamVolume;
8276 }
8277 return 0.0f;
8278}
8279
8280void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8281{
8282 Mutex::Autolock _l(mLock);
8283 if (stream == mStreamType) {
8284 mStreamMute= muted;
8285 broadcast_l();
8286 }
8287}
8288
8289void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8290{
8291 Mutex::Autolock _l(mLock);
8292 if (streamType == mStreamType) {
8293 for (const sp<MmapTrack> &track : mActiveTracks) {
8294 track->invalidate();
8295 }
8296 broadcast_l();
8297 }
8298}
8299
8300void AudioFlinger::MmapPlaybackThread::processVolume_l()
8301{
8302 float volume;
8303
8304 if (mMasterMute || mStreamMute) {
8305 volume = 0;
8306 } else {
8307 volume = mMasterVolume * mStreamVolume;
8308 }
8309
8310 if (volume != mHalVolFloat) {
8311 mHalVolFloat = volume;
8312
8313 // Convert volumes from float to 8.24
8314 uint32_t vol = (uint32_t)(volume * (1 << 24));
8315
8316 // Delegate volume control to effect in track effect chain if needed
8317 // only one effect chain can be present on DirectOutputThread, so if
8318 // there is one, the track is connected to it
8319 if (!mEffectChains.isEmpty()) {
8320 mEffectChains[0]->setVolume_l(&vol, &vol);
8321 volume = (float)vol / (1 << 24);
8322 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008323 // Try to use HW volume control and fall back to SW control if not implemented
8324 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8325 sp<MmapStreamCallback> callback = mCallback.promote();
8326 if (callback != 0) {
8327 int channelCount;
8328 if (isOutput()) {
8329 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8330 } else {
8331 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8332 }
8333 Vector<float> values;
8334 for (int i = 0; i < channelCount; i++) {
8335 values.add(volume);
8336 }
8337 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008338 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008339 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008340 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008341 }
8342 }
8343}
8344
8345void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8346{
8347 if (!mMasterMute) {
8348 char value[PROPERTY_VALUE_MAX];
8349 if (property_get("ro.audio.silent", value, "0") > 0) {
8350 char *endptr;
8351 unsigned long ul = strtoul(value, &endptr, 0);
8352 if (*endptr == '\0' && ul != 0) {
8353 ALOGD("Silence is golden");
8354 // The setprop command will not allow a property to be changed after
8355 // the first time it is set, so we don't have to worry about un-muting.
8356 setMasterMute_l(true);
8357 }
8358 }
8359 }
8360}
8361
8362void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8363{
8364 MmapThread::dumpInternals(fd, args);
8365
Glenn Kastend3bb6452016-12-05 18:14:37 -08008366 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8367 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008368 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8369}
8370
8371AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8372 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8373 AudioHwDevice *hwDev, AudioStreamIn *input,
8374 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8375 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8376 mInput(input)
8377{
8378 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8379 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8380}
8381
8382AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8383{
8384 Mutex::Autolock _l(mLock);
8385 AudioStreamIn *input = mInput;
8386 mInput = NULL;
8387 return input;
8388}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008389} // namespace android