blob: 65eccb6db4e66d053500911794b62a6b6c51e9f4 [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
Eric Laurent3e4de772017-07-16 16:55:08 -07001172 // always allow effects without processing load or latency
1173 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1174 return NO_ERROR;
1175 }
1176
Eric Laurent4c415062016-06-17 16:14:16 -07001177 switch (mType) {
1178 case MIXER: {
1179 // Reject any effect on mixer multichannel sinks.
1180 // TODO: fix both format and multichannel issues with effects.
1181 if (mChannelCount != FCC_2) {
1182 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1183 " thread %s", desc->name, mChannelCount, mThreadName);
1184 return BAD_VALUE;
1185 }
1186 audio_output_flags_t flags = mOutput->flags;
1187 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1188 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1189 // global effects are applied only to non fast tracks if they are SW
1190 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1191 break;
1192 }
1193 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1194 // only post processing on output stage session
1195 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1196 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1197 " on output stage session", desc->name);
1198 return BAD_VALUE;
1199 }
1200 } else {
1201 // no restriction on effects applied on non fast tracks
1202 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1203 break;
1204 }
1205 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001270 status_t *status,
1271 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
1273 sp<EffectModule> effect;
1274 sp<EffectHandle> handle;
1275 status_t lStatus;
1276 sp<EffectChain> chain;
1277 bool chainCreated = false;
1278 bool effectCreated = false;
1279 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001280 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001281
1282 lStatus = initCheck();
1283 if (lStatus != NO_ERROR) {
1284 ALOGW("createEffect_l() Audio driver not initialized.");
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1289
1290 { // scope for mLock
1291 Mutex::Autolock _l(mLock);
1292
Eric Laurent4c415062016-06-17 16:14:16 -07001293 lStatus = checkEffectCompatibility_l(desc, sessionId);
1294 if (lStatus != NO_ERROR) {
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // check for existing effect chain with the requested audio session
1299 chain = getEffectChain_l(sessionId);
1300 if (chain == 0) {
1301 // create a new chain for this session
1302 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1303 chain = new EffectChain(this, sessionId);
1304 addEffectChain_l(chain);
1305 chain->setStrategy(getStrategyForSession_l(sessionId));
1306 chainCreated = true;
1307 } else {
1308 effect = chain->getEffectFromDesc_l(desc);
1309 }
1310
1311 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1312
1313 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001315 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001316 lStatus = AudioSystem::registerEffect(
1317 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectRegistered = true;
1322 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectCreated = true;
1328
1329 effect->setDevice(mOutDevice);
1330 effect->setDevice(mInDevice);
1331 effect->setMode(mAudioFlinger->getMode());
1332 effect->setAudioSource(mAudioSource);
1333 }
1334 // create effect handle and connect it to effect module
1335 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001336 lStatus = handle->initCheck();
1337 if (lStatus == OK) {
1338 lStatus = effect->addHandle(handle.get());
1339 }
Eric Laurent81784c32012-11-19 14:55:58 -08001340 if (enabled != NULL) {
1341 *enabled = (int)effect->isEnabled();
1342 }
1343 }
1344
1345Exit:
1346 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1347 Mutex::Autolock _l(mLock);
1348 if (effectCreated) {
1349 chain->removeEffect_l(effect);
1350 }
1351 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001352 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001353 }
1354 if (chainCreated) {
1355 removeEffectChain_l(chain);
1356 }
1357 handle.clear();
1358 }
1359
Glenn Kasten9156ef32013-08-06 15:39:08 -07001360 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 return handle;
1362}
1363
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001364void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1365 bool unpinIfLast)
1366{
1367 bool remove = false;
1368 sp<EffectModule> effect;
1369 {
1370 Mutex::Autolock _l(mLock);
1371
1372 effect = handle->effect().promote();
1373 if (effect == 0) {
1374 return;
1375 }
1376 // restore suspended effects if the disconnected handle was enabled and the last one.
1377 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1378 if (remove) {
1379 removeEffect_l(effect, true);
1380 }
1381 }
1382 if (remove) {
1383 mAudioFlinger->updateOrphanEffectChains(effect);
1384 AudioSystem::unregisterEffect(effect->id());
1385 if (handle->enabled()) {
1386 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1387 }
1388 }
1389}
1390
Glenn Kastend848eb42016-03-08 13:42:11 -08001391sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1392 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001393{
1394 Mutex::Autolock _l(mLock);
1395 return getEffect_l(sessionId, effectId);
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1403}
1404
1405// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1406// PlaybackThread::mLock held
1407status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1408{
1409 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 bool chainCreated = false;
1413
Eric Laurent5baf2af2013-09-12 17:37:00 -07001414 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1415 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1416 this, effect->desc().name, effect->desc().flags);
1417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 if (chain == 0) {
1419 // create a new chain for this session
1420 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1421 chain = new EffectChain(this, sessionId);
1422 addEffectChain_l(chain);
1423 chain->setStrategy(getStrategyForSession_l(sessionId));
1424 chainCreated = true;
1425 }
1426 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1427
1428 if (chain->getEffectFromId_l(effect->id()) != 0) {
1429 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1430 this, effect->desc().name, chain.get());
1431 return BAD_VALUE;
1432 }
1433
Eric Laurent5baf2af2013-09-12 17:37:00 -07001434 effect->setOffloaded(mType == OFFLOAD, mId);
1435
Eric Laurent81784c32012-11-19 14:55:58 -08001436 status_t status = chain->addEffect_l(effect);
1437 if (status != NO_ERROR) {
1438 if (chainCreated) {
1439 removeEffectChain_l(chain);
1440 }
1441 return status;
1442 }
1443
1444 effect->setDevice(mOutDevice);
1445 effect->setDevice(mInDevice);
1446 effect->setMode(mAudioFlinger->getMode());
1447 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001448
Eric Laurent81784c32012-11-19 14:55:58 -08001449 return NO_ERROR;
1450}
1451
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001454 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t desc = effect->desc();
1456 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1457 detachAuxEffect_l(effect->id());
1458 }
1459
1460 sp<EffectChain> chain = effect->chain().promote();
1461 if (chain != 0) {
1462 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001463 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001464 removeEffectChain_l(chain);
1465 }
1466 } else {
1467 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1468 }
1469}
1470
1471void AudioFlinger::ThreadBase::lockEffectChains_l(
1472 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1473{
1474 effectChains = mEffectChains;
1475 for (size_t i = 0; i < mEffectChains.size(); i++) {
1476 mEffectChains[i]->lock();
1477 }
1478}
1479
1480void AudioFlinger::ThreadBase::unlockEffectChains(
1481 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1482{
1483 for (size_t i = 0; i < effectChains.size(); i++) {
1484 effectChains[i]->unlock();
1485 }
1486}
1487
Glenn Kastend848eb42016-03-08 13:42:11 -08001488sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 Mutex::Autolock _l(mLock);
1491 return getEffectChain_l(sessionId);
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1495 const
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 size_t size = mEffectChains.size();
1498 for (size_t i = 0; i < size; i++) {
1499 if (mEffectChains[i]->sessionId() == sessionId) {
1500 return mEffectChains[i];
1501 }
1502 }
1503 return 0;
1504}
1505
1506void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1507{
1508 Mutex::Autolock _l(mLock);
1509 size_t size = mEffectChains.size();
1510 for (size_t i = 0; i < size; i++) {
1511 mEffectChains[i]->setMode_l(mode);
1512 }
1513}
1514
Eric Laurent83b88082014-06-20 18:31:16 -07001515void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1516{
1517 config->type = AUDIO_PORT_TYPE_MIX;
1518 config->ext.mix.handle = mId;
1519 config->sample_rate = mSampleRate;
1520 config->format = mFormat;
1521 config->channel_mask = mChannelMask;
1522 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1523 AUDIO_PORT_CONFIG_FORMAT;
1524}
1525
Eric Laurent72e3f392015-05-20 14:43:50 -07001526void AudioFlinger::ThreadBase::systemReady()
1527{
1528 Mutex::Autolock _l(mLock);
1529 if (mSystemReady) {
1530 return;
1531 }
1532 mSystemReady = true;
1533
1534 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1535 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1536 }
1537 mPendingConfigEvents.clear();
1538}
1539
Andy Hungdae27702016-10-31 14:01:16 -07001540template <typename T>
1541ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1542 ssize_t index = mActiveTracks.indexOf(track);
1543 if (index >= 0) {
1544 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1545 return index;
1546 }
1547 mActiveTracksGeneration++;
1548 mLatestActiveTrack = track;
1549 ++mBatteryCounter[track->uid()].second;
1550 return mActiveTracks.add(track);
1551}
1552
1553template <typename T>
1554ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1555 ssize_t index = mActiveTracks.remove(track);
1556 if (index < 0) {
1557 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1558 return index;
1559 }
1560 mActiveTracksGeneration++;
1561 --mBatteryCounter[track->uid()].second;
1562 // mLatestActiveTrack is not cleared even if is the same as track.
1563 return index;
1564}
1565
1566template <typename T>
1567void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1568 for (const sp<T> &track : mActiveTracks) {
1569 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1570 }
1571 mLastActiveTracksGeneration = mActiveTracksGeneration;
1572 mActiveTracks.clear();
1573 mLatestActiveTrack.clear();
1574 mBatteryCounter.clear();
1575}
1576
1577template <typename T>
1578void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1579 sp<ThreadBase> thread, bool force) {
1580 // Updates ActiveTracks client uids to the thread wakelock.
1581 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1582 thread->updateWakeLockUids_l(getWakeLockUids());
1583 mLastActiveTracksGeneration = mActiveTracksGeneration;
1584 }
1585
1586 // Updates BatteryNotifier uids
1587 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1588 const uid_t uid = it->first;
1589 ssize_t &previous = it->second.first;
1590 ssize_t &current = it->second.second;
1591 if (current > 0) {
1592 if (previous == 0) {
1593 BatteryNotifier::getInstance().noteStartAudio(uid);
1594 }
1595 previous = current;
1596 ++it;
1597 } else if (current == 0) {
1598 if (previous > 0) {
1599 BatteryNotifier::getInstance().noteStopAudio(uid);
1600 }
1601 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1602 } else /* (current < 0) */ {
1603 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1604 }
1605 }
1606}
Eric Laurent83b88082014-06-20 18:31:16 -07001607
Eric Laurent6acd1d42017-01-04 14:23:29 -08001608void AudioFlinger::ThreadBase::broadcast_l()
1609{
1610 // Thread could be blocked waiting for async
1611 // so signal it to handle state changes immediately
1612 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1613 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1614 mSignalPending = true;
1615 mWaitWorkCV.broadcast();
1616}
1617
Eric Laurent81784c32012-11-19 14:55:58 -08001618// ----------------------------------------------------------------------------
1619// Playback
1620// ----------------------------------------------------------------------------
1621
1622AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1623 AudioStreamOut* output,
1624 audio_io_handle_t id,
1625 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001626 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001627 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001628 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001629 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001630 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001631 mMixerBuffer(NULL),
1632 mMixerBufferSize(0),
1633 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1634 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001635 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001636 mEffectBuffer(NULL),
1637 mEffectBufferSize(0),
1638 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1639 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001640 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001641 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001642 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001643 // mStreamTypes[] initialized in constructor body
1644 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001645 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001646 mMixerStatus(MIXER_IDLE),
1647 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001648 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001649 mBytesRemaining(0),
1650 mCurrentWriteLength(0),
1651 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001652 mWriteAckSequence(0),
1653 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001654 mScreenState(AudioFlinger::mScreenState),
1655 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001656 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001657 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001658{
Glenn Kastend7dca052015-03-05 16:05:54 -08001659 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1660 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001661
1662 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1663 // it would be safer to explicitly pass initial masterVolume/masterMute as
1664 // parameter.
1665 //
1666 // If the HAL we are using has support for master volume or master mute,
1667 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1668 // and the mute set to false).
1669 mMasterVolume = audioFlinger->masterVolume_l();
1670 mMasterMute = audioFlinger->masterMute_l();
1671 if (mOutput && mOutput->audioHwDev) {
1672 if (mOutput->audioHwDev->canSetMasterVolume()) {
1673 mMasterVolume = 1.0;
1674 }
1675
1676 if (mOutput->audioHwDev->canSetMasterMute()) {
1677 mMasterMute = false;
1678 }
1679 }
1680
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001681 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001682
Eric Laurent223fd5c2014-11-11 13:43:36 -08001683 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001684 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001685 stream = (audio_stream_type_t) (stream + 1)) {
1686 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1687 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1688 }
Eric Laurent81784c32012-11-19 14:55:58 -08001689}
1690
1691AudioFlinger::PlaybackThread::~PlaybackThread()
1692{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001693 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001694 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001695 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001696 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001697}
1698
1699void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1700{
1701 dumpInternals(fd, args);
1702 dumpTracks(fd, args);
1703 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001704 dprintf(fd, " Local log:\n");
1705 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001706}
1707
Glenn Kasten0f11b512014-01-31 16:18:54 -08001708void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001709{
1710 const size_t SIZE = 256;
1711 char buffer[SIZE];
1712 String8 result;
1713
Marco Nelissenb2208842014-02-07 14:00:50 -08001714 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001715 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1716 const stream_type_t *st = &mStreamTypes[i];
1717 if (i > 0) {
1718 result.appendFormat(", ");
1719 }
1720 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1721 if (st->mute) {
1722 result.append("M");
1723 }
1724 }
1725 result.append("\n");
1726 write(fd, result.string(), result.length());
1727 result.clear();
1728
Eric Laurent81784c32012-11-19 14:55:58 -08001729 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1730 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001731 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001732 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001733
1734 size_t numtracks = mTracks.size();
1735 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001736 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001737 size_t numactiveseen = 0;
1738 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001739 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001740 Track::appendDumpHeader(result);
1741 for (size_t i = 0; i < numtracks; ++i) {
1742 sp<Track> track = mTracks[i];
1743 if (track != 0) {
1744 bool active = mActiveTracks.indexOf(track) >= 0;
1745 if (active) {
1746 numactiveseen++;
1747 }
1748 track->dump(buffer, SIZE, active);
1749 result.append(buffer);
1750 }
1751 }
1752 } else {
1753 result.append("\n");
1754 }
1755 if (numactiveseen != numactive) {
1756 // some tracks in the active list were not in the tracks list
1757 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1758 " not in the track list\n");
1759 result.append(buffer);
1760 Track::appendDumpHeader(result);
1761 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001762 sp<Track> track = mActiveTracks[i];
1763 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001764 track->dump(buffer, SIZE, true);
1765 result.append(buffer);
1766 }
1767 }
1768 }
1769
1770 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001771}
1772
1773void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1774{
Glenn Kasten44182c22015-03-05 17:12:23 -08001775 dumpBase(fd, args);
1776
Elliott Hughes87cebad2014-05-22 10:14:43 -07001777 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001778 dprintf(fd, " Last write occurred (msecs): %llu\n",
1779 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001780 dprintf(fd, " Total writes: %d\n", mNumWrites);
1781 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1782 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1783 dprintf(fd, " Suspend count: %d\n", mSuspended);
1784 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1785 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1786 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1787 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001788 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001789 AudioStreamOut *output = mOutput;
1790 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001791 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1792 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001793 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1794 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1795 if (mPipeSink.get() != nullptr) {
1796 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1797 }
1798 if (output != nullptr) {
1799 dprintf(fd, " Hal stream dump:\n");
1800 (void)output->stream->dump(fd);
1801 }
Eric Laurent81784c32012-11-19 14:55:58 -08001802}
1803
1804// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001805
1806void AudioFlinger::PlaybackThread::onFirstRef()
1807{
Glenn Kastend7dca052015-03-05 16:05:54 -08001808 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001809}
1810
1811// ThreadBase virtuals
1812void AudioFlinger::PlaybackThread::preExit()
1813{
1814 ALOGV(" preExit()");
1815 // FIXME this is using hard-coded strings but in the future, this functionality will be
1816 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001817 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1818 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001819}
1820
1821// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1822sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1823 const sp<AudioFlinger::Client>& client,
1824 audio_stream_type_t streamType,
1825 uint32_t sampleRate,
1826 audio_format_t format,
1827 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001828 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001829 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001830 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001831 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001832 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001833 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001834 status_t *status,
1835 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001836{
Glenn Kasten74935e42013-12-19 08:56:45 -08001837 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001838 sp<Track> track;
1839 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001840 audio_output_flags_t outputFlags = mOutput->flags;
1841
1842 // special case for FAST flag considered OK if fast mixer is present
1843 if (hasFastMixer()) {
1844 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1845 }
1846
1847 // Check if requested flags are compatible with output stream flags
1848 if ((*flags & outputFlags) != *flags) {
1849 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1850 *flags, outputFlags);
1851 *flags = (audio_output_flags_t)(*flags & outputFlags);
1852 }
Eric Laurent81784c32012-11-19 14:55:58 -08001853
Eric Laurent81784c32012-11-19 14:55:58 -08001854 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001855 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001856 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001857 // PCM data
1858 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001859 // TODO: extract as a data library function that checks that a computationally
1860 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001861 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001862 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1863 (channelMask == AUDIO_CHANNEL_OUT_MONO
1864 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001865 // hardware sample rate
1866 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001867 // normal mixer has an associated fast mixer
1868 hasFastMixer() &&
1869 // there are sufficient fast track slots available
1870 (mFastTrackAvailMask != 0)
1871 // FIXME test that MixerThread for this fast track has a capable output HAL
1872 // FIXME add a permission test also?
1873 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001874 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1875 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001876 // read the fast track multiplier property the first time it is needed
1877 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1878 if (ok != 0) {
1879 ALOGE("%s pthread_once failed: %d", __func__, ok);
1880 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001881 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001882 }
Eric Laurent4c415062016-06-17 16:14:16 -07001883
1884 // check compatibility with audio effects.
1885 { // scope for mLock
1886 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001887 for (audio_session_t session : {
1888 AUDIO_SESSION_OUTPUT_STAGE,
1889 AUDIO_SESSION_OUTPUT_MIX,
1890 sessionId,
1891 }) {
1892 sp<EffectChain> chain = getEffectChain_l(session);
1893 if (chain.get() != nullptr) {
1894 audio_output_flags_t old = *flags;
1895 chain->checkOutputFlagCompatibility(flags);
1896 if (old != *flags) {
1897 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1898 (int)session, (int)old, (int)*flags);
1899 }
Eric Laurent4c415062016-06-17 16:14:16 -07001900 }
1901 }
1902 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001903 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001904 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1905 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001906 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001907 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1908 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001909 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001910 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001911 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001912 audio_is_linear_pcm(format),
1913 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001914 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001915 }
1916 }
1917 // For normal PCM streaming tracks, update minimum frame count.
1918 // For compatibility with AudioTrack calculation, buffer depth is forced
1919 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1920 // This is probably too conservative, but legacy application code may depend on it.
1921 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001922 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001923 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001924 // this must match AudioTrack.cpp calculateMinFrameCount().
1925 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001926 uint32_t latencyMs = 0;
1927 lStatus = mOutput->stream->getLatency(&latencyMs);
1928 if (lStatus != OK) {
1929 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1930 goto Exit;
1931 }
Eric Laurent81784c32012-11-19 14:55:58 -08001932 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1933 if (minBufCount < 2) {
1934 minBufCount = 2;
1935 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001936 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1937 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001938 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001939 minBufCount * sourceFramesNeededWithTimestretch(
1940 sampleRate, mNormalFrameCount,
1941 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001942 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001943 frameCount = minFrameCount;
1944 }
Eric Laurent81784c32012-11-19 14:55:58 -08001945 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001946 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001947
Glenn Kastenc3df8382014-03-13 15:05:25 -07001948 switch (mType) {
1949
1950 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001951 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001952 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001953 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1954 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001955 sampleRate, format, channelMask, mOutput, mFormat);
1956 lStatus = BAD_VALUE;
1957 goto Exit;
1958 }
1959 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001960 break;
1961
1962 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001963 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001964 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1965 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001966 sampleRate, format, channelMask, mOutput, mFormat);
1967 lStatus = BAD_VALUE;
1968 goto Exit;
1969 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001970 break;
1971
1972 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001973 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001974 ALOGE("createTrack_l() Bad parameter: format %#x \""
1975 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001976 format, mOutput, mFormat);
1977 lStatus = BAD_VALUE;
1978 goto Exit;
1979 }
Andy Hungcd044842014-08-07 11:04:34 -07001980 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001981 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1982 lStatus = BAD_VALUE;
1983 goto Exit;
1984 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001985 break;
1986
Eric Laurent81784c32012-11-19 14:55:58 -08001987 }
1988
1989 lStatus = initCheck();
1990 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001991 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001992 goto Exit;
1993 }
1994
1995 { // scope for mLock
1996 Mutex::Autolock _l(mLock);
1997
1998 // all tracks in same audio session must share the same routing strategy otherwise
1999 // conflicts will happen when tracks are moved from one output to another by audio policy
2000 // manager
2001 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2002 for (size_t i = 0; i < mTracks.size(); ++i) {
2003 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002004 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002005 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2006 if (sessionId == t->sessionId() && strategy != actual) {
2007 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2008 strategy, actual);
2009 lStatus = BAD_VALUE;
2010 goto Exit;
2011 }
2012 }
2013 }
2014
Glenn Kastend79072e2016-01-06 08:41:20 -08002015 track = new Track(this, client, streamType, sampleRate, format,
2016 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002017 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002018
Glenn Kasten03003332013-08-06 15:40:54 -07002019 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2020 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002021 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002022 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002023 goto Exit;
2024 }
2025 mTracks.add(track);
2026
2027 sp<EffectChain> chain = getEffectChain_l(sessionId);
2028 if (chain != 0) {
2029 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2030 track->setMainBuffer(chain->inBuffer());
2031 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2032 chain->incTrackCnt();
2033 }
2034
Eric Laurent05067782016-06-01 18:27:28 -07002035 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002036 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2037 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2038 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002039 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002040 }
2041 }
2042
2043 lStatus = NO_ERROR;
2044
2045Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002046 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002047 return track;
2048}
2049
2050uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2051{
2052 return latency;
2053}
2054
2055uint32_t AudioFlinger::PlaybackThread::latency() const
2056{
2057 Mutex::Autolock _l(mLock);
2058 return latency_l();
2059}
2060uint32_t AudioFlinger::PlaybackThread::latency_l() const
2061{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002062 uint32_t latency;
2063 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2064 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002065 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002066 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002067}
2068
2069void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2070{
2071 Mutex::Autolock _l(mLock);
2072 // Don't apply master volume in SW if our HAL can do it for us.
2073 if (mOutput && mOutput->audioHwDev &&
2074 mOutput->audioHwDev->canSetMasterVolume()) {
2075 mMasterVolume = 1.0;
2076 } else {
2077 mMasterVolume = value;
2078 }
2079}
2080
2081void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2082{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002083 if (isDuplicating()) {
2084 return;
2085 }
Eric Laurent81784c32012-11-19 14:55:58 -08002086 Mutex::Autolock _l(mLock);
2087 // Don't apply master mute in SW if our HAL can do it for us.
2088 if (mOutput && mOutput->audioHwDev &&
2089 mOutput->audioHwDev->canSetMasterMute()) {
2090 mMasterMute = false;
2091 } else {
2092 mMasterMute = muted;
2093 }
2094}
2095
2096void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2097{
2098 Mutex::Autolock _l(mLock);
2099 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002100 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002101}
2102
2103void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2104{
2105 Mutex::Autolock _l(mLock);
2106 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002107 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002108}
2109
2110float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2111{
2112 Mutex::Autolock _l(mLock);
2113 return mStreamTypes[stream].volume;
2114}
2115
2116// addTrack_l() must be called with ThreadBase::mLock held
2117status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2118{
2119 status_t status = ALREADY_EXISTS;
2120
Eric Laurent81784c32012-11-19 14:55:58 -08002121 if (mActiveTracks.indexOf(track) < 0) {
2122 // the track is newly added, make sure it fills up all its
2123 // buffers before playing. This is to ensure the client will
2124 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002125 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002126 TrackBase::track_state state = track->mState;
2127 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002128 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002129 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002130 mLock.lock();
2131 // abort track was stopped/paused while we released the lock
2132 if (state != track->mState) {
2133 if (status == NO_ERROR) {
2134 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002135 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002136 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002137 mLock.lock();
2138 }
2139 return INVALID_OPERATION;
2140 }
2141 // abort if start is rejected by audio policy manager
2142 if (status != NO_ERROR) {
2143 return PERMISSION_DENIED;
2144 }
2145#ifdef ADD_BATTERY_DATA
2146 // to track the speaker usage
2147 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2148#endif
2149 }
2150
Eric Laurent51716182016-02-29 18:00:56 -08002151 // set retry count for buffer fill
2152 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002153 if (track->isStopping_1()) {
2154 track->mRetryCount = kMaxTrackStopRetriesOffload;
2155 } else {
2156 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2157 }
2158 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002159 } else {
2160 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002161 track->mFillingUpStatus =
2162 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002163 }
2164
Eric Laurent81784c32012-11-19 14:55:58 -08002165 track->mResetDone = false;
2166 track->mPresentationCompleteFrames = 0;
2167 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002168 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2169 if (chain != 0) {
2170 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2171 track->sessionId());
2172 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002173 }
2174
Andy Hung2148bf02016-11-28 19:01:02 -08002175 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07002176 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08002177 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179 status = NO_ERROR;
2180 }
2181
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002182 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002183 return status;
2184}
2185
Eric Laurentbfb1b832013-01-07 09:53:42 -08002186bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002187{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002188 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002189 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002190 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2191 track->mState = TrackBase::STOPPED;
2192 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002193 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002194 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002196 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002197
2198 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002199}
2200
2201void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2202{
2203 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002204
2205 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07002206 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08002207 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2208
Eric Laurent81784c32012-11-19 14:55:58 -08002209 mTracks.remove(track);
2210 deleteTrackName_l(track->name());
2211 // redundant as track is about to be destroyed, for dumpsys only
2212 track->mName = -1;
2213 if (track->isFastTrack()) {
2214 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002215 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002216 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2217 mFastTrackAvailMask |= 1 << index;
2218 // redundant as track is about to be destroyed, for dumpsys only
2219 track->mFastIndex = -1;
2220 }
2221 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2222 if (chain != 0) {
2223 chain->decTrackCnt();
2224 }
2225}
2226
2227String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2228{
Eric Laurent81784c32012-11-19 14:55:58 -08002229 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002230 String8 out_s8;
2231 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2232 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002233 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002234 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002237void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002238 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2239 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002240
Eric Laurent73e26b62015-04-27 16:55:58 -07002241 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002242
2243 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002244 case AUDIO_OUTPUT_OPENED:
2245 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002246 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002247 desc->mChannelMask = mChannelMask;
2248 desc->mSamplingRate = mSampleRate;
2249 desc->mFormat = mFormat;
2250 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002251 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002252 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002253 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002254 break;
2255
Eric Laurent73e26b62015-04-27 16:55:58 -07002256 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002257 default:
2258 break;
2259 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002260 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002261}
2262
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002263void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002264{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002265 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002266}
2267
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002268void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002270 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002271}
2272
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002273void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002274{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002275 mCallbackThread->setAsyncError();
2276}
2277
Eric Laurent3b4529e2013-09-05 18:09:19 -07002278void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279{
2280 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002281 // reject out of sequence requests
2282 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2283 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284 mWaitWorkCV.signal();
2285 }
2286}
2287
Eric Laurent3b4529e2013-09-05 18:09:19 -07002288void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002289{
2290 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002291 // reject out of sequence requests
2292 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2293 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002294 mWaitWorkCV.signal();
2295 }
2296}
2297
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002298void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002299{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002300 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002301 mSampleRate = mOutput->getSampleRate();
2302 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002303 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002304 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002305 }
Andy Hung9a592762014-07-21 21:56:01 -07002306 if ((mType == MIXER || mType == DUPLICATING)
2307 && !isValidPcmSinkChannelMask(mChannelMask)) {
2308 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2309 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002310 }
Andy Hunge5412692014-05-16 11:25:07 -07002311 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002312
2313 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002314 status_t result = mOutput->stream->getFormat(&mHALFormat);
2315 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002316 // Get format from the shim, which will be different than the HAL format
2317 // if playing compressed audio over HDMI passthrough.
2318 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002319 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002320 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002321 }
Andy Hung6146c082014-03-18 11:56:15 -07002322 if ((mType == MIXER || mType == DUPLICATING)
2323 && !isValidPcmSinkFormat(mFormat)) {
2324 LOG_FATAL("HAL format %#x not supported for mixed output",
2325 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002326 }
Phil Burk062e67a2015-02-11 13:40:50 -08002327 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002328 result = mOutput->stream->getBufferSize(&mBufferSize);
2329 LOG_ALWAYS_FATAL_IF(result != OK,
2330 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002331 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002332 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002333 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002334 mFrameCount);
2335 }
2336
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002337 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2338 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002340 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002341 }
2342 }
2343
Eric Laurentd1f69b02014-12-15 14:33:13 -08002344 mHwSupportsPause = false;
2345 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002346 bool supportsPause = false, supportsResume = false;
2347 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2348 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002349 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002350 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002351 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002352 } else if (supportsResume) {
2353 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002354 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002355 }
2356 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002357 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2358 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2359 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002360
Andy Hungfbfc3952015-01-15 13:33:51 -08002361 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2362 // For best precision, we use float instead of the associated output
2363 // device format (typically PCM 16 bit).
2364
2365 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2366 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2367 mBufferSize = mFrameSize * mFrameCount;
2368
2369 // TODO: We currently use the associated output device channel mask and sample rate.
2370 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2371 // (if a valid mask) to avoid premature downmix.
2372 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2373 // instead of the output device sample rate to avoid loss of high frequency information.
2374 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2375 }
2376
Andy Hung09a50072014-02-27 14:30:47 -08002377 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002378 double multiplier = 1.0;
2379 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2380 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002381 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2382 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002383
Eric Laurent81784c32012-11-19 14:55:58 -08002384 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2385 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2386 maxNormalFrameCount = maxNormalFrameCount & ~15;
2387 if (maxNormalFrameCount < minNormalFrameCount) {
2388 maxNormalFrameCount = minNormalFrameCount;
2389 }
2390 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2391 if (multiplier <= 1.0) {
2392 multiplier = 1.0;
2393 } else if (multiplier <= 2.0) {
2394 if (2 * mFrameCount <= maxNormalFrameCount) {
2395 multiplier = 2.0;
2396 } else {
2397 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2398 }
2399 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002400 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002401 }
2402 }
2403 mNormalFrameCount = multiplier * mFrameCount;
2404 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002405 if (mType == MIXER || mType == DUPLICATING) {
2406 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2407 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002408 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002409 mNormalFrameCount);
2410
Andy Hung08fb1742015-05-31 23:22:10 -07002411 // Check if we want to throttle the processing to no more than 2x normal rate
2412 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002413 mThreadThrottleTimeMs = 0;
2414 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002415 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2416
Andy Hung010a1a12014-03-13 13:57:33 -07002417 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2418 // Originally this was int16_t[] array, need to remove legacy implications.
2419 free(mSinkBuffer);
2420 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002421 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2422 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2423 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002424 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002425
Andy Hung69aed5f2014-02-25 17:24:40 -08002426 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2427 // drives the output.
2428 free(mMixerBuffer);
2429 mMixerBuffer = NULL;
2430 if (mMixerBufferEnabled) {
2431 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2432 mMixerBufferSize = mNormalFrameCount * mChannelCount
2433 * audio_bytes_per_sample(mMixerBufferFormat);
2434 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2435 }
Andy Hung98ef9782014-03-04 14:46:50 -08002436 free(mEffectBuffer);
2437 mEffectBuffer = NULL;
2438 if (mEffectBufferEnabled) {
2439 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2440 mEffectBufferSize = mNormalFrameCount * mChannelCount
2441 * audio_bytes_per_sample(mEffectBufferFormat);
2442 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2443 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002444
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // force reconfiguration of effect chains and engines to take new buffer size and audio
2446 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002447 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2449 // matter.
2450 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2451 Vector< sp<EffectChain> > effectChains = mEffectChains;
2452 for (size_t i = 0; i < effectChains.size(); i ++) {
2453 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2454 }
2455}
2456
2457
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002458status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002459{
2460 if (halFrames == NULL || dspFrames == NULL) {
2461 return BAD_VALUE;
2462 }
2463 Mutex::Autolock _l(mLock);
2464 if (initCheck() != NO_ERROR) {
2465 return INVALID_OPERATION;
2466 }
Andy Hung818e7a32016-02-16 18:08:07 -08002467 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002468 *halFrames = framesWritten;
2469
2470 if (isSuspended()) {
2471 // return an estimation of rendered frames when the output is suspended
2472 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002473 *dspFrames = (uint32_t)
2474 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002475 return NO_ERROR;
2476 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002477 status_t status;
2478 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002479 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002480 *dspFrames = (size_t)frames;
2481 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002482 }
2483}
2484
Eric Laurent4c415062016-06-17 16:14:16 -07002485// hasAudioSession_l() must be called with ThreadBase::mLock held
2486uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002487{
Eric Laurent81784c32012-11-19 14:55:58 -08002488 uint32_t result = 0;
2489 if (getEffectChain_l(sessionId) != 0) {
2490 result = EFFECT_SESSION;
2491 }
2492
2493 for (size_t i = 0; i < mTracks.size(); ++i) {
2494 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002495 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002496 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002497 if (track->isFastTrack()) {
2498 result |= FAST_SESSION;
2499 }
Eric Laurent81784c32012-11-19 14:55:58 -08002500 break;
2501 }
2502 }
2503
2504 return result;
2505}
2506
Glenn Kastend848eb42016-03-08 13:42:11 -08002507uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002508{
2509 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2510 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2511 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2512 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2513 }
2514 for (size_t i = 0; i < mTracks.size(); i++) {
2515 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002516 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002517 return AudioSystem::getStrategyForStream(track->streamType());
2518 }
2519 }
2520 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2521}
2522
2523
Phil Burk062e67a2015-02-11 13:40:50 -08002524AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002525{
2526 Mutex::Autolock _l(mLock);
2527 return mOutput;
2528}
2529
Phil Burk062e67a2015-02-11 13:40:50 -08002530AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002531{
2532 Mutex::Autolock _l(mLock);
2533 AudioStreamOut *output = mOutput;
2534 mOutput = NULL;
2535 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2536 // must push a NULL and wait for ack
2537 mOutputSink.clear();
2538 mPipeSink.clear();
2539 mNormalSink.clear();
2540 return output;
2541}
2542
2543// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002544sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002545{
2546 if (mOutput == NULL) {
2547 return NULL;
2548 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002550}
2551
2552uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2553{
2554 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2555}
2556
2557status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2558{
2559 if (!isValidSyncEvent(event)) {
2560 return BAD_VALUE;
2561 }
2562
2563 Mutex::Autolock _l(mLock);
2564
2565 for (size_t i = 0; i < mTracks.size(); ++i) {
2566 sp<Track> track = mTracks[i];
2567 if (event->triggerSession() == track->sessionId()) {
2568 (void) track->setSyncEvent(event);
2569 return NO_ERROR;
2570 }
2571 }
2572
2573 return NAME_NOT_FOUND;
2574}
2575
2576bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2577{
2578 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2579}
2580
2581void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2582 const Vector< sp<Track> >& tracksToRemove)
2583{
2584 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002585 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002586 for (size_t i = 0 ; i < count ; i++) {
2587 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002588 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002589 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002590 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002591#ifdef ADD_BATTERY_DATA
2592 // to track the speaker usage
2593 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2594#endif
2595 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002596 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002597 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002598 }
Eric Laurent81784c32012-11-19 14:55:58 -08002599 }
2600 }
2601 }
Eric Laurent81784c32012-11-19 14:55:58 -08002602}
2603
2604void AudioFlinger::PlaybackThread::checkSilentMode_l()
2605{
2606 if (!mMasterMute) {
2607 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002608 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2609 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2610 return;
2611 }
Eric Laurent81784c32012-11-19 14:55:58 -08002612 if (property_get("ro.audio.silent", value, "0") > 0) {
2613 char *endptr;
2614 unsigned long ul = strtoul(value, &endptr, 0);
2615 if (*endptr == '\0' && ul != 0) {
2616 ALOGD("Silence is golden");
2617 // The setprop command will not allow a property to be changed after
2618 // the first time it is set, so we don't have to worry about un-muting.
2619 setMasterMute_l(true);
2620 }
2621 }
2622 }
2623}
2624
2625// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002626ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002627{
Eric Laurent81784c32012-11-19 14:55:58 -08002628 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002629 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002630 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002631
2632 // If an NBAIO sink is present, use it to write the normal mixer's submix
2633 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002634
Andy Hung010a1a12014-03-13 13:57:33 -07002635 const size_t count = mBytesRemaining / mFrameSize;
2636
Simon Wilson2d590962012-11-29 15:18:50 -08002637 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002638 // update the setpoint when AudioFlinger::mScreenState changes
2639 uint32_t screenState = AudioFlinger::mScreenState;
2640 if (screenState != mScreenState) {
2641 mScreenState = screenState;
2642 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2643 if (pipe != NULL) {
2644 pipe->setAvgFrames((mScreenState & 1) ?
2645 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2646 }
2647 }
Andy Hung010a1a12014-03-13 13:57:33 -07002648 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002649 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002650 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002651 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002652 } else {
2653 bytesWritten = framesWritten;
2654 }
2655 // otherwise use the HAL / AudioStreamOut directly
2656 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002657 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002658
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002660 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2661 mWriteAckSequence += 2;
2662 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002664 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002665 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002666 // FIXME We should have an implementation of timestamps for direct output threads.
2667 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002668 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002669
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670 if (mUseAsyncWrite &&
2671 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2672 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002673 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002675 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 }
Eric Laurent81784c32012-11-19 14:55:58 -08002677 }
2678
Eric Laurent81784c32012-11-19 14:55:58 -08002679 mNumWrites++;
2680 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002681 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 return bytesWritten;
2683}
2684
2685void AudioFlinger::PlaybackThread::threadLoop_drain()
2686{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002687 bool supportsDrain = false;
2688 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002689 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2690 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002691 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2692 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002693 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002694 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002695 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002696 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002697 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698 }
2699}
2700
2701void AudioFlinger::PlaybackThread::threadLoop_exit()
2702{
Eric Laurent275e8e92014-11-30 15:14:47 -08002703 {
2704 Mutex::Autolock _l(mLock);
2705 for (size_t i = 0; i < mTracks.size(); i++) {
2706 sp<Track> track = mTracks[i];
2707 track->invalidate();
2708 }
Andy Hungdae27702016-10-31 14:01:16 -07002709 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2710 // After we exit there are no more track changes sent to BatteryNotifier
2711 // because that requires an active threadLoop.
2712 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2713 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002714 }
Eric Laurent81784c32012-11-19 14:55:58 -08002715}
2716
2717/*
2718The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002719 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002720 - mActiveSleepTimeUs from activeSleepTimeUs()
2721 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002722 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2723 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002724 - maxPeriod from frame count and sample rate (MIXER only)
2725
2726The parameters that affect these derived values are:
2727 - frame count
2728 - frame size
2729 - sample rate
2730 - device type: A2DP or not
2731 - device latency
2732 - format: PCM or not
2733 - active sleep time
2734 - idle sleep time
2735*/
2736
2737void AudioFlinger::PlaybackThread::cacheParameters_l()
2738{
Andy Hung25c2dac2014-02-27 14:56:00 -08002739 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002740 mActiveSleepTimeUs = activeSleepTimeUs();
2741 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002742
2743 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2744 // truncating audio when going to standby.
2745 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2746 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2747 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2748 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2749 }
2750 }
Eric Laurent81784c32012-11-19 14:55:58 -08002751}
2752
Eric Laurent13084622016-05-17 10:51:49 -07002753bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002754{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002755 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002756 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002757 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 size_t size = mTracks.size();
2759 for (size_t i = 0; i < size; i++) {
2760 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002761 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002762 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002763 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002764 }
2765 }
Eric Laurent13084622016-05-17 10:51:49 -07002766 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002767}
2768
Haynes Mathew George05317d22016-05-03 16:34:26 -07002769void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2770{
2771 Mutex::Autolock _l(mLock);
2772 invalidateTracks_l(streamType);
2773}
2774
Eric Laurent81784c32012-11-19 14:55:58 -08002775status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2776{
Glenn Kastend848eb42016-03-08 13:42:11 -08002777 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002778 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2779 status_t result = EffectBufferHalInterface::mirror(
2780 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2781 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2782 &halInBuffer);
2783 if (result != OK) return result;
2784 halOutBuffer = halInBuffer;
2785 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002786
2787 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002788 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002789 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002790 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002791 if (mType != DIRECT) {
2792 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002793 status_t result = EffectBufferHalInterface::allocate(
2794 numSamples * sizeof(int16_t),
2795 &halInBuffer);
2796 if (result != OK) return result;
2797 buffer = halInBuffer->audioBuffer()->s16;
2798 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2799 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002800 }
2801
2802 // Attach all tracks with same session ID to this chain.
2803 for (size_t i = 0; i < mTracks.size(); ++i) {
2804 sp<Track> track = mTracks[i];
2805 if (session == track->sessionId()) {
2806 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2807 buffer);
2808 track->setMainBuffer(buffer);
2809 chain->incTrackCnt();
2810 }
2811 }
2812
2813 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002814 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002815 if (session == track->sessionId()) {
2816 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2817 chain->incActiveTrackCnt();
2818 }
2819 }
2820 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002821 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002822 chain->setInBuffer(halInBuffer);
2823 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002824 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002825 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002826 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2827 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002828 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002829 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002830 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // Effect chain for other sessions are inserted at beginning of effect
2832 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002833 // sessions is not important.
2834 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2835 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2836 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002837 size_t size = mEffectChains.size();
2838 size_t i = 0;
2839 for (i = 0; i < size; i++) {
2840 if (mEffectChains[i]->sessionId() < session) {
2841 break;
2842 }
2843 }
2844 mEffectChains.insertAt(chain, i);
2845 checkSuspendOnAddEffectChain_l(chain);
2846
2847 return NO_ERROR;
2848}
2849
2850size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2851{
Glenn Kastend848eb42016-03-08 13:42:11 -08002852 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002853
2854 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2855
2856 for (size_t i = 0; i < mEffectChains.size(); i++) {
2857 if (chain == mEffectChains[i]) {
2858 mEffectChains.removeAt(i);
2859 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002860 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002861 if (session == track->sessionId()) {
2862 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2863 chain.get(), session);
2864 chain->decActiveTrackCnt();
2865 }
2866 }
2867
2868 // detach all tracks with same session ID from this chain
2869 for (size_t i = 0; i < mTracks.size(); ++i) {
2870 sp<Track> track = mTracks[i];
2871 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002872 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002873 chain->decTrackCnt();
2874 }
2875 }
2876 break;
2877 }
2878 }
2879 return mEffectChains.size();
2880}
2881
2882status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002883 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002884{
2885 Mutex::Autolock _l(mLock);
2886 return attachAuxEffect_l(track, EffectId);
2887}
2888
2889status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002890 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002891{
2892 status_t status = NO_ERROR;
2893
2894 if (EffectId == 0) {
2895 track->setAuxBuffer(0, NULL);
2896 } else {
2897 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2898 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2899 if (effect != 0) {
2900 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2901 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2902 } else {
2903 status = INVALID_OPERATION;
2904 }
2905 } else {
2906 status = BAD_VALUE;
2907 }
2908 }
2909 return status;
2910}
2911
2912void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2913{
2914 for (size_t i = 0; i < mTracks.size(); ++i) {
2915 sp<Track> track = mTracks[i];
2916 if (track->auxEffectId() == effectId) {
2917 attachAuxEffect_l(track, 0);
2918 }
2919 }
2920}
2921
2922bool AudioFlinger::PlaybackThread::threadLoop()
2923{
Glenn Kasten388d5712017-04-07 14:38:41 -07002924 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002925
Eric Laurent81784c32012-11-19 14:55:58 -08002926 Vector< sp<Track> > tracksToRemove;
2927
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002928 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002929 nsecs_t lastWriteFinished = -1; // time last server write completed
2930 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002931
2932 // MIXER
2933 nsecs_t lastWarning = 0;
2934
2935 // DUPLICATING
2936 // FIXME could this be made local to while loop?
2937 writeFrames = 0;
2938
2939 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002940 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002941
2942 if (mType == MIXER) {
2943 sleepTimeShift = 0;
2944 }
2945
2946 CpuStats cpuStats;
2947 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2948
2949 acquireWakeLock();
2950
Glenn Kasteneef598c2017-04-03 14:41:13 -07002951 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2952 // thread associated with this PlaybackThread.
2953 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2954 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002955 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2956 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002957 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002958 const char *logString = NULL;
2959
rago1bb90822017-05-02 18:31:48 -07002960 // Estimated time for next buffer to be written to hal. This is used only on
2961 // suspended mode (for now) to help schedule the wait time until next iteration.
2962 nsecs_t timeLoopNextNs = 0;
2963
Eric Laurent664539d2013-09-23 18:24:31 -07002964 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002965
Eric Laurent81784c32012-11-19 14:55:58 -08002966 while (!exitPending())
2967 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002968 // Log merge requests are performed during AudioFlinger binder transactions, but
2969 // that does not cover audio playback. It's requested here for that reason.
2970 mAudioFlinger->requestLogMerge();
2971
Eric Laurent81784c32012-11-19 14:55:58 -08002972 cpuStats.sample(myName);
2973
2974 Vector< sp<EffectChain> > effectChains;
2975
Eric Laurent81784c32012-11-19 14:55:58 -08002976 { // scope for mLock
2977
2978 Mutex::Autolock _l(mLock);
2979
Eric Laurent021cf962014-05-13 10:18:14 -07002980 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002981
Glenn Kasteneef598c2017-04-03 14:41:13 -07002982 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002983 if (logString != NULL) {
2984 mNBLogWriter->logTimestamp();
2985 mNBLogWriter->log(logString);
2986 logString = NULL;
2987 }
2988
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002989 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002990 // and associate with the sink frames written out. We need
2991 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002992 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002993 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002994 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08002995 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07002996 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08002997 ExtendedTimestamp timestamp; // use private copy to fetch
2998 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07002999
3000 // We keep track of the last valid kernel position in case we are in underrun
3001 // and the normal mixer period is the same as the fast mixer period, or there
3002 // is some error from the HAL.
3003 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3004 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3005 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3006 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3007 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3008
3009 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3010 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3011 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3012 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003013 }
3014
3015 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3016 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003017 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003018 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003019 }
3020
Andy Hung818e7a32016-02-16 18:08:07 -08003021 // copy over kernel info
3022 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003023 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3024 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003025 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3026 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003027 }
3028 // mFramesWritten for non-offloaded tracks are contiguous
3029 // even after standby() is called. This is useful for the track frame
3030 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003031 bool serverLocationUpdate = false;
3032 if (mFramesWritten != lastFramesWritten) {
3033 serverLocationUpdate = true;
3034 lastFramesWritten = mFramesWritten;
3035 }
3036 // Only update timestamps if there is a meaningful change.
3037 // Either the kernel timestamp must be valid or we have written something.
3038 if (kernelLocationUpdate || serverLocationUpdate) {
3039 if (serverLocationUpdate) {
3040 // use the time before we called the HAL write - it is a bit more accurate
3041 // to when the server last read data than the current time here.
3042 //
3043 // If we haven't written anything, mLastWriteTime will be -1
3044 // and we use systemTime().
3045 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3046 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3047 ? systemTime() : mLastWriteTime;
3048 }
Andy Hungdae27702016-10-31 14:01:16 -07003049
3050 for (const sp<Track> &t : mActiveTracks) {
3051 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003052 t->updateTrackFrameInfo(
3053 t->mAudioTrackServerProxy->framesReleased(),
3054 mFramesWritten,
3055 mTimestamp);
3056 }
Andy Hunge10393e2015-06-12 13:59:33 -07003057 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003058 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003059#if 0
3060 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003061 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003062 timespec ts;
3063 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003064 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003065 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003066 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003067 }
3068 ++z;
3069#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003070 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003071 if (mSignalPending) {
3072 // A signal was raised while we were unlocked
3073 mSignalPending = false;
3074 } else if (waitingAsyncCallback_l()) {
3075 if (exitPending()) {
3076 break;
3077 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003078 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003079 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003080 releaseWakeLock_l();
3081 released = true;
3082 }
Andy Hung10cbff12017-02-21 17:30:14 -08003083
3084 const int64_t waitNs = computeWaitTimeNs_l();
3085 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3086 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3087 if (status == TIMED_OUT) {
3088 mSignalPending = true; // if timeout recheck everything
3089 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003091 if (released) {
3092 acquireWakeLock_l();
3093 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003094 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3095 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003096
3097 continue;
3098 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003099 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100 isSuspended()) {
3101 // put audio hardware into standby after short delay
3102 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003103
3104 threadLoop_standby();
3105
3106 mStandby = true;
3107 }
3108
3109 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3110 // we're about to wait, flush the binder command buffer
3111 IPCThreadState::self()->flushCommands();
3112
3113 clearOutputTracks();
3114
3115 if (exitPending()) {
3116 break;
3117 }
3118
3119 releaseWakeLock_l();
3120 // wait until we have something to do...
3121 ALOGV("%s going to sleep", myName.string());
3122 mWaitWorkCV.wait(mLock);
3123 ALOGV("%s waking up", myName.string());
3124 acquireWakeLock_l();
3125
3126 mMixerStatus = MIXER_IDLE;
3127 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3128 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003129 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003130 checkSilentMode_l();
3131
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003132 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3133 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003134 if (mType == MIXER) {
3135 sleepTimeShift = 0;
3136 }
3137
3138 continue;
3139 }
3140 }
Eric Laurent81784c32012-11-19 14:55:58 -08003141 // mMixerStatusIgnoringFastTracks is also updated internally
3142 mMixerStatus = prepareTracks_l(&tracksToRemove);
3143
Andy Hungdae27702016-10-31 14:01:16 -07003144 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003145
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // prevent any changes in effect chain list and in each effect chain
3147 // during mixing and effect process as the audio buffers could be deleted
3148 // or modified if an effect is created or deleted
3149 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003150 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003151
Eric Laurentbfb1b832013-01-07 09:53:42 -08003152 if (mBytesRemaining == 0) {
3153 mCurrentWriteLength = 0;
3154 if (mMixerStatus == MIXER_TRACKS_READY) {
3155 // threadLoop_mix() sets mCurrentWriteLength
3156 threadLoop_mix();
3157 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3158 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003159 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160 // must be written to HAL
3161 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003162 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003163 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 }
3165 }
Andy Hung98ef9782014-03-04 14:46:50 -08003166 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003167 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003168 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3169 // or mSinkBuffer (if there are no effects).
3170 //
3171 // This is done pre-effects computation; if effects change to
3172 // support higher precision, this needs to move.
3173 //
3174 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003175 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003176 if (mMixerBufferValid) {
3177 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3178 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3179
Andy Hung2ddee192015-12-18 17:34:44 -08003180 // mono blend occurs for mixer threads only (not direct or offloaded)
3181 // and is handled here if we're going directly to the sink.
3182 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003183 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3184 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003185 }
3186
Andy Hung98ef9782014-03-04 14:46:50 -08003187 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3188 mNormalFrameCount * mChannelCount);
3189 }
3190
Eric Laurentbfb1b832013-01-07 09:53:42 -08003191 mBytesRemaining = mCurrentWriteLength;
3192 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003193 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3194 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3195 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3196 mBytesWritten += mBytesRemaining;
3197 mFramesWritten += framesRemaining;
3198 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 mBytesRemaining = 0;
3200 }
Eric Laurent81784c32012-11-19 14:55:58 -08003201
Eric Laurentbfb1b832013-01-07 09:53:42 -08003202 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003203 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 for (size_t i = 0; i < effectChains.size(); i ++) {
3205 effectChains[i]->process_l();
3206 }
Eric Laurent81784c32012-11-19 14:55:58 -08003207 }
3208 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003209 // Process effect chains for offloaded thread even if no audio
3210 // was read from audio track: process only updates effect state
3211 // and thus does have to be synchronized with audio writes but may have
3212 // to be called while waiting for async write callback
3213 if (mType == OFFLOAD) {
3214 for (size_t i = 0; i < effectChains.size(); i ++) {
3215 effectChains[i]->process_l();
3216 }
3217 }
Eric Laurent81784c32012-11-19 14:55:58 -08003218
Andy Hung98ef9782014-03-04 14:46:50 -08003219 // Only if the Effects buffer is enabled and there is data in the
3220 // Effects buffer (buffer valid), we need to
3221 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003222 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003223 if (mEffectBufferValid) {
3224 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003225
3226 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003227 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3228 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003229 }
3230
Andy Hung98ef9782014-03-04 14:46:50 -08003231 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3232 mNormalFrameCount * mChannelCount);
3233 }
3234
Eric Laurent81784c32012-11-19 14:55:58 -08003235 // enable changes in effect chain
3236 unlockEffectChains(effectChains);
3237
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003239 // mSleepTimeUs == 0 means we must write to audio hardware
3240 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003241 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003242 // We save lastWriteFinished here, as previousLastWriteFinished,
3243 // for throttling. On thread start, previousLastWriteFinished will be
3244 // set to -1, which properly results in no throttling after the first write.
3245 nsecs_t previousLastWriteFinished = lastWriteFinished;
3246 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003247 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003248 // FIXME rewrite to reduce number of system calls
3249 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003250 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003251 lastWriteFinished = systemTime();
3252 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003253 if (ret < 0) {
3254 mBytesRemaining = 0;
3255 } else {
3256 mBytesWritten += ret;
3257 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003258 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003259 }
3260 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3261 (mMixerStatus == MIXER_DRAIN_ALL)) {
3262 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003263 }
Andy Hung08fb1742015-05-31 23:22:10 -07003264 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003265 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003266 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003267 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003268 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003269 ATRACE_NAME("underrun");
3270 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003271 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003272 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003273 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003274 }
Andy Hung08fb1742015-05-31 23:22:10 -07003275
3276 if (mThreadThrottle
3277 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3278 && ret > 0) { // we wrote something
3279 // Limit MixerThread data processing to no more than twice the
3280 // expected processing rate.
3281 //
3282 // This helps prevent underruns with NuPlayer and other applications
3283 // which may set up buffers that are close to the minimum size, or use
3284 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3285 //
3286 // The throttle smooths out sudden large data drains from the device,
3287 // e.g. when it comes out of standby, which often causes problems with
3288 // (1) mixer threads without a fast mixer (which has its own warm-up)
3289 // (2) minimum buffer sized tracks (even if the track is full,
3290 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003291 //
3292 // Total time spent in last processing cycle equals time spent in
3293 // 1. threadLoop_write, as well as time spent in
3294 // 2. threadLoop_mix (significant for heavy mixing, especially
3295 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003296
Andy Hung69488c42016-05-16 18:43:33 -07003297 // it's OK if deltaMs is an overestimate.
3298 const int32_t deltaMs =
3299 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003300 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3301 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3302 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003303 // notify of throttle start on verbose log
3304 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3305 "mixer(%p) throttle begin:"
3306 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003307 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003308 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003309 // Throttle must be attributed to the previous mixer loop's write time
3310 // to allow back-to-back throttling.
3311 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003312 } else {
3313 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3314 if (diff > 0) {
3315 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003316 // but prevent spamming for bluetooth
3317 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3318 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003319 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3320 }
Andy Hung08fb1742015-05-31 23:22:10 -07003321 }
3322 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003323 }
Eric Laurent81784c32012-11-19 14:55:58 -08003324
Eric Laurentbfb1b832013-01-07 09:53:42 -08003325 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003326 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003327 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003328 // suspended requires accurate metering of sleep time.
3329 if (isSuspended()) {
3330 // advance by expected sleepTime
3331 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3332 const nsecs_t nowNs = systemTime();
3333
3334 // compute expected next time vs current time.
3335 // (negative deltas are treated as delays).
3336 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3337 if (deltaNs < -kMaxNextBufferDelayNs) {
3338 // Delays longer than the max allowed trigger a reset.
3339 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3340 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3341 timeLoopNextNs = nowNs + deltaNs;
3342 } else if (deltaNs < 0) {
3343 // Delays within the max delay allowed: zero the delta/sleepTime
3344 // to help the system catch up in the next iteration(s)
3345 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3346 deltaNs = 0;
3347 }
3348 // update sleep time (which is >= 0)
3349 mSleepTimeUs = deltaNs / 1000;
3350 }
Eric Laurente93cc032016-05-05 10:15:10 -07003351 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3352 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003353 }
Glenn Kastene7754022014-10-31 12:11:26 -07003354 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 }
Eric Laurent81784c32012-11-19 14:55:58 -08003356 }
3357
3358 // Finally let go of removed track(s), without the lock held
3359 // since we can't guarantee the destructors won't acquire that
3360 // same lock. This will also mutate and push a new fast mixer state.
3361 threadLoop_removeTracks(tracksToRemove);
3362 tracksToRemove.clear();
3363
3364 // FIXME I don't understand the need for this here;
3365 // it was in the original code but maybe the
3366 // assignment in saveOutputTracks() makes this unnecessary?
3367 clearOutputTracks();
3368
3369 // Effect chains will be actually deleted here if they were removed from
3370 // mEffectChains list during mixing or effects processing
3371 effectChains.clear();
3372
3373 // FIXME Note that the above .clear() is no longer necessary since effectChains
3374 // is now local to this block, but will keep it for now (at least until merge done).
3375 }
3376
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 threadLoop_exit();
3378
Eric Laurentcf817a22014-08-04 20:36:31 -07003379 if (!mStandby) {
3380 threadLoop_standby();
3381 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003382 }
3383
3384 releaseWakeLock();
3385
3386 ALOGV("Thread %p type %d exiting", this, mType);
3387 return false;
3388}
3389
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390// removeTracks_l() must be called with ThreadBase::mLock held
3391void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3392{
3393 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003394 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003395 for (size_t i=0 ; i<count ; i++) {
3396 const sp<Track>& track = tracksToRemove.itemAt(i);
3397 mActiveTracks.remove(track);
3398 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3399 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3400 if (chain != 0) {
3401 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3402 track->sessionId());
3403 chain->decActiveTrackCnt();
3404 }
3405 if (track->isTerminated()) {
3406 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003407 } else { // inactive but not terminated
3408 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07003409 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08003410 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411 }
3412 }
3413 }
3414
3415}
Eric Laurent81784c32012-11-19 14:55:58 -08003416
Eric Laurentaccc1472013-09-20 09:36:34 -07003417status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3418{
3419 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003420 ExtendedTimestamp ets;
3421 status_t status = mNormalSink->getTimestamp(ets);
3422 if (status == NO_ERROR) {
3423 status = ets.getBestTimestamp(&timestamp);
3424 }
3425 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003426 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003427 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003428 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003429 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003430 timestamp.mPosition = (uint32_t)position64;
3431 return NO_ERROR;
3432 }
3433 }
3434 return INVALID_OPERATION;
3435}
Eric Laurent1c333e22014-05-20 10:48:17 -07003436
Eric Laurent054d9d32015-04-24 08:48:48 -07003437status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3438 audio_patch_handle_t *handle)
3439{
Andy Hungf60abce2016-08-26 11:37:54 -07003440 status_t status;
3441 if (property_get_bool("af.patch_park", false /* default_value */)) {
3442 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3443 // or if HAL does not properly lock against access.
3444 AutoPark<FastMixer> park(mFastMixer);
3445 status = PlaybackThread::createAudioPatch_l(patch, handle);
3446 } else {
3447 status = PlaybackThread::createAudioPatch_l(patch, handle);
3448 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003449 return status;
3450}
3451
Eric Laurent1c333e22014-05-20 10:48:17 -07003452status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3453 audio_patch_handle_t *handle)
3454{
3455 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003456
3457 // store new device and send to effects
3458 audio_devices_t type = AUDIO_DEVICE_NONE;
3459 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3460 type |= patch->sinks[i].ext.device.type;
3461 }
3462
3463#ifdef ADD_BATTERY_DATA
3464 // when changing the audio output device, call addBatteryData to notify
3465 // the change
3466 if (mOutDevice != type) {
3467 uint32_t params = 0;
3468 // check whether speaker is on
3469 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3470 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003471 }
3472
Eric Laurent054d9d32015-04-24 08:48:48 -07003473 audio_devices_t deviceWithoutSpeaker
3474 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3475 // check if any other device (except speaker) is on
3476 if (type & deviceWithoutSpeaker) {
3477 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3478 }
3479
3480 if (params != 0) {
3481 addBatteryData(params);
3482 }
3483 }
3484#endif
3485
3486 for (size_t i = 0; i < mEffectChains.size(); i++) {
3487 mEffectChains[i]->setDevice_l(type);
3488 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003489
3490 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3491 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3492 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003493 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003494 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003495
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003496 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003497 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3498 status = hwDevice->createAudioPatch(patch->num_sources,
3499 patch->sources,
3500 patch->num_sinks,
3501 patch->sinks,
3502 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003503 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003504 char *address;
3505 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3506 //FIXME: we only support address on first sink with HAL version < 3.0
3507 address = audio_device_address_to_parameter(
3508 patch->sinks[0].ext.device.type,
3509 patch->sinks[0].ext.device.address);
3510 } else {
3511 address = (char *)calloc(1, 1);
3512 }
3513 AudioParameter param = AudioParameter(String8(address));
3514 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003515 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003516 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003517 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003518 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003519 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003520 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003521 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3522 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003523 return status;
3524}
3525
Eric Laurent054d9d32015-04-24 08:48:48 -07003526status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3527{
Andy Hungf60abce2016-08-26 11:37:54 -07003528 status_t status;
3529 if (property_get_bool("af.patch_park", false /* default_value */)) {
3530 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3531 // or if HAL does not properly lock against access.
3532 AutoPark<FastMixer> park(mFastMixer);
3533 status = PlaybackThread::releaseAudioPatch_l(handle);
3534 } else {
3535 status = PlaybackThread::releaseAudioPatch_l(handle);
3536 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003537 return status;
3538}
3539
Eric Laurent1c333e22014-05-20 10:48:17 -07003540status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3541{
3542 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003543
3544 mOutDevice = AUDIO_DEVICE_NONE;
3545
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003546 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003547 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3548 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003549 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003550 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003551 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003552 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003553 }
3554 return status;
3555}
3556
Eric Laurent83b88082014-06-20 18:31:16 -07003557void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3558{
3559 Mutex::Autolock _l(mLock);
3560 mTracks.add(track);
3561}
3562
3563void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3564{
3565 Mutex::Autolock _l(mLock);
3566 destroyTrack_l(track);
3567}
3568
3569void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3570{
3571 ThreadBase::getAudioPortConfig(config);
3572 config->role = AUDIO_PORT_ROLE_SOURCE;
3573 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3574 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3575}
3576
Eric Laurent81784c32012-11-19 14:55:58 -08003577// ----------------------------------------------------------------------------
3578
3579AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003580 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3581 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003582 // mAudioMixer below
3583 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003584 mFastMixerFutex(0),
3585 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003586 // mOutputSink below
3587 // mPipeSink below
3588 // mNormalSink below
3589{
3590 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003591 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3592 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003593 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3594 mNormalFrameCount);
3595 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3596
Andy Hungfbfc3952015-01-15 13:33:51 -08003597 if (type == DUPLICATING) {
3598 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3599 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3600 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3601 return;
3602 }
Eric Laurent81784c32012-11-19 14:55:58 -08003603 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003604 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003605 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003606 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003607#if !LOG_NDEBUG
3608 ssize_t index =
3609#else
3610 (void)
3611#endif
3612 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003613 ALOG_ASSERT(index == 0);
3614
3615 // initialize fast mixer depending on configuration
3616 bool initFastMixer;
3617 switch (kUseFastMixer) {
3618 case FastMixer_Never:
3619 initFastMixer = false;
3620 break;
3621 case FastMixer_Always:
3622 initFastMixer = true;
3623 break;
3624 case FastMixer_Static:
3625 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003626 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3627 // where the period is less than an experimentally determined threshold that can be
3628 // scheduled reliably with CFS. However, the BT A2DP HAL is
3629 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3630 initFastMixer = mFrameCount < mNormalFrameCount
3631 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003632 break;
3633 }
Andy Hungfda69402017-02-15 14:33:12 -08003634 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3635 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3636 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003637 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003638 audio_format_t fastMixerFormat;
3639 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3640 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3641 } else {
3642 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3643 }
3644 if (mFormat != fastMixerFormat) {
3645 // change our Sink format to accept our intermediate precision
3646 mFormat = fastMixerFormat;
3647 free(mSinkBuffer);
3648 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3649 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3650 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3651 }
Eric Laurent81784c32012-11-19 14:55:58 -08003652
3653 // create a MonoPipe to connect our submix to FastMixer
3654 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003655#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003656 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003657#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003658 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003659 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003660 format.mFormat = fastMixerFormat;
3661 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3662
Eric Laurent81784c32012-11-19 14:55:58 -08003663 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3664 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3665 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3666 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3667 const NBAIO_Format offers[1] = {format};
3668 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003669#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003670 ssize_t index =
3671#else
3672 (void)
3673#endif
3674 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003675 ALOG_ASSERT(index == 0);
3676 monoPipe->setAvgFrames((mScreenState & 1) ?
3677 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3678 mPipeSink = monoPipe;
3679
Glenn Kasten46909e72013-02-26 09:20:22 -08003680#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003681 if (mTeeSinkOutputEnabled) {
3682 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003683 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3684 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003685 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003686 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003687 ALOG_ASSERT(index == 0);
3688 mTeeSink = teeSink;
3689 PipeReader *teeSource = new PipeReader(*teeSink);
3690 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003691 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003692 ALOG_ASSERT(index == 0);
3693 mTeeSource = teeSource;
3694 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003695#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003696
3697 // create fast mixer and configure it initially with just one fast track for our submix
3698 mFastMixer = new FastMixer();
3699 FastMixerStateQueue *sq = mFastMixer->sq();
3700#ifdef STATE_QUEUE_DUMP
3701 sq->setObserverDump(&mStateQueueObserverDump);
3702 sq->setMutatorDump(&mStateQueueMutatorDump);
3703#endif
3704 FastMixerState *state = sq->begin();
3705 FastTrack *fastTrack = &state->mFastTracks[0];
3706 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3707 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3708 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003709 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3710 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003711 fastTrack->mGeneration++;
3712 state->mFastTracksGen++;
3713 state->mTrackMask = 1;
3714 // fast mixer will use the HAL output sink
3715 state->mOutputSink = mOutputSink.get();
3716 state->mOutputSinkGen++;
3717 state->mFrameCount = mFrameCount;
3718 state->mCommand = FastMixerState::COLD_IDLE;
3719 // already done in constructor initialization list
3720 //mFastMixerFutex = 0;
3721 state->mColdFutexAddr = &mFastMixerFutex;
3722 state->mColdGen++;
3723 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003724#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003725 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003726#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003727 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3728 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003729 sq->end();
3730 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3731
3732 // start the fast mixer
3733 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3734 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003735 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003736 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003737
3738#ifdef AUDIO_WATCHDOG
3739 // create and start the watchdog
3740 mAudioWatchdog = new AudioWatchdog();
3741 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3742 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3743 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003744 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003745#endif
3746
Eric Laurent81784c32012-11-19 14:55:58 -08003747 }
3748
3749 switch (kUseFastMixer) {
3750 case FastMixer_Never:
3751 case FastMixer_Dynamic:
3752 mNormalSink = mOutputSink;
3753 break;
3754 case FastMixer_Always:
3755 mNormalSink = mPipeSink;
3756 break;
3757 case FastMixer_Static:
3758 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3759 break;
3760 }
3761}
3762
3763AudioFlinger::MixerThread::~MixerThread()
3764{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003765 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003766 FastMixerStateQueue *sq = mFastMixer->sq();
3767 FastMixerState *state = sq->begin();
3768 if (state->mCommand == FastMixerState::COLD_IDLE) {
3769 int32_t old = android_atomic_inc(&mFastMixerFutex);
3770 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003771 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003772 }
3773 }
3774 state->mCommand = FastMixerState::EXIT;
3775 sq->end();
3776 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3777 mFastMixer->join();
3778 // Though the fast mixer thread has exited, it's state queue is still valid.
3779 // We'll use that extract the final state which contains one remaining fast track
3780 // corresponding to our sub-mix.
3781 state = sq->begin();
3782 ALOG_ASSERT(state->mTrackMask == 1);
3783 FastTrack *fastTrack = &state->mFastTracks[0];
3784 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3785 delete fastTrack->mBufferProvider;
3786 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003787 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003788#ifdef AUDIO_WATCHDOG
3789 if (mAudioWatchdog != 0) {
3790 mAudioWatchdog->requestExit();
3791 mAudioWatchdog->requestExitAndWait();
3792 mAudioWatchdog.clear();
3793 }
3794#endif
3795 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003796 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003797 delete mAudioMixer;
3798}
3799
3800
3801uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3802{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003803 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003804 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3805 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3806 }
3807 return latency;
3808}
3809
3810
3811void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3812{
3813 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3814}
3815
Eric Laurentbfb1b832013-01-07 09:53:42 -08003816ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003817{
3818 // FIXME we should only do one push per cycle; confirm this is true
3819 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003820 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003821 FastMixerStateQueue *sq = mFastMixer->sq();
3822 FastMixerState *state = sq->begin();
3823 if (state->mCommand != FastMixerState::MIX_WRITE &&
3824 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3825 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003826
3827 // FIXME workaround for first HAL write being CPU bound on some devices
3828 ATRACE_BEGIN("write");
3829 mOutput->write((char *)mSinkBuffer, 0);
3830 ATRACE_END();
3831
Eric Laurent81784c32012-11-19 14:55:58 -08003832 int32_t old = android_atomic_inc(&mFastMixerFutex);
3833 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003834 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003835 }
3836#ifdef AUDIO_WATCHDOG
3837 if (mAudioWatchdog != 0) {
3838 mAudioWatchdog->resume();
3839 }
3840#endif
3841 }
3842 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003843#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003844 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003845 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003846#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003847 sq->end();
3848 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3849 if (kUseFastMixer == FastMixer_Dynamic) {
3850 mNormalSink = mPipeSink;
3851 }
3852 } else {
3853 sq->end(false /*didModify*/);
3854 }
3855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003856 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003857}
3858
3859void AudioFlinger::MixerThread::threadLoop_standby()
3860{
3861 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003862 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003863 FastMixerStateQueue *sq = mFastMixer->sq();
3864 FastMixerState *state = sq->begin();
3865 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003866 // Report any frames trapped in the Monopipe
3867 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3868 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3869 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3870 "monoPipeWritten:%lld monoPipeLeft:%lld",
3871 (long long)mFramesWritten, (long long)mSuspendedFrames,
3872 (long long)mPipeSink->framesWritten(), pipeFrames);
3873 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3874
Eric Laurent81784c32012-11-19 14:55:58 -08003875 state->mCommand = FastMixerState::COLD_IDLE;
3876 state->mColdFutexAddr = &mFastMixerFutex;
3877 state->mColdGen++;
3878 mFastMixerFutex = 0;
3879 sq->end();
3880 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3881 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3882 if (kUseFastMixer == FastMixer_Dynamic) {
3883 mNormalSink = mOutputSink;
3884 }
3885#ifdef AUDIO_WATCHDOG
3886 if (mAudioWatchdog != 0) {
3887 mAudioWatchdog->pause();
3888 }
3889#endif
3890 } else {
3891 sq->end(false /*didModify*/);
3892 }
3893 }
3894 PlaybackThread::threadLoop_standby();
3895}
3896
Eric Laurentbfb1b832013-01-07 09:53:42 -08003897bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3898{
3899 return false;
3900}
3901
3902bool AudioFlinger::PlaybackThread::shouldStandby_l()
3903{
3904 return !mStandby;
3905}
3906
3907bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3908{
3909 Mutex::Autolock _l(mLock);
3910 return waitingAsyncCallback_l();
3911}
3912
Eric Laurent81784c32012-11-19 14:55:58 -08003913// shared by MIXER and DIRECT, overridden by DUPLICATING
3914void AudioFlinger::PlaybackThread::threadLoop_standby()
3915{
3916 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003917 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003918 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003919 // discard any pending drain or write ack by incrementing sequence
3920 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3921 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003922 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003923 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3924 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003926 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003927}
3928
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003929void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3930{
3931 ALOGV("signal playback thread");
3932 broadcast_l();
3933}
3934
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003935void AudioFlinger::PlaybackThread::onAsyncError()
3936{
3937 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3938 invalidateTracks((audio_stream_type_t)i);
3939 }
3940}
3941
Eric Laurent81784c32012-11-19 14:55:58 -08003942void AudioFlinger::MixerThread::threadLoop_mix()
3943{
Eric Laurent81784c32012-11-19 14:55:58 -08003944 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003945 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003946 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003947 // increase sleep time progressively when application underrun condition clears.
3948 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3949 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3950 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003951 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003952 sleepTimeShift--;
3953 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003954 mSleepTimeUs = 0;
3955 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003956 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003957
Eric Laurent81784c32012-11-19 14:55:58 -08003958}
3959
3960void AudioFlinger::MixerThread::threadLoop_sleepTime()
3961{
3962 // If no tracks are ready, sleep once for the duration of an output
3963 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003964 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003965 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3967 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3968 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003969 }
3970 // reduce sleep time in case of consecutive application underruns to avoid
3971 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3972 // duration we would end up writing less data than needed by the audio HAL if
3973 // the condition persists.
3974 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3975 sleepTimeShift++;
3976 }
3977 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003978 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003979 }
3980 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003981 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3982 // before effects processing or output.
3983 if (mMixerBufferValid) {
3984 memset(mMixerBuffer, 0, mMixerBufferSize);
3985 } else {
3986 memset(mSinkBuffer, 0, mSinkBufferSize);
3987 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003988 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003989 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3990 "anticipated start");
3991 }
3992 // TODO add standby time extension fct of effect tail
3993}
3994
3995// prepareTracks_l() must be called with ThreadBase::mLock held
3996AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
3997 Vector< sp<Track> > *tracksToRemove)
3998{
3999
4000 mixer_state mixerStatus = MIXER_IDLE;
4001 // find out which tracks need to be processed
4002 size_t count = mActiveTracks.size();
4003 size_t mixedTracks = 0;
4004 size_t tracksWithEffect = 0;
4005 // counts only _active_ fast tracks
4006 size_t fastTracks = 0;
4007 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4008
4009 float masterVolume = mMasterVolume;
4010 bool masterMute = mMasterMute;
4011
4012 if (masterMute) {
4013 masterVolume = 0;
4014 }
4015 // Delegate master volume control to effect in output mix effect chain if needed
4016 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4017 if (chain != 0) {
4018 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4019 chain->setVolume_l(&v, &v);
4020 masterVolume = (float)((v + (1 << 23)) >> 24);
4021 chain.clear();
4022 }
4023
4024 // prepare a new state to push
4025 FastMixerStateQueue *sq = NULL;
4026 FastMixerState *state = NULL;
4027 bool didModify = false;
4028 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004029 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004030 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004031 sq = mFastMixer->sq();
4032 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004033 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004034 }
4035
Andy Hung69aed5f2014-02-25 17:24:40 -08004036 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004037 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004038
Eric Laurent81784c32012-11-19 14:55:58 -08004039 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004040 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004041
4042 // this const just means the local variable doesn't change
4043 Track* const track = t.get();
4044
4045 // process fast tracks
4046 if (track->isFastTrack()) {
4047
4048 // It's theoretically possible (though unlikely) for a fast track to be created
4049 // and then removed within the same normal mix cycle. This is not a problem, as
4050 // the track never becomes active so it's fast mixer slot is never touched.
4051 // The converse, of removing an (active) track and then creating a new track
4052 // at the identical fast mixer slot within the same normal mix cycle,
4053 // is impossible because the slot isn't marked available until the end of each cycle.
4054 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004055 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004056 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4057 FastTrack *fastTrack = &state->mFastTracks[j];
4058
4059 // Determine whether the track is currently in underrun condition,
4060 // and whether it had a recent underrun.
4061 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4062 FastTrackUnderruns underruns = ftDump->mUnderruns;
4063 uint32_t recentFull = (underruns.mBitFields.mFull -
4064 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4065 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4066 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4067 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4068 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4069 uint32_t recentUnderruns = recentPartial + recentEmpty;
4070 track->mObservedUnderruns = underruns;
4071 // don't count underruns that occur while stopping or pausing
4072 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004073 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4074 recentUnderruns > 0) {
4075 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4076 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004077 } else {
4078 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004079 }
4080
4081 // This is similar to the state machine for normal tracks,
4082 // with a few modifications for fast tracks.
4083 bool isActive = true;
4084 switch (track->mState) {
4085 case TrackBase::STOPPING_1:
4086 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004087 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004088 track->mState = TrackBase::STOPPING_2;
4089 }
4090 break;
4091 case TrackBase::PAUSING:
4092 // ramp down is not yet implemented
4093 track->setPaused();
4094 break;
4095 case TrackBase::RESUMING:
4096 // ramp up is not yet implemented
4097 track->mState = TrackBase::ACTIVE;
4098 break;
4099 case TrackBase::ACTIVE:
4100 if (recentFull > 0 || recentPartial > 0) {
4101 // track has provided at least some frames recently: reset retry count
4102 track->mRetryCount = kMaxTrackRetries;
4103 }
4104 if (recentUnderruns == 0) {
4105 // no recent underruns: stay active
4106 break;
4107 }
4108 // there has recently been an underrun of some kind
4109 if (track->sharedBuffer() == 0) {
4110 // were any of the recent underruns "empty" (no frames available)?
4111 if (recentEmpty == 0) {
4112 // no, then ignore the partial underruns as they are allowed indefinitely
4113 break;
4114 }
4115 // there has recently been an "empty" underrun: decrement the retry counter
4116 if (--(track->mRetryCount) > 0) {
4117 break;
4118 }
4119 // indicate to client process that the track was disabled because of underrun;
4120 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004121 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004122 // remove from active list, but state remains ACTIVE [confusing but true]
4123 isActive = false;
4124 break;
4125 }
4126 // fall through
4127 case TrackBase::STOPPING_2:
4128 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004129 case TrackBase::STOPPED:
4130 case TrackBase::FLUSHED: // flush() while active
4131 // Check for presentation complete if track is inactive
4132 // We have consumed all the buffers of this track.
4133 // This would be incomplete if we auto-paused on underrun
4134 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004135 uint32_t latency = 0;
4136 status_t result = mOutput->stream->getLatency(&latency);
4137 ALOGE_IF(result != OK,
4138 "Error when retrieving output stream latency: %d", result);
4139 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004140 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004141 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4142 // track stays in active list until presentation is complete
4143 break;
4144 }
4145 }
4146 if (track->isStopping_2()) {
4147 track->mState = TrackBase::STOPPED;
4148 }
4149 if (track->isStopped()) {
4150 // Can't reset directly, as fast mixer is still polling this track
4151 // track->reset();
4152 // So instead mark this track as needing to be reset after push with ack
4153 resetMask |= 1 << i;
4154 }
4155 isActive = false;
4156 break;
4157 case TrackBase::IDLE:
4158 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004159 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004160 }
4161
4162 if (isActive) {
4163 // was it previously inactive?
4164 if (!(state->mTrackMask & (1 << j))) {
4165 ExtendedAudioBufferProvider *eabp = track;
4166 VolumeProvider *vp = track;
4167 fastTrack->mBufferProvider = eabp;
4168 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004169 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004170 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004171 fastTrack->mGeneration++;
4172 state->mTrackMask |= 1 << j;
4173 didModify = true;
4174 // no acknowledgement required for newly active tracks
4175 }
4176 // cache the combined master volume and stream type volume for fast mixer; this
4177 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004178 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004179 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004180 track->mCachedVolume = masterVolume
4181 * mStreamTypes[track->streamType()].volume
4182 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004183 ++fastTracks;
4184 } else {
4185 // was it previously active?
4186 if (state->mTrackMask & (1 << j)) {
4187 fastTrack->mBufferProvider = NULL;
4188 fastTrack->mGeneration++;
4189 state->mTrackMask &= ~(1 << j);
4190 didModify = true;
4191 // If any fast tracks were removed, we must wait for acknowledgement
4192 // because we're about to decrement the last sp<> on those tracks.
4193 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4194 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004195 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4196 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4197 j, track->mState, state->mTrackMask, recentUnderruns,
4198 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004199 }
4200 tracksToRemove->add(track);
4201 // Avoids a misleading display in dumpsys
4202 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4203 }
4204 continue;
4205 }
4206
4207 { // local variable scope to avoid goto warning
4208
4209 audio_track_cblk_t* cblk = track->cblk();
4210
4211 // The first time a track is added we wait
4212 // for all its buffers to be filled before processing it
4213 int name = track->name();
4214 // make sure that we have enough frames to mix one full buffer.
4215 // enforce this condition only once to enable draining the buffer in case the client
4216 // app does not call stop() and relies on underrun to stop:
4217 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4218 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004219 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004220 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004221 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004222
4223 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004224 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004225 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4226 // add frames already consumed but not yet released by the resampler
4227 // because mAudioTrackServerProxy->framesReady() will include these frames
4228 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4229
Eric Laurent81784c32012-11-19 14:55:58 -08004230 uint32_t minFrames = 1;
4231 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4232 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004233 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004234 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004235
4236 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004237 if (ATRACE_ENABLED()) {
4238 // I wish we had formatted trace names
4239 char traceName[16];
4240 strcpy(traceName, "nRdy");
4241 int name = track->name();
4242 if (AudioMixer::TRACK0 <= name &&
4243 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4244 name -= AudioMixer::TRACK0;
4245 traceName[4] = (name / 10) + '0';
4246 traceName[5] = (name % 10) + '0';
4247 } else {
4248 traceName[4] = '?';
4249 traceName[5] = '?';
4250 }
4251 traceName[6] = '\0';
4252 ATRACE_INT(traceName, framesReady);
4253 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004254 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004255 !track->isPaused() && !track->isTerminated())
4256 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004257 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004258
4259 mixedTracks++;
4260
Andy Hung69aed5f2014-02-25 17:24:40 -08004261 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4262 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004263 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004264 if (track->mainBuffer() != mSinkBuffer &&
4265 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004266 if (mEffectBufferEnabled) {
4267 mEffectBufferValid = true; // Later can set directly.
4268 }
Eric Laurent81784c32012-11-19 14:55:58 -08004269 chain = getEffectChain_l(track->sessionId());
4270 // Delegate volume control to effect in track effect chain if needed
4271 if (chain != 0) {
4272 tracksWithEffect++;
4273 } else {
4274 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4275 "session %d",
4276 name, track->sessionId());
4277 }
4278 }
4279
4280
4281 int param = AudioMixer::VOLUME;
4282 if (track->mFillingUpStatus == Track::FS_FILLED) {
4283 // no ramp for the first volume setting
4284 track->mFillingUpStatus = Track::FS_ACTIVE;
4285 if (track->mState == TrackBase::RESUMING) {
4286 track->mState = TrackBase::ACTIVE;
4287 param = AudioMixer::RAMP_VOLUME;
4288 }
4289 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004290 // FIXME should not make a decision based on mServer
4291 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004292 // If the track is stopped before the first frame was mixed,
4293 // do not apply ramp
4294 param = AudioMixer::RAMP_VOLUME;
4295 }
4296
4297 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004298 uint32_t vl, vr; // in U8.24 integer format
4299 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004300 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004301 vl = vr = 0;
4302 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004303 if (track->isPausing()) {
4304 track->setPaused();
4305 }
4306 } else {
4307
4308 // read original volumes with volume control
4309 float typeVolume = mStreamTypes[track->streamType()].volume;
4310 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004311 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004312 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004313 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4314 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004315 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004316 if (vlf > GAIN_FLOAT_UNITY) {
4317 ALOGV("Track left volume out of range: %.3g", vlf);
4318 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004319 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004320 if (vrf > GAIN_FLOAT_UNITY) {
4321 ALOGV("Track right volume out of range: %.3g", vrf);
4322 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004323 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004324 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004325 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004326 // now apply the master volume and stream type volume and shaper volume
4327 vlf *= v * vh;
4328 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004329 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004330 // then derive vl and vr as U8.24 versions for the effect chain
4331 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4332 vl = (uint32_t) (scaleto8_24 * vlf);
4333 vr = (uint32_t) (scaleto8_24 * vrf);
4334 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004335 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004336 // send level comes from shared memory and so may be corrupt
4337 if (sendLevel > MAX_GAIN_INT) {
4338 ALOGV("Track send level out of range: %04X", sendLevel);
4339 sendLevel = MAX_GAIN_INT;
4340 }
Andy Hung6be49402014-05-30 10:42:03 -07004341 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4342 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004343 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004344
Eric Laurent81784c32012-11-19 14:55:58 -08004345 // Delegate volume control to effect in track effect chain if needed
4346 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4347 // Do not ramp volume if volume is controlled by effect
4348 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004349 // Update remaining floating point volume levels
4350 vlf = (float)vl / (1 << 24);
4351 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004352 track->mHasVolumeController = true;
4353 } else {
4354 // force no volume ramp when volume controller was just disabled or removed
4355 // from effect chain to avoid volume spike
4356 if (track->mHasVolumeController) {
4357 param = AudioMixer::VOLUME;
4358 }
4359 track->mHasVolumeController = false;
4360 }
4361
Eric Laurent81784c32012-11-19 14:55:58 -08004362 // XXX: these things DON'T need to be done each time
4363 mAudioMixer->setBufferProvider(name, track);
4364 mAudioMixer->enable(name);
4365
Andy Hung6be49402014-05-30 10:42:03 -07004366 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4367 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4368 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004369 mAudioMixer->setParameter(
4370 name,
4371 AudioMixer::TRACK,
4372 AudioMixer::FORMAT, (void *)track->format());
4373 mAudioMixer->setParameter(
4374 name,
4375 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004376 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004377 mAudioMixer->setParameter(
4378 name,
4379 AudioMixer::TRACK,
4380 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004381 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004382 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004383 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004384 if (reqSampleRate == 0) {
4385 reqSampleRate = mSampleRate;
4386 } else if (reqSampleRate > maxSampleRate) {
4387 reqSampleRate = maxSampleRate;
4388 }
Eric Laurent81784c32012-11-19 14:55:58 -08004389 mAudioMixer->setParameter(
4390 name,
4391 AudioMixer::RESAMPLE,
4392 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004393 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004394
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004395 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004396 mAudioMixer->setParameter(
4397 name,
4398 AudioMixer::TIMESTRETCH,
4399 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004400 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004401
Andy Hung69aed5f2014-02-25 17:24:40 -08004402 /*
4403 * Select the appropriate output buffer for the track.
4404 *
Andy Hung98ef9782014-03-04 14:46:50 -08004405 * Tracks with effects go into their own effects chain buffer
4406 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004407 *
4408 * Other tracks can use mMixerBuffer for higher precision
4409 * channel accumulation. If this buffer is enabled
4410 * (mMixerBufferEnabled true), then selected tracks will accumulate
4411 * into it.
4412 *
4413 */
4414 if (mMixerBufferEnabled
4415 && (track->mainBuffer() == mSinkBuffer
4416 || track->mainBuffer() == mMixerBuffer)) {
4417 mAudioMixer->setParameter(
4418 name,
4419 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004420 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004421 mAudioMixer->setParameter(
4422 name,
4423 AudioMixer::TRACK,
4424 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4425 // TODO: override track->mainBuffer()?
4426 mMixerBufferValid = true;
4427 } else {
4428 mAudioMixer->setParameter(
4429 name,
4430 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004431 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004432 mAudioMixer->setParameter(
4433 name,
4434 AudioMixer::TRACK,
4435 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4436 }
Eric Laurent81784c32012-11-19 14:55:58 -08004437 mAudioMixer->setParameter(
4438 name,
4439 AudioMixer::TRACK,
4440 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4441
4442 // reset retry count
4443 track->mRetryCount = kMaxTrackRetries;
4444
4445 // If one track is ready, set the mixer ready if:
4446 // - the mixer was not ready during previous round OR
4447 // - no other track is not ready
4448 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4449 mixerStatus != MIXER_TRACKS_ENABLED) {
4450 mixerStatus = MIXER_TRACKS_READY;
4451 }
4452 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004453 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004454 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4455 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004456 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004457 } else {
4458 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004459 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004460
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // clear effect chain input buffer if an active track underruns to avoid sending
4462 // previous audio buffer again to effects
4463 chain = getEffectChain_l(track->sessionId());
4464 if (chain != 0) {
4465 chain->clearInputBuffer();
4466 }
4467
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004468 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004469 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4470 track->isStopped() || track->isPaused()) {
4471 // We have consumed all the buffers of this track.
4472 // Remove it from the list of active tracks.
4473 // TODO: use actual buffer filling status instead of latency when available from
4474 // audio HAL
4475 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004476 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004477 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4478 if (track->isStopped()) {
4479 track->reset();
4480 }
4481 tracksToRemove->add(track);
4482 }
4483 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004484 // No buffers for this track. Give it a few chances to
4485 // fill a buffer, then remove it from active list.
4486 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004487 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004488 tracksToRemove->add(track);
4489 // indicate to client process that the track was disabled because of underrun;
4490 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004491 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004492 // If one track is not ready, mark the mixer also not ready if:
4493 // - the mixer was ready during previous round OR
4494 // - no other track is ready
4495 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4496 mixerStatus != MIXER_TRACKS_READY) {
4497 mixerStatus = MIXER_TRACKS_ENABLED;
4498 }
4499 }
4500 mAudioMixer->disable(name);
4501 }
4502
4503 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004504
4505 }
4506
4507 // Push the new FastMixer state if necessary
4508 bool pauseAudioWatchdog = false;
4509 if (didModify) {
4510 state->mFastTracksGen++;
4511 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4512 if (kUseFastMixer == FastMixer_Dynamic &&
4513 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4514 state->mCommand = FastMixerState::COLD_IDLE;
4515 state->mColdFutexAddr = &mFastMixerFutex;
4516 state->mColdGen++;
4517 mFastMixerFutex = 0;
4518 if (kUseFastMixer == FastMixer_Dynamic) {
4519 mNormalSink = mOutputSink;
4520 }
4521 // If we go into cold idle, need to wait for acknowledgement
4522 // so that fast mixer stops doing I/O.
4523 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4524 pauseAudioWatchdog = true;
4525 }
Eric Laurent81784c32012-11-19 14:55:58 -08004526 }
4527 if (sq != NULL) {
4528 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004529 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4530 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4531 // when bringing the output sink into standby.)
4532 //
4533 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4534 //
4535 // This occurs with BT suspend when we idle the FastMixer with
4536 // active tracks, which may be added or removed.
4537 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004538 }
4539#ifdef AUDIO_WATCHDOG
4540 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4541 mAudioWatchdog->pause();
4542 }
4543#endif
4544
4545 // Now perform the deferred reset on fast tracks that have stopped
4546 while (resetMask != 0) {
4547 size_t i = __builtin_ctz(resetMask);
4548 ALOG_ASSERT(i < count);
4549 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004550 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004551 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4552 track->reset();
4553 }
4554
4555 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004556 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004557
Eric Laurent97d547d2014-09-02 14:45:53 -07004558 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4559 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004560 }
4561
4562 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004563 // as long as there are effects we should clear the effects buffer, to avoid
4564 // passing a non-clean buffer to the effect chain
4565 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004566 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004567 // sink or mix buffer must be cleared if all tracks are connected to an
4568 // effect chain as in this case the mixer will not write to the sink or mix buffer
4569 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004570 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4571 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004572 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004573 if (mMixerBufferValid) {
4574 memset(mMixerBuffer, 0, mMixerBufferSize);
4575 // TODO: In testing, mSinkBuffer below need not be cleared because
4576 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4577 // after mixing.
4578 //
4579 // To enforce this guarantee:
4580 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4581 // (mixedTracks == 0 && fastTracks > 0))
4582 // must imply MIXER_TRACKS_READY.
4583 // Later, we may clear buffers regardless, and skip much of this logic.
4584 }
Andy Hung98ef9782014-03-04 14:46:50 -08004585 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004586 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004587 }
4588
4589 // if any fast tracks, then status is ready
4590 mMixerStatusIgnoringFastTracks = mixerStatus;
4591 if (fastTracks > 0) {
4592 mixerStatus = MIXER_TRACKS_READY;
4593 }
4594 return mixerStatus;
4595}
4596
Eric Laurentad7dd962016-09-22 12:38:37 -07004597// trackCountForUid_l() must be called with ThreadBase::mLock held
4598uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4599{
4600 uint32_t trackCount = 0;
4601 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004602 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004603 trackCount++;
4604 }
4605 }
4606 return trackCount;
4607}
4608
Eric Laurent81784c32012-11-19 14:55:58 -08004609// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004610int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004611 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004612{
Eric Laurentad7dd962016-09-22 12:38:37 -07004613 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4614 return -1;
4615 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004616 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004617}
4618
4619// deleteTrackName_l() must be called with ThreadBase::mLock held
4620void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4621{
4622 ALOGV("remove track (%d) and delete from mixer", name);
4623 mAudioMixer->deleteTrackName(name);
4624}
4625
Eric Laurent10351942014-05-08 18:49:52 -07004626// checkForNewParameter_l() must be called with ThreadBase::mLock held
4627bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4628 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004629{
Eric Laurent81784c32012-11-19 14:55:58 -08004630 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004631 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004632
Eric Laurent10351942014-05-08 18:49:52 -07004633 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004634
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004635 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004636
Eric Laurent10351942014-05-08 18:49:52 -07004637 AudioParameter param = AudioParameter(keyValuePair);
4638 int value;
4639 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4640 reconfig = true;
4641 }
4642 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004643 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004644 status = BAD_VALUE;
4645 } else {
4646 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004647 reconfig = true;
4648 }
Eric Laurent10351942014-05-08 18:49:52 -07004649 }
4650 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004651 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004652 status = BAD_VALUE;
4653 } else {
4654 // no need to save value, since it's constant
4655 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004656 }
Eric Laurent10351942014-05-08 18:49:52 -07004657 }
4658 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4659 // do not accept frame count changes if tracks are open as the track buffer
4660 // size depends on frame count and correct behavior would not be guaranteed
4661 // if frame count is changed after track creation
4662 if (!mTracks.isEmpty()) {
4663 status = INVALID_OPERATION;
4664 } else {
4665 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004666 }
Eric Laurent10351942014-05-08 18:49:52 -07004667 }
4668 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004669#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004670 // when changing the audio output device, call addBatteryData to notify
4671 // the change
4672 if (mOutDevice != value) {
4673 uint32_t params = 0;
4674 // check whether speaker is on
4675 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4676 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004677 }
Eric Laurent10351942014-05-08 18:49:52 -07004678
4679 audio_devices_t deviceWithoutSpeaker
4680 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4681 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004682 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004683 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4684 }
4685
4686 if (params != 0) {
4687 addBatteryData(params);
4688 }
4689 }
Eric Laurent81784c32012-11-19 14:55:58 -08004690#endif
4691
Eric Laurent10351942014-05-08 18:49:52 -07004692 // forward device change to effects that have requested to be
4693 // aware of attached audio device.
4694 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004695 a2dpDeviceChanged =
4696 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004697 mOutDevice = value;
4698 for (size_t i = 0; i < mEffectChains.size(); i++) {
4699 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004700 }
4701 }
Eric Laurent10351942014-05-08 18:49:52 -07004702 }
Eric Laurent81784c32012-11-19 14:55:58 -08004703
Eric Laurent10351942014-05-08 18:49:52 -07004704 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004705 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004706 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004707 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004708 mStandby = true;
4709 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004710 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004711 }
Eric Laurent10351942014-05-08 18:49:52 -07004712 if (status == NO_ERROR && reconfig) {
4713 readOutputParameters_l();
4714 delete mAudioMixer;
4715 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4716 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004717 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004718 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004719 if (name < 0) {
4720 break;
4721 }
4722 mTracks[i]->mName = name;
4723 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004724 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004725 }
Eric Laurent81784c32012-11-19 14:55:58 -08004726 }
4727
Eric Laurent42537be2016-01-08 17:16:42 -08004728 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004729}
4730
4731
4732void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4733{
Eric Laurent81784c32012-11-19 14:55:58 -08004734 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004735 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004736 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004737 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004738
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004739 if (hasFastMixer()) {
4740 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4741
4742 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4743 // while we are dumping it. It may be inconsistent, but it won't mutate!
4744 // This is a large object so we place it on the heap.
4745 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4746 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4747 copy->dump(fd);
4748 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004749
4750#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004751 // Similar for state queue
4752 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4753 observerCopy.dump(fd);
4754 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4755 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004756#endif
4757
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004758#ifdef AUDIO_WATCHDOG
4759 if (mAudioWatchdog != 0) {
4760 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4761 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4762 wdCopy.dump(fd);
4763 }
4764#endif
4765
4766 } else {
4767 dprintf(fd, " No FastMixer\n");
4768 }
4769
Glenn Kasten46909e72013-02-26 09:20:22 -08004770#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004771 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004772 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004773#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004774
Eric Laurent81784c32012-11-19 14:55:58 -08004775}
4776
4777uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4778{
4779 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4780}
4781
4782uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4783{
4784 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4785}
4786
4787void AudioFlinger::MixerThread::cacheParameters_l()
4788{
4789 PlaybackThread::cacheParameters_l();
4790
4791 // FIXME: Relaxed timing because of a certain device that can't meet latency
4792 // Should be reduced to 2x after the vendor fixes the driver issue
4793 // increase threshold again due to low power audio mode. The way this warning
4794 // threshold is calculated and its usefulness should be reconsidered anyway.
4795 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4796}
4797
4798// ----------------------------------------------------------------------------
4799
4800AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004801 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4802 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004803 // mLeftVolFloat, mRightVolFloat
4804{
4805}
4806
Eric Laurentbfb1b832013-01-07 09:53:42 -08004807AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4808 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004809 ThreadBase::type_t type, bool systemReady)
4810 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004811 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004812 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004813{
4814}
4815
Eric Laurent81784c32012-11-19 14:55:58 -08004816AudioFlinger::DirectOutputThread::~DirectOutputThread()
4817{
4818}
4819
Eric Laurent5850c4c2016-11-10 13:04:31 -08004820void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004821{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004822 float left, right;
4823
4824 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4825 left = right = 0;
4826 } else {
4827 float typeVolume = mStreamTypes[track->streamType()].volume;
4828 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004829 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004830
Andy Hung10cbff12017-02-21 17:30:14 -08004831 // Get volumeshaper scaling
4832 std::pair<float /* volume */, bool /* active */>
4833 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004834 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004835 v *= vh.first;
4836 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004837
Glenn Kastenc56f3422014-03-21 17:53:17 -07004838 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4839 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4840 if (left > GAIN_FLOAT_UNITY) {
4841 left = GAIN_FLOAT_UNITY;
4842 }
4843 left *= v;
4844 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4845 if (right > GAIN_FLOAT_UNITY) {
4846 right = GAIN_FLOAT_UNITY;
4847 }
4848 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 }
4850
4851 if (lastTrack) {
4852 if (left != mLeftVolFloat || right != mRightVolFloat) {
4853 mLeftVolFloat = left;
4854 mRightVolFloat = right;
4855
4856 // Convert volumes from float to 8.24
4857 uint32_t vl = (uint32_t)(left * (1 << 24));
4858 uint32_t vr = (uint32_t)(right * (1 << 24));
4859
4860 // Delegate volume control to effect in track effect chain if needed
4861 // only one effect chain can be present on DirectOutputThread, so if
4862 // there is one, the track is connected to it
4863 if (!mEffectChains.isEmpty()) {
4864 mEffectChains[0]->setVolume_l(&vl, &vr);
4865 left = (float)vl / (1 << 24);
4866 right = (float)vr / (1 << 24);
4867 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004868 status_t result = mOutput->stream->setVolume(left, right);
4869 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004870 }
4871 }
4872}
4873
Phil Burk43b4dcc2015-06-09 16:53:44 -07004874void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4875{
4876 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004877 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004878
Eric Laurent0f0631e2015-07-06 18:01:25 -07004879 if (previousTrack != 0 && latestTrack != 0) {
4880 if (mType == DIRECT) {
4881 if (previousTrack.get() != latestTrack.get()) {
4882 mFlushPending = true;
4883 }
4884 } else /* mType == OFFLOAD */ {
4885 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4886 mFlushPending = true;
4887 }
4888 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004889 }
4890 PlaybackThread::onAddNewTrack_l();
4891}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004892
Eric Laurent81784c32012-11-19 14:55:58 -08004893AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4894 Vector< sp<Track> > *tracksToRemove
4895)
4896{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004897 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004898 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004899 bool doHwPause = false;
4900 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004901
4902 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004903 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004904 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004905 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004906 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004907 continue;
4908 }
4909
Eric Laurent5850c4c2016-11-10 13:04:31 -08004910 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004911#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004912 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004913#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004914 // Only consider last track started for volume and mixer state control.
4915 // In theory an older track could underrun and restart after the new one starts
4916 // but as we only care about the transition phase between two tracks on a
4917 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004918 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004919 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004920
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004921 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004922 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004923 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004924 doHwPause = true;
4925 mHwPaused = true;
4926 }
4927 tracksToRemove->add(track);
4928 } else if (track->isFlushPending()) {
4929 track->flushAck();
4930 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004931 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004932 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004933 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004934 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004935 if (last) {
4936 mLeftVolFloat = mRightVolFloat = -1.0;
4937 if (mHwPaused) {
4938 doHwResume = true;
4939 mHwPaused = false;
4940 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004941 }
4942 }
4943
Eric Laurent81784c32012-11-19 14:55:58 -08004944 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004945 // for all its buffers to be filled before processing it.
4946 // Allow draining the buffer in case the client
4947 // app does not call stop() and relies on underrun to stop:
4948 // hence the test on (track->mRetryCount > 1).
4949 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004950 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004951 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004952 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004953 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004954 minFrames = mNormalFrameCount;
4955 } else {
4956 minFrames = 1;
4957 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958
Eric Laurentab5cdba2014-06-09 17:22:27 -07004959 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4960 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004961 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004962 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004963
4964 if (track->mFillingUpStatus == Track::FS_FILLED) {
4965 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004966 if (last) {
4967 // make sure processVolume_l() will apply new volume even if 0
4968 mLeftVolFloat = mRightVolFloat = -1.0;
4969 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004970 if (!mHwSupportsPause) {
4971 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004972 }
4973 }
4974
4975 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004976 processVolume_l(track, last);
4977 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004978 sp<Track> previousTrack = mPreviousTrack.promote();
4979 if (previousTrack != 0) {
4980 if (track != previousTrack.get()) {
4981 // Flush any data still being written from last track
4982 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004983 // Invalidate previous track to force a seek when resuming.
4984 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004985 }
4986 }
4987 mPreviousTrack = track;
4988
Eric Laurentd595b7c2013-04-03 17:27:56 -07004989 // reset retry count
4990 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004991 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004992 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004993 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004994 doHwResume = true;
4995 mHwPaused = false;
4996 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07004997 }
Eric Laurent81784c32012-11-19 14:55:58 -08004998 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07004999 // clear effect chain input buffer if the last active track started underruns
5000 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005001 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005002 mEffectChains[0]->clearInputBuffer();
5003 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005004 if (track->isStopping_1()) {
5005 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005006 if (last && mHwPaused) {
5007 doHwResume = true;
5008 mHwPaused = false;
5009 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005010 }
5011 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5012 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005013 // We have consumed all the buffers of this track.
5014 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005015 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005016 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005017 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5018 } else {
5019 audioHALFrames = 0;
5020 }
5021
Andy Hung818e7a32016-02-16 18:08:07 -08005022 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005023 if (mStandby || !last ||
5024 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005025 if (track->isStopping_2()) {
5026 track->mState = TrackBase::STOPPED;
5027 }
Eric Laurent81784c32012-11-19 14:55:58 -08005028 if (track->isStopped()) {
5029 track->reset();
5030 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005031 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005032 }
5033 } else {
5034 // No buffers for this track. Give it a few chances to
5035 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005036 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005037 if (--(track->mRetryCount) <= 0) {
5038 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005039 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005040 // indicate to client process that the track was disabled because of underrun;
5041 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005042 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005043 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005044 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5045 "minFrames = %u, mFormat = %#x",
5046 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005047 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005048 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005049 doHwPause = true;
5050 mHwPaused = true;
5051 }
Eric Laurent81784c32012-11-19 14:55:58 -08005052 }
5053 }
5054 }
5055 }
5056
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005058 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059 for (size_t i = 0; i < mTracks.size(); i++) {
5060 if (mTracks[i]->isFlushPending()) {
5061 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005062 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005063 }
5064 }
5065 }
5066
5067 // make sure the pause/flush/resume sequence is executed in the right order.
5068 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5069 // before flush and then resume HW. This can happen in case of pause/flush/resume
5070 // if resume is received before pause is executed.
5071 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005072 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005073 status_t result = mOutput->stream->pause();
5074 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005075 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005076 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005077 flushHw_l();
5078 }
5079 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005080 status_t result = mOutput->stream->resume();
5081 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005082 }
Eric Laurent81784c32012-11-19 14:55:58 -08005083 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005084 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005085
5086 return mixerStatus;
5087}
5088
5089void AudioFlinger::DirectOutputThread::threadLoop_mix()
5090{
Eric Laurent81784c32012-11-19 14:55:58 -08005091 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005092 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005093 // output audio to hardware
5094 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005095 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005096 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005097 status_t status = mActiveTrack->getNextBuffer(&buffer);
5098 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005099 // no need to pad with 0 for compressed audio
5100 if (audio_has_proportional_frames(mFormat)) {
5101 memset(curBuf, 0, frameCount * mFrameSize);
5102 }
Eric Laurent81784c32012-11-19 14:55:58 -08005103 break;
5104 }
5105 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5106 frameCount -= buffer.frameCount;
5107 curBuf += buffer.frameCount * mFrameSize;
5108 mActiveTrack->releaseBuffer(&buffer);
5109 }
Andy Hung2098f272014-02-27 14:00:06 -08005110 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005111 mSleepTimeUs = 0;
5112 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005113 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005114}
5115
5116void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5117{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005118 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005119 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005120 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005121 return;
5122 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005123 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005124 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005125 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005126 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005127 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005128 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005129 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005130 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005131 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005132 }
5133}
5134
Eric Laurentd1f69b02014-12-15 14:33:13 -08005135void AudioFlinger::DirectOutputThread::threadLoop_exit()
5136{
5137 {
5138 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005139 for (size_t i = 0; i < mTracks.size(); i++) {
5140 if (mTracks[i]->isFlushPending()) {
5141 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005142 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005143 }
5144 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005145 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005146 flushHw_l();
5147 }
5148 }
5149 PlaybackThread::threadLoop_exit();
5150}
5151
5152// must be called with thread mutex locked
5153bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5154{
5155 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005156 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005157
vivek mehta9cd7ad12016-03-17 00:18:29 -07005158 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5159 return !mStandby;
5160 }
5161
Eric Laurentd1f69b02014-12-15 14:33:13 -08005162 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5163 // after a timeout and we will enter standby then.
5164 if (mTracks.size() > 0) {
5165 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005166 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5167 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005168 }
5169
Eric Laurent5cff4032015-05-26 13:49:58 -07005170 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005171}
5172
Eric Laurent81784c32012-11-19 14:55:58 -08005173// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005174int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005175 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005176{
Eric Laurentad7dd962016-09-22 12:38:37 -07005177 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5178 return -1;
5179 }
Eric Laurent81784c32012-11-19 14:55:58 -08005180 return 0;
5181}
5182
5183// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005184void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005185{
5186}
5187
Eric Laurent10351942014-05-08 18:49:52 -07005188// checkForNewParameter_l() must be called with ThreadBase::mLock held
5189bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5190 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005191{
5192 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005193 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005194
Eric Laurent10351942014-05-08 18:49:52 -07005195 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005196
Eric Laurent10351942014-05-08 18:49:52 -07005197 AudioParameter param = AudioParameter(keyValuePair);
5198 int value;
5199 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5200 // forward device change to effects that have requested to be
5201 // aware of attached audio device.
5202 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005203 a2dpDeviceChanged =
5204 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005205 mOutDevice = value;
5206 for (size_t i = 0; i < mEffectChains.size(); i++) {
5207 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005208 }
5209 }
Eric Laurent81784c32012-11-19 14:55:58 -08005210 }
Eric Laurent10351942014-05-08 18:49:52 -07005211 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5212 // do not accept frame count changes if tracks are open as the track buffer
5213 // size depends on frame count and correct behavior would not be garantied
5214 // if frame count is changed after track creation
5215 if (!mTracks.isEmpty()) {
5216 status = INVALID_OPERATION;
5217 } else {
5218 reconfig = true;
5219 }
5220 }
5221 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005222 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005223 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005224 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005225 mStandby = true;
5226 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005227 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005228 }
5229 if (status == NO_ERROR && reconfig) {
5230 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005231 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005232 }
5233 }
5234
Eric Laurent42537be2016-01-08 17:16:42 -08005235 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005236}
5237
5238uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5239{
5240 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005241 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005242 time = PlaybackThread::activeSleepTimeUs();
5243 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005244 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005245 }
5246 return time;
5247}
5248
5249uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5250{
5251 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005252 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005253 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5254 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005255 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005256 }
5257 return time;
5258}
5259
5260uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5261{
5262 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005263 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005264 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5265 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005266 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005267 }
5268 return time;
5269}
5270
5271void AudioFlinger::DirectOutputThread::cacheParameters_l()
5272{
5273 PlaybackThread::cacheParameters_l();
5274
5275 // use shorter standby delay as on normal output to release
5276 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005277 // no delay on outputs with HW A/V sync
5278 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005279 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005280 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005281 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005282 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005283 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005284 }
Eric Laurent81784c32012-11-19 14:55:58 -08005285}
5286
Eric Laurente659ef42014-09-29 13:06:46 -07005287void AudioFlinger::DirectOutputThread::flushHw_l()
5288{
Phil Burk062e67a2015-02-11 13:40:50 -08005289 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005290 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005291 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005292}
5293
Andy Hung10cbff12017-02-21 17:30:14 -08005294int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5295 // If a VolumeShaper is active, we must wake up periodically to update volume.
5296 const int64_t NS_PER_MS = 1000000;
5297 return mVolumeShaperActive ?
5298 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5299}
5300
Eric Laurent81784c32012-11-19 14:55:58 -08005301// ----------------------------------------------------------------------------
5302
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005304 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005306 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005307 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005308 mDrainSequence(0),
5309 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310{
5311}
5312
5313AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5314{
5315}
5316
5317void AudioFlinger::AsyncCallbackThread::onFirstRef()
5318{
5319 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5320}
5321
5322bool AudioFlinger::AsyncCallbackThread::threadLoop()
5323{
5324 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005325 uint32_t writeAckSequence;
5326 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005327 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005328
5329 {
5330 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005331 while (!((mWriteAckSequence & 1) ||
5332 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005333 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005334 exitPending())) {
5335 mWaitWorkCV.wait(mLock);
5336 }
5337
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 if (exitPending()) {
5339 break;
5340 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005341 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5342 mWriteAckSequence, mDrainSequence);
5343 writeAckSequence = mWriteAckSequence;
5344 mWriteAckSequence &= ~1;
5345 drainSequence = mDrainSequence;
5346 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005347 asyncError = mAsyncError;
5348 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005349 }
5350 {
Eric Laurent4de95592013-09-26 15:28:21 -07005351 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5352 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005353 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005354 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005356 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005357 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005358 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005359 if (asyncError) {
5360 playbackThread->onAsyncError();
5361 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005362 }
5363 }
5364 }
5365 return false;
5366}
5367
5368void AudioFlinger::AsyncCallbackThread::exit()
5369{
5370 ALOGV("AsyncCallbackThread::exit");
5371 Mutex::Autolock _l(mLock);
5372 requestExit();
5373 mWaitWorkCV.broadcast();
5374}
5375
Eric Laurent3b4529e2013-09-05 18:09:19 -07005376void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005377{
5378 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005379 // bit 0 is cleared
5380 mWriteAckSequence = sequence << 1;
5381}
5382
5383void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5384{
5385 Mutex::Autolock _l(mLock);
5386 // ignore unexpected callbacks
5387 if (mWriteAckSequence & 2) {
5388 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389 mWaitWorkCV.signal();
5390 }
5391}
5392
Eric Laurent3b4529e2013-09-05 18:09:19 -07005393void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394{
5395 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005396 // bit 0 is cleared
5397 mDrainSequence = sequence << 1;
5398}
5399
5400void AudioFlinger::AsyncCallbackThread::resetDraining()
5401{
5402 Mutex::Autolock _l(mLock);
5403 // ignore unexpected callbacks
5404 if (mDrainSequence & 2) {
5405 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406 mWaitWorkCV.signal();
5407 }
5408}
5409
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005410void AudioFlinger::AsyncCallbackThread::setAsyncError()
5411{
5412 Mutex::Autolock _l(mLock);
5413 mAsyncError = true;
5414 mWaitWorkCV.signal();
5415}
5416
Eric Laurentbfb1b832013-01-07 09:53:42 -08005417
5418// ----------------------------------------------------------------------------
5419AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005420 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5421 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005422 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5423 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005424{
Eric Laurentfd477972013-10-25 18:10:40 -07005425 //FIXME: mStandby should be set to true by ThreadBase constructor
5426 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005427 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428}
5429
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430void AudioFlinger::OffloadThread::threadLoop_exit()
5431{
5432 if (mFlushPending || mHwPaused) {
5433 // If a flush is pending or track was paused, just discard buffered data
5434 flushHw_l();
5435 } else {
5436 mMixerStatus = MIXER_DRAIN_ALL;
5437 threadLoop_drain();
5438 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005439 if (mUseAsyncWrite) {
5440 ALOG_ASSERT(mCallbackThread != 0);
5441 mCallbackThread->exit();
5442 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005443 PlaybackThread::threadLoop_exit();
5444}
5445
5446AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5447 Vector< sp<Track> > *tracksToRemove
5448)
5449{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005450 size_t count = mActiveTracks.size();
5451
5452 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005453 bool doHwPause = false;
5454 bool doHwResume = false;
5455
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005456 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005457
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005459 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005460 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005461#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005463#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005464 // Only consider last track started for volume and mixer state control.
5465 // In theory an older track could underrun and restart after the new one starts
5466 // but as we only care about the transition phase between two tracks on a
5467 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005468 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005469 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005470
Haynes Mathew George7844f672014-01-15 12:32:55 -08005471 if (track->isInvalid()) {
5472 ALOGW("An invalidated track shouldn't be in active list");
5473 tracksToRemove->add(track);
5474 continue;
5475 }
5476
5477 if (track->mState == TrackBase::IDLE) {
5478 ALOGW("An idle track shouldn't be in active list");
5479 continue;
5480 }
5481
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 if (track->isPausing()) {
5483 track->setPaused();
5484 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005485 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005486 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 mHwPaused = true;
5488 }
5489 // If we were part way through writing the mixbuffer to
5490 // the HAL we must save this until we resume
5491 // BUG - this will be wrong if a different track is made active,
5492 // in that case we want to discard the pending data in the
5493 // mixbuffer and tell the client to present it again when the
5494 // track is resumed
5495 mPausedWriteLength = mCurrentWriteLength;
5496 mPausedBytesRemaining = mBytesRemaining;
5497 mBytesRemaining = 0; // stop writing
5498 }
5499 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005500 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005501 if (track->isStopping_1()) {
5502 track->mRetryCount = kMaxTrackStopRetriesOffload;
5503 } else {
5504 track->mRetryCount = kMaxTrackRetriesOffload;
5505 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005506 track->flushAck();
5507 if (last) {
5508 mFlushPending = true;
5509 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005510 } else if (track->isResumePending()){
5511 track->resumeAck();
5512 if (last) {
5513 if (mPausedBytesRemaining) {
5514 // Need to continue write that was interrupted
5515 mCurrentWriteLength = mPausedWriteLength;
5516 mBytesRemaining = mPausedBytesRemaining;
5517 mPausedBytesRemaining = 0;
5518 }
5519 if (mHwPaused) {
5520 doHwResume = true;
5521 mHwPaused = false;
5522 // threadLoop_mix() will handle the case that we need to
5523 // resume an interrupted write
5524 }
5525 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005526 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005527
Eric Laurent3df841a2016-07-15 15:15:40 -07005528 mLeftVolFloat = mRightVolFloat = -1.0;
5529
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005530 // Do not handle new data in this iteration even if track->framesReady()
5531 mixerStatus = MIXER_TRACKS_ENABLED;
5532 }
5533 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005534 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005535 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005536 if (track->mFillingUpStatus == Track::FS_FILLED) {
5537 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005538 if (last) {
5539 // make sure processVolume_l() will apply new volume even if 0
5540 mLeftVolFloat = mRightVolFloat = -1.0;
5541 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005542 }
5543
5544 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005545 sp<Track> previousTrack = mPreviousTrack.promote();
5546 if (previousTrack != 0) {
5547 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005548 // Flush any data still being written from last track
5549 mBytesRemaining = 0;
5550 if (mPausedBytesRemaining) {
5551 // Last track was paused so we also need to flush saved
5552 // mixbuffer state and invalidate track so that it will
5553 // re-submit that unwritten data when it is next resumed
5554 mPausedBytesRemaining = 0;
5555 // Invalidate is a bit drastic - would be more efficient
5556 // to have a flag to tell client that some of the
5557 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005558 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005559 }
5560 // flush data already sent to the DSP if changing audio session as audio
5561 // comes from a different source. Also invalidate previous track to force a
5562 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005563 if (previousTrack->sessionId() != track->sessionId()) {
5564 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005565 }
5566 }
5567 }
5568 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005569 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005570 if (track->isStopping_1()) {
5571 track->mRetryCount = kMaxTrackStopRetriesOffload;
5572 } else {
5573 track->mRetryCount = kMaxTrackRetriesOffload;
5574 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005575 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005576 mixerStatus = MIXER_TRACKS_READY;
5577 }
5578 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005579 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005580 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005581 if (--(track->mRetryCount) <= 0) {
5582 // Hardware buffer can hold a large amount of audio so we must
5583 // wait for all current track's data to drain before we say
5584 // that the track is stopped.
5585 if (mBytesRemaining == 0) {
5586 // Only start draining when all data in mixbuffer
5587 // has been written
5588 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5589 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5590 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5591 if (last && !mStandby) {
5592 // do not modify drain sequence if we are already draining. This happens
5593 // when resuming from pause after drain.
5594 if ((mDrainSequence & 1) == 0) {
5595 mSleepTimeUs = 0;
5596 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5597 mixerStatus = MIXER_DRAIN_TRACK;
5598 mDrainSequence += 2;
5599 }
5600 if (mHwPaused) {
5601 // It is possible to move from PAUSED to STOPPING_1 without
5602 // a resume so we must ensure hardware is running
5603 doHwResume = true;
5604 mHwPaused = false;
5605 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005606 }
5607 }
Eric Laurente93cc032016-05-05 10:15:10 -07005608 } else if (last) {
5609 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5610 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005611 }
5612 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005613 // Drain has completed or we are in standby, signal presentation complete
5614 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005615 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005616 uint32_t latency = 0;
5617 status_t result = mOutput->stream->getLatency(&latency);
5618 ALOGE_IF(result != OK,
5619 "Error when retrieving output stream latency: %d", result);
5620 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005621 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005622 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005623 track->presentationComplete(framesWritten, audioHALFrames);
5624 track->reset();
5625 tracksToRemove->add(track);
5626 }
5627 } else {
5628 // No buffers for this track. Give it a few chances to
5629 // fill a buffer, then remove it from active list.
5630 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005631 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005632 uint64_t position = 0;
5633 struct timespec unused;
5634 // The running check restarts the retry counter at least once.
5635 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5636 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5637 running = true;
5638 mOffloadUnderrunPosition = position;
5639 }
5640 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005641 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5642 (long long)position, (long long)mOffloadUnderrunPosition);
5643 }
5644 if (running) { // still running, give us more time.
5645 track->mRetryCount = kMaxTrackRetriesOffload;
5646 } else {
5647 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5648 track->name());
5649 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005650 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005651 // it will then automatically call start() when data is available
5652 track->disable();
5653 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005654 } else if (last){
5655 mixerStatus = MIXER_TRACKS_ENABLED;
5656 }
5657 }
5658 }
5659 // compute volume for this track
5660 processVolume_l(track, last);
5661 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005662
Eric Laurentea0fade2013-10-04 16:23:48 -07005663 // make sure the pause/flush/resume sequence is executed in the right order.
5664 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5665 // before flush and then resume HW. This can happen in case of pause/flush/resume
5666 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005667 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005668 status_t result = mOutput->stream->pause();
5669 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005670 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005671 if (mFlushPending) {
5672 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005673 }
Eric Laurentfd477972013-10-25 18:10:40 -07005674 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005675 status_t result = mOutput->stream->resume();
5676 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005677 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005678
Eric Laurentbfb1b832013-01-07 09:53:42 -08005679 // remove all the tracks that need to be...
5680 removeTracks_l(*tracksToRemove);
5681
5682 return mixerStatus;
5683}
5684
Eric Laurentbfb1b832013-01-07 09:53:42 -08005685// must be called with thread mutex locked
5686bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5687{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005688 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5689 mWriteAckSequence, mDrainSequence);
5690 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691 return true;
5692 }
5693 return false;
5694}
5695
Eric Laurentbfb1b832013-01-07 09:53:42 -08005696bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5697{
5698 Mutex::Autolock _l(mLock);
5699 return waitingAsyncCallback_l();
5700}
5701
5702void AudioFlinger::OffloadThread::flushHw_l()
5703{
Eric Laurente659ef42014-09-29 13:06:46 -07005704 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005705 // Flush anything still waiting in the mixbuffer
5706 mCurrentWriteLength = 0;
5707 mBytesRemaining = 0;
5708 mPausedWriteLength = 0;
5709 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005710 // reset bytes written count to reflect that DSP buffers are empty after flush.
5711 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005712 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005713
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005715 // discard any pending drain or write ack by incrementing sequence
5716 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5717 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005718 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005719 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5720 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005721 }
5722}
5723
Haynes Mathew George05317d22016-05-03 16:34:26 -07005724void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5725{
5726 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005727 if (PlaybackThread::invalidateTracks_l(streamType)) {
5728 mFlushPending = true;
5729 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005730}
5731
Eric Laurentbfb1b832013-01-07 09:53:42 -08005732// ----------------------------------------------------------------------------
5733
Eric Laurent81784c32012-11-19 14:55:58 -08005734AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005735 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005736 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005737 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005738 mWaitTimeMs(UINT_MAX)
5739{
5740 addOutputTrack(mainThread);
5741}
5742
5743AudioFlinger::DuplicatingThread::~DuplicatingThread()
5744{
5745 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5746 mOutputTracks[i]->destroy();
5747 }
5748}
5749
5750void AudioFlinger::DuplicatingThread::threadLoop_mix()
5751{
5752 // mix buffers...
5753 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005754 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005755 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005756 if (mMixerBufferValid) {
5757 memset(mMixerBuffer, 0, mMixerBufferSize);
5758 } else {
5759 memset(mSinkBuffer, 0, mSinkBufferSize);
5760 }
Eric Laurent81784c32012-11-19 14:55:58 -08005761 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005762 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005763 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005764 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005765 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005766}
5767
5768void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5769{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005770 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005771 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005772 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005773 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005774 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005775 }
5776 } else if (mBytesWritten != 0) {
5777 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5778 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005779 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005780 } else {
5781 // flush remaining overflow buffers in output tracks
5782 writeFrames = 0;
5783 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005784 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005785 }
5786}
5787
Eric Laurentbfb1b832013-01-07 09:53:42 -08005788ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005789{
5790 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005791 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005792 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005793 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005794 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005795}
5796
5797void AudioFlinger::DuplicatingThread::threadLoop_standby()
5798{
5799 // DuplicatingThread implements standby by stopping all tracks
5800 for (size_t i = 0; i < outputTracks.size(); i++) {
5801 outputTracks[i]->stop();
5802 }
5803}
5804
5805void AudioFlinger::DuplicatingThread::saveOutputTracks()
5806{
5807 outputTracks = mOutputTracks;
5808}
5809
5810void AudioFlinger::DuplicatingThread::clearOutputTracks()
5811{
5812 outputTracks.clear();
5813}
5814
5815void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5816{
5817 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005818 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5819 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5820 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5821 const size_t frameCount =
5822 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5823 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5824 // from different OutputTracks and their associated MixerThreads (e.g. one may
5825 // nearly empty and the other may be dropping data).
5826
5827 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005828 this,
5829 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005830 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005831 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005832 frameCount,
5833 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005834 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5835 if (status != NO_ERROR) {
5836 ALOGE("addOutputTrack() initCheck failed %d", status);
5837 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005838 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005839 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5840 mOutputTracks.add(outputTrack);
5841 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5842 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005843}
5844
5845void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5846{
5847 Mutex::Autolock _l(mLock);
5848 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5849 if (mOutputTracks[i]->thread() == thread) {
5850 mOutputTracks[i]->destroy();
5851 mOutputTracks.removeAt(i);
5852 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005853 if (thread->getOutput() == mOutput) {
5854 mOutput = NULL;
5855 }
Eric Laurent81784c32012-11-19 14:55:58 -08005856 return;
5857 }
5858 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005859 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005860}
5861
5862// caller must hold mLock
5863void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5864{
5865 mWaitTimeMs = UINT_MAX;
5866 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5867 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5868 if (strong != 0) {
5869 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5870 if (waitTimeMs < mWaitTimeMs) {
5871 mWaitTimeMs = waitTimeMs;
5872 }
5873 }
5874 }
5875}
5876
5877
5878bool AudioFlinger::DuplicatingThread::outputsReady(
5879 const SortedVector< sp<OutputTrack> > &outputTracks)
5880{
5881 for (size_t i = 0; i < outputTracks.size(); i++) {
5882 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5883 if (thread == 0) {
5884 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5885 outputTracks[i].get());
5886 return false;
5887 }
5888 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5889 // see note at standby() declaration
5890 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5891 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5892 thread.get());
5893 return false;
5894 }
5895 }
5896 return true;
5897}
5898
5899uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5900{
5901 return (mWaitTimeMs * 1000) / 2;
5902}
5903
5904void AudioFlinger::DuplicatingThread::cacheParameters_l()
5905{
5906 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5907 updateWaitTime_l();
5908
5909 MixerThread::cacheParameters_l();
5910}
5911
Eric Laurent6acd1d42017-01-04 14:23:29 -08005912
Eric Laurent81784c32012-11-19 14:55:58 -08005913// ----------------------------------------------------------------------------
5914// Record
5915// ----------------------------------------------------------------------------
5916
5917AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5918 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005919 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005920 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005921 audio_devices_t inDevice,
5922 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005923#ifdef TEE_SINK
5924 , const sp<NBAIO_Sink>& teeSink
5925#endif
5926 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005927 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005928 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005929 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005930 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005931#ifdef TEE_SINK
5932 , mTeeSink(teeSink)
5933#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005934 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5935 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005936 // mFastCapture below
5937 , mFastCaptureFutex(0)
5938 // mInputSource
5939 // mPipeSink
5940 // mPipeSource
5941 , mPipeFramesP2(0)
5942 // mPipeMemory
5943 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005944 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07005945 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005946{
Glenn Kastend7dca052015-03-05 16:05:54 -08005947 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5948 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005949
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005950 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005951
5952 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005953 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005954 size_t numCounterOffers = 0;
5955 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005956#if !LOG_NDEBUG
5957 ssize_t index =
5958#else
5959 (void)
5960#endif
5961 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005962 ALOG_ASSERT(index == 0);
5963
5964 // initialize fast capture depending on configuration
5965 bool initFastCapture;
5966 switch (kUseFastCapture) {
5967 case FastCapture_Never:
5968 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005969 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005970 break;
5971 case FastCapture_Always:
5972 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005973 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005974 break;
5975 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005976 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005977 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
5978 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
5979 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005980 break;
5981 // case FastCapture_Dynamic:
5982 }
5983
5984 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005985 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005986 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005987 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5988 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005989 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005990 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005991 const sp<MemoryDealer> roHeap(readOnlyHeap());
5992 sp<IMemory> pipeMemory;
5993 if ((roHeap == 0) ||
5994 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005995 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
5996 ALOGE("not enough memory for pipe buffer size=%zu; "
5997 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
5998 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
5999 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006000 goto failed;
6001 }
6002 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6003 memset(pipeBuffer, 0, pipeSize);
6004 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6005 const NBAIO_Format offers[1] = {format};
6006 size_t numCounterOffers = 0;
6007 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6008 ALOG_ASSERT(index == 0);
6009 mPipeSink = pipe;
6010 PipeReader *pipeReader = new PipeReader(*pipe);
6011 numCounterOffers = 0;
6012 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6013 ALOG_ASSERT(index == 0);
6014 mPipeSource = pipeReader;
6015 mPipeFramesP2 = pipeFramesP2;
6016 mPipeMemory = pipeMemory;
6017
6018 // create fast capture
6019 mFastCapture = new FastCapture();
6020 FastCaptureStateQueue *sq = mFastCapture->sq();
6021#ifdef STATE_QUEUE_DUMP
6022 // FIXME
6023#endif
6024 FastCaptureState *state = sq->begin();
6025 state->mCblk = NULL;
6026 state->mInputSource = mInputSource.get();
6027 state->mInputSourceGen++;
6028 state->mPipeSink = pipe;
6029 state->mPipeSinkGen++;
6030 state->mFrameCount = mFrameCount;
6031 state->mCommand = FastCaptureState::COLD_IDLE;
6032 // already done in constructor initialization list
6033 //mFastCaptureFutex = 0;
6034 state->mColdFutexAddr = &mFastCaptureFutex;
6035 state->mColdGen++;
6036 state->mDumpState = &mFastCaptureDumpState;
6037#ifdef TEE_SINK
6038 // FIXME
6039#endif
6040 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6041 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6042 sq->end();
6043 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6044
6045 // start the fast capture
6046 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6047 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006048 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006049 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006050#ifdef AUDIO_WATCHDOG
6051 // FIXME
6052#endif
6053
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006054 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006055 }
6056failed: ;
6057
6058 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006059}
6060
Eric Laurent81784c32012-11-19 14:55:58 -08006061AudioFlinger::RecordThread::~RecordThread()
6062{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006063 if (mFastCapture != 0) {
6064 FastCaptureStateQueue *sq = mFastCapture->sq();
6065 FastCaptureState *state = sq->begin();
6066 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6067 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6068 if (old == -1) {
6069 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6070 }
6071 }
6072 state->mCommand = FastCaptureState::EXIT;
6073 sq->end();
6074 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6075 mFastCapture->join();
6076 mFastCapture.clear();
6077 }
6078 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006079 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006080 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006081}
6082
6083void AudioFlinger::RecordThread::onFirstRef()
6084{
Glenn Kastend7dca052015-03-05 16:05:54 -08006085 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006086}
6087
Eric Laurent555530a2017-02-07 18:17:24 -08006088void AudioFlinger::RecordThread::preExit()
6089{
6090 ALOGV(" preExit()");
6091 Mutex::Autolock _l(mLock);
6092 for (size_t i = 0; i < mTracks.size(); i++) {
6093 sp<RecordTrack> track = mTracks[i];
6094 track->invalidate();
6095 }
6096 mActiveTracks.clear();
6097 mStartStopCond.broadcast();
6098}
6099
Eric Laurent81784c32012-11-19 14:55:58 -08006100bool AudioFlinger::RecordThread::threadLoop()
6101{
Eric Laurent81784c32012-11-19 14:55:58 -08006102 nsecs_t lastWarning = 0;
6103
6104 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006105
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006106reacquire_wakelock:
6107 sp<RecordTrack> activeTrack;
6108 {
6109 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006110 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006111 }
6112
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006113 // used to request a deferred sleep, to be executed later while mutex is unlocked
6114 uint32_t sleepUs = 0;
6115
6116 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006117 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006118 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006119
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006120 // activeTracks accumulates a copy of a subset of mActiveTracks
6121 Vector< sp<RecordTrack> > activeTracks;
6122
Glenn Kasten735f45f2014-08-18 15:51:59 -07006123 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006124 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006125
Glenn Kasten735f45f2014-08-18 15:51:59 -07006126 // reference to a fast track which is about to be removed
6127 sp<RecordTrack> fastTrackToRemove;
6128
Eric Laurent81784c32012-11-19 14:55:58 -08006129 { // scope for mLock
6130 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006131
Eric Laurent021cf962014-05-13 10:18:14 -07006132 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006133
Eric Laurent000a4192014-01-29 15:17:32 -08006134 // check exitPending here because checkForNewParameters_l() and
6135 // checkForNewParameters_l() can temporarily release mLock
6136 if (exitPending()) {
6137 break;
6138 }
6139
Eric Laurent5c25d562016-07-13 17:17:45 -07006140 // sleep with mutex unlocked
6141 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006142 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006143 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6144 ATRACE_END();
6145 sleepUs = 0;
6146 continue;
6147 }
6148
Glenn Kasten2b806402013-11-20 16:37:38 -08006149 // if no active track(s), then standby and release wakelock
6150 size_t size = mActiveTracks.size();
6151 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006152 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006153 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006154 releaseWakeLock_l();
6155 ALOGV("RecordThread: loop stopping");
6156 // go to sleep
6157 mWaitWorkCV.wait(mLock);
6158 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006159 goto reacquire_wakelock;
6160 }
6161
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006162 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006163 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006164 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006165
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 activeTrack = mActiveTracks[i];
6167 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006168 if (activeTrack->isFastTrack()) {
6169 ALOG_ASSERT(fastTrackToRemove == 0);
6170 fastTrackToRemove = activeTrack;
6171 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006172 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006173 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006175 continue;
6176 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177
6178 TrackBase::track_state activeTrackState = activeTrack->mState;
6179 switch (activeTrackState) {
6180
6181 case TrackBase::PAUSING:
6182 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006183 doBroadcast = true;
6184 size--;
6185 continue;
6186
6187 case TrackBase::STARTING_1:
6188 sleepUs = 10000;
6189 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006190 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 continue;
6192
6193 case TrackBase::STARTING_2:
6194 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006196 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006197 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006198 break;
6199
6200 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006201 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006202 break;
6203
6204 case TrackBase::IDLE:
6205 i++;
6206 continue;
6207
6208 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006209 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006210 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006211
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 activeTracks.add(activeTrack);
6213 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006215 if (activeTrack->isFastTrack()) {
6216 ALOG_ASSERT(!mFastTrackAvail);
6217 ALOG_ASSERT(fastTrack == 0);
6218 fastTrack = activeTrack;
6219 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006220 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006221
Andy Hungdae27702016-10-31 14:01:16 -07006222 mActiveTracks.updatePowerState(this);
6223
Eric Laurent5c25d562016-07-13 17:17:45 -07006224 if (allStopped) {
6225 standbyIfNotAlreadyInStandby();
6226 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006227 if (doBroadcast) {
6228 mStartStopCond.broadcast();
6229 }
6230
6231 // sleep if there are no active tracks to process
6232 if (activeTracks.size() == 0) {
6233 if (sleepUs == 0) {
6234 sleepUs = kRecordThreadSleepUs;
6235 }
6236 continue;
6237 }
6238 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006239
Eric Laurent81784c32012-11-19 14:55:58 -08006240 lockEffectChains_l(effectChains);
6241 }
6242
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006243 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006244
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006245 size_t size = effectChains.size();
6246 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006247 // thread mutex is not locked, but effect chain is locked
6248 effectChains[i]->process_l();
6249 }
6250
Glenn Kasten735f45f2014-08-18 15:51:59 -07006251 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006252 if (mFastCapture != 0) {
6253 FastCaptureStateQueue *sq = mFastCapture->sq();
6254 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006255 bool didModify = false;
6256 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006257 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6258 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6259 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6260 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6261 if (old == -1) {
6262 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6263 }
6264 }
6265 state->mCommand = FastCaptureState::READ_WRITE;
6266#if 0 // FIXME
6267 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006268 FastThreadDumpState::kSamplingNforLowRamDevice :
6269 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006270#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006271 didModify = true;
6272 }
6273 audio_track_cblk_t *cblkOld = state->mCblk;
6274 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6275 if (cblkNew != cblkOld) {
6276 state->mCblk = cblkNew;
6277 // block until acked if removing a fast track
6278 if (cblkOld != NULL) {
6279 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6280 }
6281 didModify = true;
6282 }
6283 sq->end(didModify);
6284 if (didModify) {
6285 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006286#if 0
6287 if (kUseFastCapture == FastCapture_Dynamic) {
6288 mNormalSource = mPipeSource;
6289 }
6290#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006291 }
6292 }
6293
Glenn Kasten735f45f2014-08-18 15:51:59 -07006294 // now run the fast track destructor with thread mutex unlocked
6295 fastTrackToRemove.clear();
6296
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006297 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6298 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6299 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6300 // If destination is non-contiguous, first read past the nominal end of buffer, then
6301 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006302
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006304 ssize_t framesRead;
6305
6306 // If an NBAIO source is present, use it to read the normal capture's data
6307 if (mPipeSource != 0) {
6308 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006309 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006310 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006311 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006312 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6313 // buffer size or at least for 20ms.
6314 size_t sleepFrames = max(
6315 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6316 if (framesRead <= (ssize_t) sleepFrames) {
6317 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6318 }
6319 if (framesRead < 0) {
6320 status_t status = (status_t) framesRead;
6321 switch (status) {
6322 case OVERRUN:
6323 ALOGW("overrun on read from pipe");
6324 framesRead = 0;
6325 break;
6326 case NEGOTIATE:
6327 ALOGE("re-negotiation is needed");
6328 framesRead = -1; // Will cause an attempt to recover.
6329 break;
6330 default:
6331 ALOGE("unknown error %d on read from pipe", status);
6332 break;
6333 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006334 }
6335 // otherwise use the HAL / AudioStreamIn directly
6336 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006337 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006338 size_t bytesRead;
6339 status_t result = mInput->stream->read(
6340 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006341 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006342 if (result < 0) {
6343 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006344 } else {
6345 framesRead = bytesRead / mFrameSize;
6346 }
6347 }
6348
Andy Hung3f0c9022016-01-15 17:49:46 -08006349 // Update server timestamp with server stats
6350 // systemTime() is optional if the hardware supports timestamps.
6351 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6352 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6353
6354 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006355 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006356 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006357 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006358 if (ret == NO_ERROR) {
6359 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6360 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6361 // Note: In general record buffers should tend to be empty in
6362 // a properly running pipeline.
6363 //
6364 // Also, it is not advantageous to call get_presentation_position during the read
6365 // as the read obtains a lock, preventing the timestamp call from executing.
6366 }
6367 }
6368 // Use this to track timestamp information
6369 // ALOGD("%s", mTimestamp.toString().c_str());
6370
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006371 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006372 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006373 // Force input into standby so that it tries to recover at next read attempt
6374 inputStandBy();
6375 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006376 }
6377 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006378 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006379 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006380 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006381
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006383 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006384 }
6385 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006386 {
6387 size_t part1 = mRsmpInFramesP2 - rear;
6388 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006389 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006390 (framesRead - part1) * mFrameSize);
6391 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006392 }
6393 rear = mRsmpInRear += framesRead;
6394
6395 size = activeTracks.size();
6396 // loop over each active track
6397 for (size_t i = 0; i < size; i++) {
6398 activeTrack = activeTracks[i];
6399
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006400 // skip fast tracks, as those are handled directly by FastCapture
6401 if (activeTrack->isFastTrack()) {
6402 continue;
6403 }
6404
Andy Hung73c02e42015-03-29 01:13:58 -07006405 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006406 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6407
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006408 enum {
6409 OVERRUN_UNKNOWN,
6410 OVERRUN_TRUE,
6411 OVERRUN_FALSE
6412 } overrun = OVERRUN_UNKNOWN;
6413
6414 // loop over getNextBuffer to handle circular sink
6415 for (;;) {
6416
6417 activeTrack->mSink.frameCount = ~0;
6418 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6419 size_t framesOut = activeTrack->mSink.frameCount;
6420 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6421
Andy Hung73c02e42015-03-29 01:13:58 -07006422 // check available frames and handle overrun conditions
6423 // if the record track isn't draining fast enough.
6424 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006425 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006426 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6427 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006428 overrun = OVERRUN_TRUE;
6429 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006430 if (framesOut == 0 || framesIn == 0) {
6431 break;
6432 }
6433
Andy Hung6770c6f2015-04-07 13:43:36 -07006434 // Don't allow framesOut to be larger than what is possible with resampling
6435 // from framesIn.
6436 // This isn't strictly necessary but helps limit buffer resizing in
6437 // RecordBufferConverter. TODO: remove when no longer needed.
6438 framesOut = min(framesOut,
6439 destinationFramesPossible(
6440 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006441 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6442 framesOut = activeTrack->mRecordBufferConverter->convert(
6443 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006444
6445 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6446 overrun = OVERRUN_FALSE;
6447 }
6448
6449 if (activeTrack->mFramesToDrop == 0) {
6450 if (framesOut > 0) {
6451 activeTrack->mSink.frameCount = framesOut;
6452 activeTrack->releaseBuffer(&activeTrack->mSink);
6453 }
6454 } else {
6455 // FIXME could do a partial drop of framesOut
6456 if (activeTrack->mFramesToDrop > 0) {
6457 activeTrack->mFramesToDrop -= framesOut;
6458 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006459 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006460 }
6461 } else {
6462 activeTrack->mFramesToDrop += framesOut;
6463 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6464 activeTrack->mSyncStartEvent->isCancelled()) {
6465 ALOGW("Synced record %s, session %d, trigger session %d",
6466 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6467 activeTrack->sessionId(),
6468 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006469 activeTrack->mSyncStartEvent->triggerSession() :
6470 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006471 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006472 }
6473 }
6474 }
6475
6476 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006477 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006478 }
6479 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006480
6481 switch (overrun) {
6482 case OVERRUN_TRUE:
6483 // client isn't retrieving buffers fast enough
6484 if (!activeTrack->setOverflow()) {
6485 nsecs_t now = systemTime();
6486 // FIXME should lastWarning per track?
6487 if ((now - lastWarning) > kWarningThrottleNs) {
6488 ALOGW("RecordThread: buffer overflow");
6489 lastWarning = now;
6490 }
6491 }
6492 break;
6493 case OVERRUN_FALSE:
6494 activeTrack->clearOverflow();
6495 break;
6496 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006497 break;
6498 }
6499
Andy Hung3f0c9022016-01-15 17:49:46 -08006500 // update frame information and push timestamp out
6501 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006502 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006503 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6504 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006505 }
6506
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006507unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006508 // enable changes in effect chain
6509 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006510 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006511 }
6512
Glenn Kasten93e471f2013-08-19 08:40:07 -07006513 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006514
6515 {
6516 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006517 for (size_t i = 0; i < mTracks.size(); i++) {
6518 sp<RecordTrack> track = mTracks[i];
6519 track->invalidate();
6520 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006521 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006522 mStartStopCond.broadcast();
6523 }
6524
6525 releaseWakeLock();
6526
6527 ALOGV("RecordThread %p exiting", this);
6528 return false;
6529}
6530
Glenn Kasten93e471f2013-08-19 08:40:07 -07006531void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006532{
6533 if (!mStandby) {
6534 inputStandBy();
6535 mStandby = true;
6536 }
6537}
6538
6539void AudioFlinger::RecordThread::inputStandBy()
6540{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006541 // Idle the fast capture if it's currently running
6542 if (mFastCapture != 0) {
6543 FastCaptureStateQueue *sq = mFastCapture->sq();
6544 FastCaptureState *state = sq->begin();
6545 if (!(state->mCommand & FastCaptureState::IDLE)) {
6546 state->mCommand = FastCaptureState::COLD_IDLE;
6547 state->mColdFutexAddr = &mFastCaptureFutex;
6548 state->mColdGen++;
6549 mFastCaptureFutex = 0;
6550 sq->end();
6551 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6552 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6553#if 0
6554 if (kUseFastCapture == FastCapture_Dynamic) {
6555 // FIXME
6556 }
6557#endif
6558#ifdef AUDIO_WATCHDOG
6559 // FIXME
6560#endif
6561 } else {
6562 sq->end(false /*didModify*/);
6563 }
6564 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006565 status_t result = mInput->stream->standby();
6566 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006567
6568 // If going into standby, flush the pipe source.
6569 if (mPipeSource.get() != nullptr) {
6570 const ssize_t flushed = mPipeSource->flush();
6571 if (flushed > 0) {
6572 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6573 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6574 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6575 }
6576 }
Eric Laurent81784c32012-11-19 14:55:58 -08006577}
6578
Glenn Kasten05997e22014-03-13 15:08:33 -07006579// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006580sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006581 const sp<AudioFlinger::Client>& client,
6582 uint32_t sampleRate,
6583 audio_format_t format,
6584 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006585 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006586 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006587 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006588 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006589 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006590 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006591 status_t *status,
6592 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006593{
Glenn Kasten74935e42013-12-19 08:56:45 -08006594 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006595 sp<RecordTrack> track;
6596 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006597 audio_input_flags_t inputFlags = mInput->flags;
6598
6599 // special case for FAST flag considered OK if fast capture is present
6600 if (hasFastCapture()) {
6601 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6602 }
6603
6604 // Check if requested flags are compatible with output stream flags
6605 if ((*flags & inputFlags) != *flags) {
6606 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6607 " input flags (%08x)",
6608 *flags, inputFlags);
6609 *flags = (audio_input_flags_t)(*flags & inputFlags);
6610 }
Eric Laurent81784c32012-11-19 14:55:58 -08006611
Glenn Kasten90e58b12013-07-31 16:16:02 -07006612 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006613 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006614 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006615 // we formerly checked for a callback handler (non-0 tid),
6616 // but that is no longer required for TRANSFER_OBTAIN mode
6617 //
Glenn Kasten74105912014-07-03 12:28:53 -07006618 // frame count is not specified, or is exactly the pipe depth
6619 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006620 // PCM data
6621 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006622 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006623 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006624 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006625 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006626 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006627 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006628 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006629 hasFastCapture() &&
6630 // there are sufficient fast track slots available
6631 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006632 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006633 // check compatibility with audio effects.
6634 Mutex::Autolock _l(mLock);
6635 // Do not accept FAST flag if the session has software effects
6636 sp<EffectChain> chain = getEffectChain_l(sessionId);
6637 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006638 audio_input_flags_t old = *flags;
6639 chain->checkInputFlagCompatibility(flags);
6640 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006641 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6642 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006643 }
6644 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006645 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006646 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6647 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006648 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006649 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6650 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006651 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006652 this, frameCount, mFrameCount, mPipeFramesP2,
6653 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006654 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006655 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006656 }
6657 }
6658
6659 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006660 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006661 // fast track: frame count is exactly the pipe depth
6662 frameCount = mPipeFramesP2;
6663 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6664 *notificationFrames = mFrameCount;
6665 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006666 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6667 // or 20 ms if there is a fast capture
6668 // TODO This could be a roundupRatio inline, and const
6669 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6670 * sampleRate + mSampleRate - 1) / mSampleRate;
6671 // minimum number of notification periods is at least kMinNotifications,
6672 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6673 static const size_t kMinNotifications = 3;
6674 static const uint32_t kMinMs = 30;
6675 // TODO This could be a roundupRatio inline
6676 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6677 // TODO This could be a roundupRatio inline
6678 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6679 maxNotificationFrames;
6680 const size_t minFrameCount = maxNotificationFrames *
6681 max(kMinNotifications, minNotificationsByMs);
6682 frameCount = max(frameCount, minFrameCount);
6683 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6684 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006685 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006686 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006687 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006688
Glenn Kasten15e57982013-09-24 11:52:37 -07006689 lStatus = initCheck();
6690 if (lStatus != NO_ERROR) {
6691 ALOGE("createRecordTrack_l() audio driver not initialized");
6692 goto Exit;
6693 }
Eric Laurent81784c32012-11-19 14:55:58 -08006694
6695 { // scope for mLock
6696 Mutex::Autolock _l(mLock);
6697
6698 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006699 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006700 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006701
Glenn Kasten03003332013-08-06 15:40:54 -07006702 lStatus = track->initCheck();
6703 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006704 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006705 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006706 goto Exit;
6707 }
6708 mTracks.add(track);
6709
Eric Laurent05067782016-06-01 18:27:28 -07006710 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006711 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6712 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6713 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006714 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006715 }
Eric Laurent81784c32012-11-19 14:55:58 -08006716 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006717
Eric Laurent81784c32012-11-19 14:55:58 -08006718 lStatus = NO_ERROR;
6719
6720Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006721 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006722 return track;
6723}
6724
6725status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6726 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006727 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006728{
6729 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6730 sp<ThreadBase> strongMe = this;
6731 status_t status = NO_ERROR;
6732
6733 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006734 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006735 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006736 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006737 triggerSession,
6738 recordTrack->sessionId(),
6739 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006740 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006741 // Sync event can be cancelled by the trigger session if the track is not in a
6742 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006743 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006744 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006745 } else {
6746 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006747 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006748 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006749 }
6750 }
6751
6752 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006753 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006754 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006755 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6756 if (recordTrack->mState == TrackBase::PAUSING) {
6757 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006758 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006759 } else {
6760 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006761 }
6762 return status;
6763 }
6764
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006765 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6766 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6767 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006768 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006769 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006770 status_t status = NO_ERROR;
6771 if (recordTrack->isExternalTrack()) {
6772 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006773 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006774 mLock.lock();
6775 // FIXME should verify that recordTrack is still in mActiveTracks
6776 if (status != NO_ERROR) {
6777 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006778 recordTrack->clearSyncStartEvent();
6779 ALOGV("RecordThread::start error %d", status);
6780 return status;
6781 }
Eric Laurent81784c32012-11-19 14:55:58 -08006782 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006783 // Catch up with current buffer indices if thread is already running.
6784 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6785 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6786 // see previously buffered data before it called start(), but with greater risk of overrun.
6787
Andy Hung73c02e42015-03-29 01:13:58 -07006788 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006789 // clear any converter state as new data will be discontinuous
6790 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006791 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006792 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006793 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006794 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006795 ALOGV("Record failed to start");
6796 status = BAD_VALUE;
6797 goto startError;
6798 }
Eric Laurent81784c32012-11-19 14:55:58 -08006799 return status;
6800 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006801
Eric Laurent81784c32012-11-19 14:55:58 -08006802startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006803 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006804 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006805 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006806 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006807 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006808 return status;
6809}
6810
Eric Laurent81784c32012-11-19 14:55:58 -08006811void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6812{
6813 sp<SyncEvent> strongEvent = event.promote();
6814
6815 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006816 sp<RefBase> ptr = strongEvent->cookie().promote();
6817 if (ptr != 0) {
6818 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6819 recordTrack->handleSyncStartEvent(strongEvent);
6820 }
Eric Laurent81784c32012-11-19 14:55:58 -08006821 }
6822}
6823
Glenn Kastena8356f62013-07-25 14:37:52 -07006824bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006825 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006826 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006827 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006828 return false;
6829 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006830 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006831 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006832 // signal thread to stop
6833 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006834 // do not wait for mStartStopCond if exiting
6835 if (exitPending()) {
6836 return true;
6837 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006838 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006839 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006840 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006841 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006842 ALOGV("Record stopped OK");
6843 return true;
6844 }
6845 return false;
6846}
6847
Glenn Kasten0f11b512014-01-31 16:18:54 -08006848bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006849{
6850 return false;
6851}
6852
Glenn Kasten0f11b512014-01-31 16:18:54 -08006853status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006854{
6855#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6856 if (!isValidSyncEvent(event)) {
6857 return BAD_VALUE;
6858 }
6859
Glenn Kastend848eb42016-03-08 13:42:11 -08006860 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006861 status_t ret = NAME_NOT_FOUND;
6862
6863 Mutex::Autolock _l(mLock);
6864
6865 for (size_t i = 0; i < mTracks.size(); i++) {
6866 sp<RecordTrack> track = mTracks[i];
6867 if (eventSession == track->sessionId()) {
6868 (void) track->setSyncEvent(event);
6869 ret = NO_ERROR;
6870 }
6871 }
6872 return ret;
6873#else
6874 return BAD_VALUE;
6875#endif
6876}
6877
6878// destroyTrack_l() must be called with ThreadBase::mLock held
6879void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6880{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006881 track->terminate();
6882 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006883 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006884 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006885 removeTrack_l(track);
6886 }
6887}
6888
6889void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6890{
6891 mTracks.remove(track);
6892 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006893 if (track->isFastTrack()) {
6894 ALOG_ASSERT(!mFastTrackAvail);
6895 mFastTrackAvail = true;
6896 }
Eric Laurent81784c32012-11-19 14:55:58 -08006897}
6898
6899void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6900{
6901 dumpInternals(fd, args);
6902 dumpTracks(fd, args);
6903 dumpEffectChains(fd, args);
6904}
6905
6906void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6907{
Glenn Kasten44182c22015-03-05 17:12:23 -08006908 dumpBase(fd, args);
6909
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006910 AudioStreamIn *input = mInput;
6911 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6912 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6913 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006914 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006915 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006917 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006918 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006919
Glenn Kasten2f90c512015-12-02 11:40:09 -08006920 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6921 // while we are dumping it. It may be inconsistent, but it won't mutate!
6922 // This is a large object so we place it on the heap.
6923 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6924 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6925 copy->dump(fd);
6926 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006927}
6928
Glenn Kasten0f11b512014-01-31 16:18:54 -08006929void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006930{
6931 const size_t SIZE = 256;
6932 char buffer[SIZE];
6933 String8 result;
6934
Marco Nelissenb2208842014-02-07 14:00:50 -08006935 size_t numtracks = mTracks.size();
6936 size_t numactive = mActiveTracks.size();
6937 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006938 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006939 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006940 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006941 RecordTrack::appendDumpHeader(result);
6942 for (size_t i = 0; i < numtracks ; ++i) {
6943 sp<RecordTrack> track = mTracks[i];
6944 if (track != 0) {
6945 bool active = mActiveTracks.indexOf(track) >= 0;
6946 if (active) {
6947 numactiveseen++;
6948 }
6949 track->dump(buffer, SIZE, active);
6950 result.append(buffer);
6951 }
Eric Laurent81784c32012-11-19 14:55:58 -08006952 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006953 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006954 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006955 }
6956
Marco Nelissenb2208842014-02-07 14:00:50 -08006957 if (numactiveseen != numactive) {
6958 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6959 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006960 result.append(buffer);
6961 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006962 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006963 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006964 if (mTracks.indexOf(track) < 0) {
6965 track->dump(buffer, SIZE, true);
6966 result.append(buffer);
6967 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006968 }
Eric Laurent81784c32012-11-19 14:55:58 -08006969
6970 }
6971 write(fd, result.string(), result.size());
6972}
6973
Andy Hung73c02e42015-03-29 01:13:58 -07006974
6975void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6976{
6977 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6978 RecordThread *recordThread = (RecordThread *) threadBase.get();
6979 mRsmpInFront = recordThread->mRsmpInRear;
6980 mRsmpInUnrel = 0;
6981}
6982
6983void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6984 size_t *framesAvailable, bool *hasOverrun)
6985{
6986 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6987 RecordThread *recordThread = (RecordThread *) threadBase.get();
6988 const int32_t rear = recordThread->mRsmpInRear;
6989 const int32_t front = mRsmpInFront;
6990 const ssize_t filled = rear - front;
6991
6992 size_t framesIn;
6993 bool overrun = false;
6994 if (filled < 0) {
6995 // should not happen, but treat like a massive overrun and re-sync
6996 framesIn = 0;
6997 mRsmpInFront = rear;
6998 overrun = true;
6999 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7000 framesIn = (size_t) filled;
7001 } else {
7002 // client is not keeping up with server, but give it latest data
7003 framesIn = recordThread->mRsmpInFrames;
7004 mRsmpInFront = /* front = */ rear - framesIn;
7005 overrun = true;
7006 }
7007 if (framesAvailable != NULL) {
7008 *framesAvailable = framesIn;
7009 }
7010 if (hasOverrun != NULL) {
7011 *hasOverrun = overrun;
7012 }
7013}
7014
Eric Laurent81784c32012-11-19 14:55:58 -08007015// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007016status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007017 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007018{
Andy Hung73c02e42015-03-29 01:13:58 -07007019 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007020 if (threadBase == 0) {
7021 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007022 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007023 return NOT_ENOUGH_DATA;
7024 }
7025 RecordThread *recordThread = (RecordThread *) threadBase.get();
7026 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007027 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007028 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007029 // FIXME should not be P2 (don't want to increase latency)
7030 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007031 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007032 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007033 front &= recordThread->mRsmpInFramesP2 - 1;
7034 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007035 if (part1 > (size_t) filled) {
7036 part1 = filled;
7037 }
7038 size_t ask = buffer->frameCount;
7039 ALOG_ASSERT(ask > 0);
7040 if (part1 > ask) {
7041 part1 = ask;
7042 }
7043 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007044 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007045 buffer->raw = NULL;
7046 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007047 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007048 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007049 }
7050
Andy Hung57446612015-04-19 23:56:46 -07007051 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007052 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007053 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007054 return NO_ERROR;
7055}
7056
7057// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007058void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7059 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007060{
Glenn Kasten85948432013-08-19 12:09:05 -07007061 size_t stepCount = buffer->frameCount;
7062 if (stepCount == 0) {
7063 return;
7064 }
Andy Hung73c02e42015-03-29 01:13:58 -07007065 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7066 mRsmpInUnrel -= stepCount;
7067 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007068 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007069 buffer->frameCount = 0;
7070}
7071
Eric Laurentd8365c52017-07-16 15:27:05 -07007072void AudioFlinger::RecordThread::checkBtNrec()
7073{
7074 Mutex::Autolock _l(mLock);
7075 checkBtNrec_l();
7076}
7077
7078void AudioFlinger::RecordThread::checkBtNrec_l()
7079{
7080 // disable AEC and NS if the device is a BT SCO headset supporting those
7081 // pre processings
7082 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7083 mAudioFlinger->btNrecIsOff();
7084 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7085 for (size_t i = 0; i < mEffectChains.size(); i++) {
7086 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7087 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7088 }
7089 }
7090}
7091
Andy Hung97a893e2015-03-29 01:03:07 -07007092
Eric Laurent10351942014-05-08 18:49:52 -07007093bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7094 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007095{
7096 bool reconfig = false;
7097
Eric Laurent10351942014-05-08 18:49:52 -07007098 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007099
Eric Laurent10351942014-05-08 18:49:52 -07007100 audio_format_t reqFormat = mFormat;
7101 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007102 // 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 -07007103 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7104
7105 AudioParameter param = AudioParameter(keyValuePair);
7106 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007107
7108 // scope for AutoPark extends to end of method
7109 AutoPark<FastCapture> park(mFastCapture);
7110
Eric Laurent10351942014-05-08 18:49:52 -07007111 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7112 // channel count change can be requested. Do we mandate the first client defines the
7113 // HAL sampling rate and channel count or do we allow changes on the fly?
7114 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7115 samplingRate = value;
7116 reconfig = true;
7117 }
7118 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007119 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007120 status = BAD_VALUE;
7121 } else {
7122 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007123 reconfig = true;
7124 }
Eric Laurent10351942014-05-08 18:49:52 -07007125 }
7126 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7127 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007128 if (!audio_is_input_channel(mask) ||
7129 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007130 status = BAD_VALUE;
7131 } else {
7132 channelMask = mask;
7133 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007134 }
Eric Laurent10351942014-05-08 18:49:52 -07007135 }
7136 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7137 // do not accept frame count changes if tracks are open as the track buffer
7138 // size depends on frame count and correct behavior would not be guaranteed
7139 // if frame count is changed after track creation
7140 if (mActiveTracks.size() > 0) {
7141 status = INVALID_OPERATION;
7142 } else {
7143 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007144 }
Eric Laurent10351942014-05-08 18:49:52 -07007145 }
7146 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7147 // forward device change to effects that have requested to be
7148 // aware of attached audio device.
7149 for (size_t i = 0; i < mEffectChains.size(); i++) {
7150 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007151 }
Eric Laurent81784c32012-11-19 14:55:58 -08007152
Eric Laurent10351942014-05-08 18:49:52 -07007153 // store input device and output device but do not forward output device to audio HAL.
7154 // Note that status is ignored by the caller for output device
7155 // (see AudioFlinger::setParameters()
7156 if (audio_is_output_devices(value)) {
7157 mOutDevice = value;
7158 status = BAD_VALUE;
7159 } else {
7160 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007161 if (value != AUDIO_DEVICE_NONE) {
7162 mPrevInDevice = value;
7163 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007164 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007165 }
Eric Laurent10351942014-05-08 18:49:52 -07007166 }
7167 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7168 mAudioSource != (audio_source_t)value) {
7169 // forward device change to effects that have requested to be
7170 // aware of attached audio device.
7171 for (size_t i = 0; i < mEffectChains.size(); i++) {
7172 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007173 }
Eric Laurent10351942014-05-08 18:49:52 -07007174 mAudioSource = (audio_source_t)value;
7175 }
Glenn Kastene198c362013-08-13 09:13:36 -07007176
Eric Laurent10351942014-05-08 18:49:52 -07007177 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007178 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007179 if (status == INVALID_OPERATION) {
7180 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007181 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007182 }
7183 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007184 if (status == BAD_VALUE) {
7185 uint32_t sRate;
7186 audio_channel_mask_t channelMask;
7187 audio_format_t format;
7188 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7189 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7190 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7191 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7192 status = NO_ERROR;
7193 }
Eric Laurent81784c32012-11-19 14:55:58 -08007194 }
Eric Laurent10351942014-05-08 18:49:52 -07007195 if (status == NO_ERROR) {
7196 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007197 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007198 }
7199 }
Eric Laurent81784c32012-11-19 14:55:58 -08007200 }
Eric Laurent10351942014-05-08 18:49:52 -07007201
Eric Laurent81784c32012-11-19 14:55:58 -08007202 return reconfig;
7203}
7204
7205String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7206{
Eric Laurent81784c32012-11-19 14:55:58 -08007207 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007208 if (initCheck() == NO_ERROR) {
7209 String8 out_s8;
7210 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7211 return out_s8;
7212 }
Eric Laurent81784c32012-11-19 14:55:58 -08007213 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007214 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007215}
7216
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007217void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007218 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7219
7220 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007221
7222 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007223 case AUDIO_INPUT_OPENED:
7224 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007225 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007226 desc->mChannelMask = mChannelMask;
7227 desc->mSamplingRate = mSampleRate;
7228 desc->mFormat = mFormat;
7229 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007230 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007231 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007232 break;
7233
Eric Laurent73e26b62015-04-27 16:55:58 -07007234 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007235 default:
7236 break;
7237 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007238 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007239}
7240
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007241void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007242{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007243 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7244 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007245 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007246 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007247 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007248 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7249 result = mInput->stream->getFrameSize(&mFrameSize);
7250 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7251 result = mInput->stream->getBufferSize(&mBufferSize);
7252 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007253 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007254 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7255 "mBufferSize=%lld, mFrameCount=%lld",
7256 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7257 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007258 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007259 // 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 -07007260 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007261 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007262 // A larger value should allow more old data to be read after a track calls start(),
7263 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007264 //
7265 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007266 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007267 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007268 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007269 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007270
7271 // TODO optimize audio capture buffer sizes ...
7272 // Here we calculate the size of the sliding buffer used as a source
7273 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7274 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7275 // be better to have it derived from the pipe depth in the long term.
7276 // The current value is higher than necessary. However it should not add to latency.
7277
Glenn Kasten85948432013-08-19 12:09:05 -07007278 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007279 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7280 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007281 // if posix_memalign fails, will segv here.
7282 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007283
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007284 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7285 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007286}
7287
Glenn Kasten5f972c02014-01-13 09:59:31 -08007288uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007289{
7290 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007291 uint32_t result;
7292 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7293 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007294 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007295 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007296}
7297
Eric Laurent4c415062016-06-17 16:14:16 -07007298// hasAudioSession_l() must be called with ThreadBase::mLock held
7299uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007300{
Eric Laurent81784c32012-11-19 14:55:58 -08007301 uint32_t result = 0;
7302 if (getEffectChain_l(sessionId) != 0) {
7303 result = EFFECT_SESSION;
7304 }
7305
7306 for (size_t i = 0; i < mTracks.size(); ++i) {
7307 if (sessionId == mTracks[i]->sessionId()) {
7308 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007309 if (mTracks[i]->isFastTrack()) {
7310 result |= FAST_SESSION;
7311 }
Eric Laurent81784c32012-11-19 14:55:58 -08007312 break;
7313 }
7314 }
7315
7316 return result;
7317}
7318
Glenn Kastend848eb42016-03-08 13:42:11 -08007319KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007320{
Glenn Kastend848eb42016-03-08 13:42:11 -08007321 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007322 Mutex::Autolock _l(mLock);
7323 for (size_t j = 0; j < mTracks.size(); ++j) {
7324 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007325 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007326 if (ids.indexOfKey(sessionId) < 0) {
7327 ids.add(sessionId, true);
7328 }
7329 }
7330 return ids;
7331}
7332
7333AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7334{
7335 Mutex::Autolock _l(mLock);
7336 AudioStreamIn *input = mInput;
7337 mInput = NULL;
7338 return input;
7339}
7340
7341// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007342sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007343{
7344 if (mInput == NULL) {
7345 return NULL;
7346 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007347 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007348}
7349
7350status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7351{
7352 // only one chain per input thread
7353 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007354 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007355 return INVALID_OPERATION;
7356 }
7357 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007358 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007359 chain->setInBuffer(NULL);
7360 chain->setOutBuffer(NULL);
7361
7362 checkSuspendOnAddEffectChain_l(chain);
7363
Eric Laurent1b928682014-10-02 19:41:47 -07007364 // make sure enabled pre processing effects state is communicated to the HAL as we
7365 // just moved them to a new input stream.
7366 chain->syncHalEffectsState();
7367
Eric Laurent81784c32012-11-19 14:55:58 -08007368 mEffectChains.add(chain);
7369
7370 return NO_ERROR;
7371}
7372
7373size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7374{
7375 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7376 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007377 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007378 chain.get(), mEffectChains.size(), this);
7379 if (mEffectChains.size() == 1) {
7380 mEffectChains.removeAt(0);
7381 }
7382 return 0;
7383}
7384
Eric Laurent1c333e22014-05-20 10:48:17 -07007385status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7386 audio_patch_handle_t *handle)
7387{
7388 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007389
7390 // store new device and send to effects
7391 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007392 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007393 for (size_t i = 0; i < mEffectChains.size(); i++) {
7394 mEffectChains[i]->setDevice_l(mInDevice);
7395 }
7396
Eric Laurentd8365c52017-07-16 15:27:05 -07007397 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007398
7399 // store new source and send to effects
7400 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7401 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007402 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007403 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007404 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007405 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007406
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007407 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007408 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7409 status = hwDevice->createAudioPatch(patch->num_sources,
7410 patch->sources,
7411 patch->num_sinks,
7412 patch->sinks,
7413 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007414 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007415 char *address;
7416 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7417 address = audio_device_address_to_parameter(
7418 patch->sources[0].ext.device.type,
7419 patch->sources[0].ext.device.address);
7420 } else {
7421 address = (char *)calloc(1, 1);
7422 }
7423 AudioParameter param = AudioParameter(String8(address));
7424 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007425 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007426 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007427 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007428 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007429 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007430 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007431 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007432
Eric Laurente8726fe2015-06-26 09:39:24 -07007433 if (mInDevice != mPrevInDevice) {
7434 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7435 mPrevInDevice = mInDevice;
7436 }
Eric Laurent296fb132015-05-01 11:38:42 -07007437
Eric Laurent1c333e22014-05-20 10:48:17 -07007438 return status;
7439}
7440
7441status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7442{
7443 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007444
7445 mInDevice = AUDIO_DEVICE_NONE;
7446
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007447 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007448 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7449 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007450 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007451 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007452 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007453 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007454 }
7455 return status;
7456}
7457
Eric Laurent83b88082014-06-20 18:31:16 -07007458void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7459{
7460 Mutex::Autolock _l(mLock);
7461 mTracks.add(record);
7462}
7463
7464void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7465{
7466 Mutex::Autolock _l(mLock);
7467 destroyTrack_l(record);
7468}
7469
7470void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7471{
7472 ThreadBase::getAudioPortConfig(config);
7473 config->role = AUDIO_PORT_ROLE_SINK;
7474 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7475 config->ext.mix.usecase.source = mAudioSource;
7476}
Eric Laurent1c333e22014-05-20 10:48:17 -07007477
Eric Laurent6acd1d42017-01-04 14:23:29 -08007478// ----------------------------------------------------------------------------
7479// Mmap
7480// ----------------------------------------------------------------------------
7481
7482AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7483 : mThread(thread)
7484{
7485}
7486
7487AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7488{
7489 MmapThread *thread = mThread.get();
7490 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007491 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007492 // and the thread removed from mMMapThreads list causing the thread destruction.
7493 mThread.clear();
7494 if (thread != nullptr) {
7495 thread->disconnect();
7496 }
7497}
7498
7499status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7500 struct audio_mmap_buffer_info *info)
7501{
7502 if (mThread == 0) {
7503 return NO_INIT;
7504 }
7505 return mThread->createMmapBuffer(minSizeFrames, info);
7506}
7507
7508status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7509{
7510 if (mThread == 0) {
7511 return NO_INIT;
7512 }
7513 return mThread->getMmapPosition(position);
7514}
7515
Eric Laurentcb4dae22017-07-01 19:39:32 -07007516status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007517 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007518
7519{
7520 if (mThread == 0) {
7521 return NO_INIT;
7522 }
7523 return mThread->start(client, handle);
7524}
7525
7526status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7527{
7528 if (mThread == 0) {
7529 return NO_INIT;
7530 }
7531 return mThread->stop(handle);
7532}
7533
Eric Laurent18b57012017-02-13 16:23:52 -08007534status_t AudioFlinger::MmapThreadHandle::standby()
7535{
7536 if (mThread == 0) {
7537 return NO_INIT;
7538 }
7539 return mThread->standby();
7540}
7541
Eric Laurent6acd1d42017-01-04 14:23:29 -08007542
7543AudioFlinger::MmapThread::MmapThread(
7544 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7545 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7546 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7547 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7548 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7549{
Eric Laurent18b57012017-02-13 16:23:52 -08007550 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007551 readHalParameters_l();
7552}
7553
7554AudioFlinger::MmapThread::~MmapThread()
7555{
Eric Laurent18b57012017-02-13 16:23:52 -08007556 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007557}
7558
7559void AudioFlinger::MmapThread::onFirstRef()
7560{
7561 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7562}
7563
7564void AudioFlinger::MmapThread::disconnect()
7565{
7566 for (const sp<MmapTrack> &t : mActiveTracks) {
7567 stop(t->portId());
7568 }
7569 // this will cause the destruction of this thread.
7570 if (isOutput()) {
7571 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7572 } else {
7573 AudioSystem::releaseInput(mId, mSessionId);
7574 }
7575}
7576
7577
7578void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7579 audio_stream_type_t streamType __unused,
7580 audio_session_t sessionId,
7581 const sp<MmapStreamCallback>& callback,
7582 audio_port_handle_t portId)
7583{
7584 mAttr = *attr;
7585 mSessionId = sessionId;
7586 mCallback = callback;
7587 mPortId = portId;
7588}
7589
7590status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7591 struct audio_mmap_buffer_info *info)
7592{
7593 if (mHalStream == 0) {
7594 return NO_INIT;
7595 }
Eric Laurent18b57012017-02-13 16:23:52 -08007596 mStandby = true;
7597 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007598 return mHalStream->createMmapBuffer(minSizeFrames, info);
7599}
7600
7601status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7602{
7603 if (mHalStream == 0) {
7604 return NO_INIT;
7605 }
7606 return mHalStream->getMmapPosition(position);
7607}
7608
Eric Laurentcb4dae22017-07-01 19:39:32 -07007609status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007610 audio_port_handle_t *handle)
7611{
Eric Laurentcb4dae22017-07-01 19:39:32 -07007612 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7613 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007614 if (mHalStream == 0) {
7615 return NO_INIT;
7616 }
7617
7618 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007619
Eric Laurentcb4dae22017-07-01 19:39:32 -07007620 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007621 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007622 ret = mHalStream->start();
7623 if (ret != NO_ERROR) {
7624 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7625 return ret;
7626 }
Eric Laurent18b57012017-02-13 16:23:52 -08007627 mStandby = false;
Eric Laurentcb4dae22017-07-01 19:39:32 -07007628 return NO_ERROR;
7629 }
7630
7631 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7632
7633 audio_io_handle_t io = mId;
7634 if (isOutput()) {
7635 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7636 config.sample_rate = mSampleRate;
7637 config.channel_mask = mChannelMask;
7638 config.format = mFormat;
7639 audio_stream_type_t stream = streamType();
7640 audio_output_flags_t flags =
7641 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7642 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7643 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7644 mSessionId,
7645 &stream,
7646 client.clientUid,
7647 &config,
7648 flags,
7649 &deviceId,
7650 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007651 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007652 audio_config_base_t config;
7653 config.sample_rate = mSampleRate;
7654 config.channel_mask = mChannelMask;
7655 config.format = mFormat;
7656 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7657 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7658 mSessionId,
7659 client.clientPid,
7660 client.clientUid,
7661 &config,
7662 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7663 &deviceId,
7664 &portId);
7665 }
7666 // APM should not chose a different input or output stream for the same set of attributes
7667 // and audo configuration
7668 if (ret != NO_ERROR || io != mId) {
7669 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7670 __FUNCTION__, ret, io, mId);
7671 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007672 }
7673
7674 if (isOutput()) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007675 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007676 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007677 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007678 }
7679
7680 // abort if start is rejected by audio policy manager
7681 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007682 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007683 if (mActiveTracks.size() != 0) {
7684 if (isOutput()) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007685 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007686 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007687 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007688 }
Eric Laurent18b57012017-02-13 16:23:52 -08007689 } else {
7690 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007691 }
7692 return PERMISSION_DENIED;
7693 }
7694
Eric Laurentcb4dae22017-07-01 19:39:32 -07007695 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007696 client.clientUid, portId);
7697
7698 mActiveTracks.add(track);
Eric Laurentcb4dae22017-07-01 19:39:32 -07007699 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007700 if (chain != 0) {
7701 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7702 chain->incTrackCnt();
7703 chain->incActiveTrackCnt();
7704 }
7705
7706 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007707 broadcast_l();
7708
Eric Laurentcb4dae22017-07-01 19:39:32 -07007709 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007710
7711 return NO_ERROR;
7712}
7713
7714status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7715{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007716 ALOGV("%s handle %d", __FUNCTION__, handle);
7717
7718 if (mHalStream == 0) {
7719 return NO_INIT;
7720 }
7721
Eric Laurentcb4dae22017-07-01 19:39:32 -07007722 if (handle == mPortId) {
7723 mHalStream->stop();
7724 return NO_ERROR;
7725 }
7726
Eric Laurent6acd1d42017-01-04 14:23:29 -08007727 sp<MmapTrack> track;
7728 for (const sp<MmapTrack> &t : mActiveTracks) {
7729 if (handle == t->portId()) {
7730 track = t;
7731 break;
7732 }
7733 }
7734 if (track == 0) {
7735 return BAD_VALUE;
7736 }
7737
7738 mActiveTracks.remove(track);
7739
7740 if (isOutput()) {
7741 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurentcb4dae22017-07-01 19:39:32 -07007742 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007743 } else {
7744 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurentcb4dae22017-07-01 19:39:32 -07007745 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007746 }
7747
7748 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7749 if (chain != 0) {
7750 chain->decActiveTrackCnt();
7751 chain->decTrackCnt();
7752 }
7753
7754 broadcast_l();
7755
Eric Laurent6acd1d42017-01-04 14:23:29 -08007756 return NO_ERROR;
7757}
7758
Eric Laurent18b57012017-02-13 16:23:52 -08007759status_t AudioFlinger::MmapThread::standby()
7760{
7761 ALOGV("%s", __FUNCTION__);
7762
7763 if (mHalStream == 0) {
7764 return NO_INIT;
7765 }
7766 if (mActiveTracks.size() != 0) {
7767 return INVALID_OPERATION;
7768 }
7769 mHalStream->standby();
7770 mStandby = true;
7771 releaseWakeLock();
7772 return NO_ERROR;
7773}
7774
Eric Laurent6acd1d42017-01-04 14:23:29 -08007775
7776void AudioFlinger::MmapThread::readHalParameters_l()
7777{
7778 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7779 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7780 mFormat = mHALFormat;
7781 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7782 result = mHalStream->getFrameSize(&mFrameSize);
7783 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7784 result = mHalStream->getBufferSize(&mBufferSize);
7785 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7786 mFrameCount = mBufferSize / mFrameSize;
7787}
7788
7789bool AudioFlinger::MmapThread::threadLoop()
7790{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007791 checkSilentMode_l();
7792
7793 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7794
7795 while (!exitPending())
7796 {
7797 Mutex::Autolock _l(mLock);
7798 Vector< sp<EffectChain> > effectChains;
7799
7800 if (mSignalPending) {
7801 // A signal was raised while we were unlocked
7802 mSignalPending = false;
7803 } else {
7804 if (mConfigEvents.isEmpty()) {
7805 // we're about to wait, flush the binder command buffer
7806 IPCThreadState::self()->flushCommands();
7807
7808 if (exitPending()) {
7809 break;
7810 }
7811
Eric Laurent6acd1d42017-01-04 14:23:29 -08007812 // wait until we have something to do...
7813 ALOGV("%s going to sleep", myName.string());
7814 mWaitWorkCV.wait(mLock);
7815 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007816
7817 checkSilentMode_l();
7818
7819 continue;
7820 }
7821 }
7822
7823 processConfigEvents_l();
7824
7825 processVolume_l();
7826
7827 checkInvalidTracks_l();
7828
7829 mActiveTracks.updatePowerState(this);
7830
7831 lockEffectChains_l(effectChains);
7832 for (size_t i = 0; i < effectChains.size(); i ++) {
7833 effectChains[i]->process_l();
7834 }
7835 // enable changes in effect chain
7836 unlockEffectChains(effectChains);
7837 // Effect chains will be actually deleted here if they were removed from
7838 // mEffectChains list during mixing or effects processing
7839 }
7840
7841 threadLoop_exit();
7842
7843 if (!mStandby) {
7844 threadLoop_standby();
7845 mStandby = true;
7846 }
7847
Eric Laurent6acd1d42017-01-04 14:23:29 -08007848 ALOGV("Thread %p type %d exiting", this, mType);
7849 return false;
7850}
7851
7852// checkForNewParameter_l() must be called with ThreadBase::mLock held
7853bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7854 status_t& status)
7855{
7856 AudioParameter param = AudioParameter(keyValuePair);
7857 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07007858 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007859 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007860 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007861 // forward device change to effects that have requested to be
7862 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07007863 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007864 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007865 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007866 }
7867 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007868 if (audio_is_output_devices(device)) {
7869 mOutDevice = device;
7870 if (!isOutput()) {
7871 sendToHal = false;
7872 }
7873 } else {
7874 mInDevice = device;
7875 if (device != AUDIO_DEVICE_NONE) {
7876 mPrevInDevice = value;
7877 }
7878 // TODO: implement and call checkBtNrec_l();
7879 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007880 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007881 if (sendToHal) {
7882 status = mHalStream->setParameters(keyValuePair);
7883 } else {
7884 status = NO_ERROR;
7885 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007886
7887 return false;
7888}
7889
7890String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7891{
7892 Mutex::Autolock _l(mLock);
7893 String8 out_s8;
7894 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7895 return out_s8;
7896 }
7897 return String8();
7898}
7899
7900void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7901 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7902
7903 desc->mIoHandle = mId;
7904
7905 switch (event) {
7906 case AUDIO_INPUT_OPENED:
7907 case AUDIO_INPUT_CONFIG_CHANGED:
7908 case AUDIO_OUTPUT_OPENED:
7909 case AUDIO_OUTPUT_CONFIG_CHANGED:
7910 desc->mPatch = mPatch;
7911 desc->mChannelMask = mChannelMask;
7912 desc->mSamplingRate = mSampleRate;
7913 desc->mFormat = mFormat;
7914 desc->mFrameCount = mFrameCount;
7915 desc->mFrameCountHAL = mFrameCount;
7916 desc->mLatency = 0;
7917 break;
7918
7919 case AUDIO_INPUT_CLOSED:
7920 case AUDIO_OUTPUT_CLOSED:
7921 default:
7922 break;
7923 }
7924 mAudioFlinger->ioConfigChanged(event, desc, pid);
7925}
7926
7927status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7928 audio_patch_handle_t *handle)
7929{
7930 status_t status = NO_ERROR;
7931
7932 // store new device and send to effects
7933 audio_devices_t type = AUDIO_DEVICE_NONE;
7934 audio_port_handle_t deviceId;
7935 if (isOutput()) {
7936 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7937 type |= patch->sinks[i].ext.device.type;
7938 }
7939 deviceId = patch->sinks[0].id;
7940 } else {
7941 type = patch->sources[0].ext.device.type;
7942 deviceId = patch->sources[0].id;
7943 }
7944
7945 for (size_t i = 0; i < mEffectChains.size(); i++) {
7946 mEffectChains[i]->setDevice_l(type);
7947 }
7948
7949 if (isOutput()) {
7950 mOutDevice = type;
7951 } else {
7952 mInDevice = type;
7953 // store new source and send to effects
7954 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7955 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7956 for (size_t i = 0; i < mEffectChains.size(); i++) {
7957 mEffectChains[i]->setAudioSource_l(mAudioSource);
7958 }
7959 }
7960 }
7961
7962 if (mAudioHwDev->supportsAudioPatches()) {
7963 status = mHalDevice->createAudioPatch(patch->num_sources,
7964 patch->sources,
7965 patch->num_sinks,
7966 patch->sinks,
7967 handle);
7968 } else {
7969 char *address;
7970 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7971 //FIXME: we only support address on first sink with HAL version < 3.0
7972 address = audio_device_address_to_parameter(
7973 patch->sinks[0].ext.device.type,
7974 patch->sinks[0].ext.device.address);
7975 } else {
7976 address = (char *)calloc(1, 1);
7977 }
7978 AudioParameter param = AudioParameter(String8(address));
7979 free(address);
7980 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7981 if (!isOutput()) {
7982 param.addInt(String8(AudioParameter::keyInputSource),
7983 (int)patch->sinks[0].ext.mix.usecase.source);
7984 }
7985 status = mHalStream->setParameters(param.toString());
7986 *handle = AUDIO_PATCH_HANDLE_NONE;
7987 }
7988
7989 if (isOutput() && mPrevOutDevice != mOutDevice) {
7990 mPrevOutDevice = type;
7991 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007992 sp<MmapStreamCallback> callback = mCallback.promote();
7993 if (callback != 0) {
7994 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007995 }
7996 }
7997 if (!isOutput() && mPrevInDevice != mInDevice) {
7998 mPrevInDevice = type;
7999 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008000 sp<MmapStreamCallback> callback = mCallback.promote();
8001 if (callback != 0) {
8002 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008003 }
8004 }
8005 return status;
8006}
8007
8008status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8009{
8010 status_t status = NO_ERROR;
8011
8012 mInDevice = AUDIO_DEVICE_NONE;
8013
8014 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8015 supportsAudioPatches : false;
8016
8017 if (supportsAudioPatches) {
8018 status = mHalDevice->releaseAudioPatch(handle);
8019 } else {
8020 AudioParameter param;
8021 param.addInt(String8(AudioParameter::keyRouting), 0);
8022 status = mHalStream->setParameters(param.toString());
8023 }
8024 return status;
8025}
8026
8027void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8028{
8029 ThreadBase::getAudioPortConfig(config);
8030 if (isOutput()) {
8031 config->role = AUDIO_PORT_ROLE_SOURCE;
8032 config->ext.mix.hw_module = mAudioHwDev->handle();
8033 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8034 } else {
8035 config->role = AUDIO_PORT_ROLE_SINK;
8036 config->ext.mix.hw_module = mAudioHwDev->handle();
8037 config->ext.mix.usecase.source = mAudioSource;
8038 }
8039}
8040
8041status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8042{
8043 audio_session_t session = chain->sessionId();
8044
8045 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8046 // Attach all tracks with same session ID to this chain.
8047 // indicate all active tracks in the chain
8048 for (const sp<MmapTrack> &track : mActiveTracks) {
8049 if (session == track->sessionId()) {
8050 chain->incTrackCnt();
8051 chain->incActiveTrackCnt();
8052 }
8053 }
8054
8055 chain->setThread(this);
8056 chain->setInBuffer(nullptr);
8057 chain->setOutBuffer(nullptr);
8058 chain->syncHalEffectsState();
8059
8060 mEffectChains.add(chain);
8061 checkSuspendOnAddEffectChain_l(chain);
8062 return NO_ERROR;
8063}
8064
8065size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8066{
8067 audio_session_t session = chain->sessionId();
8068
8069 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8070
8071 for (size_t i = 0; i < mEffectChains.size(); i++) {
8072 if (chain == mEffectChains[i]) {
8073 mEffectChains.removeAt(i);
8074 // detach all active tracks from the chain
8075 // detach all tracks with same session ID from this chain
8076 for (const sp<MmapTrack> &track : mActiveTracks) {
8077 if (session == track->sessionId()) {
8078 chain->decActiveTrackCnt();
8079 chain->decTrackCnt();
8080 }
8081 }
8082 break;
8083 }
8084 }
8085 return mEffectChains.size();
8086}
8087
8088// hasAudioSession_l() must be called with ThreadBase::mLock held
8089uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8090{
8091 uint32_t result = 0;
8092 if (getEffectChain_l(sessionId) != 0) {
8093 result = EFFECT_SESSION;
8094 }
8095
8096 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8097 sp<MmapTrack> track = mActiveTracks[i];
8098 if (sessionId == track->sessionId()) {
8099 result |= TRACK_SESSION;
8100 if (track->isFastTrack()) {
8101 result |= FAST_SESSION;
8102 }
8103 break;
8104 }
8105 }
8106
8107 return result;
8108}
8109
8110void AudioFlinger::MmapThread::threadLoop_standby()
8111{
8112 mHalStream->standby();
8113}
8114
8115void AudioFlinger::MmapThread::threadLoop_exit()
8116{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008117 sp<MmapStreamCallback> callback = mCallback.promote();
8118 if (callback != 0) {
8119 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008120 }
8121}
8122
8123status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8124{
8125 return BAD_VALUE;
8126}
8127
8128bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8129{
8130 return false;
8131}
8132
8133status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8134 const effect_descriptor_t *desc, audio_session_t sessionId)
8135{
8136 // No global effect sessions on mmap threads
8137 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8138 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8139 desc->name, mThreadName);
8140 return BAD_VALUE;
8141 }
8142
8143 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8144 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8145 desc->name);
8146 return BAD_VALUE;
8147 }
8148 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008149 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8150 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008151 return BAD_VALUE;
8152 }
8153
8154 // Only allow effects without processing load or latency
8155 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8156 return BAD_VALUE;
8157 }
8158
8159 return NO_ERROR;
8160
8161}
8162
8163void AudioFlinger::MmapThread::checkInvalidTracks_l()
8164{
8165 for (const sp<MmapTrack> &track : mActiveTracks) {
8166 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008167 sp<MmapStreamCallback> callback = mCallback.promote();
8168 if (callback != 0) {
8169 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008170 }
8171 break;
8172 }
8173 }
8174}
8175
8176void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8177{
8178 dumpInternals(fd, args);
8179 dumpTracks(fd, args);
8180 dumpEffectChains(fd, args);
8181}
8182
8183void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8184{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008185 dumpBase(fd, args);
8186
8187 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8188 mAttr.content_type, mAttr.usage, mAttr.source);
8189 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8190 if (mActiveTracks.size() == 0) {
8191 dprintf(fd, " No active clients\n");
8192 }
8193}
8194
8195void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8196{
8197 const size_t SIZE = 256;
8198 char buffer[SIZE];
8199 String8 result;
8200
8201 size_t numtracks = mActiveTracks.size();
8202 dprintf(fd, " %zu Tracks", numtracks);
8203 if (numtracks) {
8204 MmapTrack::appendDumpHeader(result);
8205 for (size_t i = 0; i < numtracks ; ++i) {
8206 sp<MmapTrack> track = mActiveTracks[i];
8207 track->dump(buffer, SIZE);
8208 result.append(buffer);
8209 }
8210 } else {
8211 dprintf(fd, "\n");
8212 }
8213 write(fd, result.string(), result.size());
8214}
8215
8216AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8217 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8218 AudioHwDevice *hwDev, AudioStreamOut *output,
8219 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8220 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8221 mStreamType(AUDIO_STREAM_MUSIC),
8222 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8223{
8224 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8225 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8226 mMasterVolume = audioFlinger->masterVolume_l();
8227 mMasterMute = audioFlinger->masterMute_l();
8228 if (mAudioHwDev) {
8229 if (mAudioHwDev->canSetMasterVolume()) {
8230 mMasterVolume = 1.0;
8231 }
8232
8233 if (mAudioHwDev->canSetMasterMute()) {
8234 mMasterMute = false;
8235 }
8236 }
8237}
8238
8239void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8240 audio_stream_type_t streamType,
8241 audio_session_t sessionId,
8242 const sp<MmapStreamCallback>& callback,
8243 audio_port_handle_t portId)
8244{
8245 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8246 mStreamType = streamType;
8247}
8248
8249AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8250{
8251 Mutex::Autolock _l(mLock);
8252 AudioStreamOut *output = mOutput;
8253 mOutput = NULL;
8254 return output;
8255}
8256
8257void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8258{
8259 Mutex::Autolock _l(mLock);
8260 // Don't apply master volume in SW if our HAL can do it for us.
8261 if (mAudioHwDev &&
8262 mAudioHwDev->canSetMasterVolume()) {
8263 mMasterVolume = 1.0;
8264 } else {
8265 mMasterVolume = value;
8266 }
8267}
8268
8269void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8270{
8271 Mutex::Autolock _l(mLock);
8272 // Don't apply master mute in SW if our HAL can do it for us.
8273 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8274 mMasterMute = false;
8275 } else {
8276 mMasterMute = muted;
8277 }
8278}
8279
8280void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8281{
8282 Mutex::Autolock _l(mLock);
8283 if (stream == mStreamType) {
8284 mStreamVolume = value;
8285 broadcast_l();
8286 }
8287}
8288
8289float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8290{
8291 Mutex::Autolock _l(mLock);
8292 if (stream == mStreamType) {
8293 return mStreamVolume;
8294 }
8295 return 0.0f;
8296}
8297
8298void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8299{
8300 Mutex::Autolock _l(mLock);
8301 if (stream == mStreamType) {
8302 mStreamMute= muted;
8303 broadcast_l();
8304 }
8305}
8306
8307void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8308{
8309 Mutex::Autolock _l(mLock);
8310 if (streamType == mStreamType) {
8311 for (const sp<MmapTrack> &track : mActiveTracks) {
8312 track->invalidate();
8313 }
8314 broadcast_l();
8315 }
8316}
8317
8318void AudioFlinger::MmapPlaybackThread::processVolume_l()
8319{
8320 float volume;
8321
8322 if (mMasterMute || mStreamMute) {
8323 volume = 0;
8324 } else {
8325 volume = mMasterVolume * mStreamVolume;
8326 }
8327
8328 if (volume != mHalVolFloat) {
8329 mHalVolFloat = volume;
8330
8331 // Convert volumes from float to 8.24
8332 uint32_t vol = (uint32_t)(volume * (1 << 24));
8333
8334 // Delegate volume control to effect in track effect chain if needed
8335 // only one effect chain can be present on DirectOutputThread, so if
8336 // there is one, the track is connected to it
8337 if (!mEffectChains.isEmpty()) {
8338 mEffectChains[0]->setVolume_l(&vol, &vol);
8339 volume = (float)vol / (1 << 24);
8340 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008341 // Try to use HW volume control and fall back to SW control if not implemented
8342 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8343 sp<MmapStreamCallback> callback = mCallback.promote();
8344 if (callback != 0) {
8345 int channelCount;
8346 if (isOutput()) {
8347 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8348 } else {
8349 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8350 }
8351 Vector<float> values;
8352 for (int i = 0; i < channelCount; i++) {
8353 values.add(volume);
8354 }
8355 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008356 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008357 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008358 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008359 }
8360 }
8361}
8362
8363void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8364{
8365 if (!mMasterMute) {
8366 char value[PROPERTY_VALUE_MAX];
8367 if (property_get("ro.audio.silent", value, "0") > 0) {
8368 char *endptr;
8369 unsigned long ul = strtoul(value, &endptr, 0);
8370 if (*endptr == '\0' && ul != 0) {
8371 ALOGD("Silence is golden");
8372 // The setprop command will not allow a property to be changed after
8373 // the first time it is set, so we don't have to worry about un-muting.
8374 setMasterMute_l(true);
8375 }
8376 }
8377 }
8378}
8379
8380void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8381{
8382 MmapThread::dumpInternals(fd, args);
8383
Glenn Kastend3bb6452016-12-05 18:14:37 -08008384 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8385 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008386 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8387}
8388
8389AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8390 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8391 AudioHwDevice *hwDev, AudioStreamIn *input,
8392 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8393 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8394 mInput(input)
8395{
8396 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8397 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8398}
8399
8400AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8401{
8402 Mutex::Autolock _l(mLock);
8403 AudioStreamIn *input = mInput;
8404 mInput = NULL;
8405 return input;
8406}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008407} // namespace android