blob: d9324839a95fcf3e5b4cdf974032afcf5b9a8c20 [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
994void AudioFlinger::ThreadBase::setEffectSuspended(
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 Mutex::Autolock _l(mLock);
998 setEffectSuspended_l(type, suspend, sessionId);
999}
1000
1001void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001002 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001003{
1004 sp<EffectChain> chain = getEffectChain_l(sessionId);
1005 if (chain != 0) {
1006 if (type != NULL) {
1007 chain->setEffectSuspended_l(type, suspend);
1008 } else {
1009 chain->setEffectSuspendedAll_l(suspend);
1010 }
1011 }
1012
1013 updateSuspendedSessions_l(type, suspend, sessionId);
1014}
1015
1016void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1017{
1018 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1019 if (index < 0) {
1020 return;
1021 }
1022
1023 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1024 mSuspendedSessions.valueAt(index);
1025
1026 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001027 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001028 for (int j = 0; j < desc->mRefCount; j++) {
1029 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1030 chain->setEffectSuspendedAll_l(true);
1031 } else {
1032 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1033 desc->mType.timeLow);
1034 chain->setEffectSuspended_l(&desc->mType, true);
1035 }
1036 }
1037 }
1038}
1039
1040void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1041 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001042 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001043{
1044 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1045
1046 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1047
1048 if (suspend) {
1049 if (index >= 0) {
1050 sessionEffects = mSuspendedSessions.valueAt(index);
1051 } else {
1052 mSuspendedSessions.add(sessionId, sessionEffects);
1053 }
1054 } else {
1055 if (index < 0) {
1056 return;
1057 }
1058 sessionEffects = mSuspendedSessions.valueAt(index);
1059 }
1060
1061
1062 int key = EffectChain::kKeyForSuspendAll;
1063 if (type != NULL) {
1064 key = type->timeLow;
1065 }
1066 index = sessionEffects.indexOfKey(key);
1067
1068 sp<SuspendedSessionDesc> desc;
1069 if (suspend) {
1070 if (index >= 0) {
1071 desc = sessionEffects.valueAt(index);
1072 } else {
1073 desc = new SuspendedSessionDesc();
1074 if (type != NULL) {
1075 desc->mType = *type;
1076 }
1077 sessionEffects.add(key, desc);
1078 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1079 }
1080 desc->mRefCount++;
1081 } else {
1082 if (index < 0) {
1083 return;
1084 }
1085 desc = sessionEffects.valueAt(index);
1086 if (--desc->mRefCount == 0) {
1087 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1088 sessionEffects.removeItemsAt(index);
1089 if (sessionEffects.isEmpty()) {
1090 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1091 sessionId);
1092 mSuspendedSessions.removeItem(sessionId);
1093 }
1094 }
1095 }
1096 if (!sessionEffects.isEmpty()) {
1097 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1098 }
1099}
1100
1101void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1102 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001103 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001104{
1105 Mutex::Autolock _l(mLock);
1106 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1107}
1108
1109void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1110 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001111 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001112{
1113 if (mType != RECORD) {
1114 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1115 // another session. This gives the priority to well behaved effect control panels
1116 // and applications not using global effects.
1117 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1118 // global effects
1119 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1120 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1121 }
1122 }
1123
1124 sp<EffectChain> chain = getEffectChain_l(sessionId);
1125 if (chain != 0) {
1126 chain->checkSuspendOnEffectEnabled(effect, enabled);
1127 }
1128}
1129
Eric Laurent4c415062016-06-17 16:14:16 -07001130// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1131status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1132 const effect_descriptor_t *desc, audio_session_t sessionId)
1133{
1134 // No global effect sessions on record threads
1135 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1136 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1137 desc->name, mThreadName);
1138 return BAD_VALUE;
1139 }
1140 // only pre processing effects on record thread
1141 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1142 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1143 desc->name, mThreadName);
1144 return BAD_VALUE;
1145 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001146
1147 // always allow effects without processing load or latency
1148 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1149 return NO_ERROR;
1150 }
1151
Eric Laurent4c415062016-06-17 16:14:16 -07001152 audio_input_flags_t flags = mInput->flags;
1153 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1154 if (flags & AUDIO_INPUT_FLAG_RAW) {
1155 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1156 desc->name, mThreadName);
1157 return BAD_VALUE;
1158 }
1159 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1160 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1161 desc->name, mThreadName);
1162 return BAD_VALUE;
1163 }
1164 }
1165 return NO_ERROR;
1166}
1167
1168// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1169status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1170 const effect_descriptor_t *desc, audio_session_t sessionId)
1171{
1172 // no preprocessing on playback threads
1173 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1174 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1175 " thread %s", desc->name, mThreadName);
1176 return BAD_VALUE;
1177 }
1178
1179 switch (mType) {
1180 case MIXER: {
1181 // Reject any effect on mixer multichannel sinks.
1182 // TODO: fix both format and multichannel issues with effects.
1183 if (mChannelCount != FCC_2) {
1184 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1185 " thread %s", desc->name, mChannelCount, mThreadName);
1186 return BAD_VALUE;
1187 }
1188 audio_output_flags_t flags = mOutput->flags;
1189 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1190 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1191 // global effects are applied only to non fast tracks if they are SW
1192 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1193 break;
1194 }
1195 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1196 // only post processing on output stage session
1197 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1198 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1199 " on output stage session", desc->name);
1200 return BAD_VALUE;
1201 }
1202 } else {
1203 // no restriction on effects applied on non fast tracks
1204 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1205 break;
1206 }
1207 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001208
1209 // always allow effects without processing load or latency
1210 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1211 break;
1212 }
Eric Laurent4c415062016-06-17 16:14:16 -07001213 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1214 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1215 desc->name);
1216 return BAD_VALUE;
1217 }
1218 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1219 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1220 " in fast mode", desc->name);
1221 return BAD_VALUE;
1222 }
1223 }
1224 } break;
1225 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001226 // nothing actionable on offload threads, if the effect:
1227 // - is offloadable: the effect can be created
1228 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1229 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001230 break;
1231 case DIRECT:
1232 // Reject any effect on Direct output threads for now, since the format of
1233 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1234 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1235 desc->name, mThreadName);
1236 return BAD_VALUE;
1237 case DUPLICATING:
1238 // Reject any effect on mixer multichannel sinks.
1239 // TODO: fix both format and multichannel issues with effects.
1240 if (mChannelCount != FCC_2) {
1241 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1242 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1243 return BAD_VALUE;
1244 }
1245 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1246 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1247 " thread %s", desc->name, mThreadName);
1248 return BAD_VALUE;
1249 }
1250 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1251 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1252 " DUPLICATING thread %s", desc->name, mThreadName);
1253 return BAD_VALUE;
1254 }
1255 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1256 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1257 " DUPLICATING thread %s", desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 break;
1261 default:
1262 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1263 }
1264
1265 return NO_ERROR;
1266}
1267
Eric Laurent81784c32012-11-19 14:55:58 -08001268// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1269sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1270 const sp<AudioFlinger::Client>& client,
1271 const sp<IEffectClient>& effectClient,
1272 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001273 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001274 effect_descriptor_t *desc,
1275 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001276 status_t *status,
1277 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001278{
1279 sp<EffectModule> effect;
1280 sp<EffectHandle> handle;
1281 status_t lStatus;
1282 sp<EffectChain> chain;
1283 bool chainCreated = false;
1284 bool effectCreated = false;
1285 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001286 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001287
1288 lStatus = initCheck();
1289 if (lStatus != NO_ERROR) {
1290 ALOGW("createEffect_l() Audio driver not initialized.");
1291 goto Exit;
1292 }
1293
Eric Laurent81784c32012-11-19 14:55:58 -08001294 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1295
1296 { // scope for mLock
1297 Mutex::Autolock _l(mLock);
1298
Eric Laurent4c415062016-06-17 16:14:16 -07001299 lStatus = checkEffectCompatibility_l(desc, sessionId);
1300 if (lStatus != NO_ERROR) {
1301 goto Exit;
1302 }
1303
Eric Laurent81784c32012-11-19 14:55:58 -08001304 // check for existing effect chain with the requested audio session
1305 chain = getEffectChain_l(sessionId);
1306 if (chain == 0) {
1307 // create a new chain for this session
1308 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1309 chain = new EffectChain(this, sessionId);
1310 addEffectChain_l(chain);
1311 chain->setStrategy(getStrategyForSession_l(sessionId));
1312 chainCreated = true;
1313 } else {
1314 effect = chain->getEffectFromDesc_l(desc);
1315 }
1316
1317 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1318
1319 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001320 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001321 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001322 lStatus = AudioSystem::registerEffect(
1323 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectRegistered = true;
1328 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001329 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001330 if (lStatus != NO_ERROR) {
1331 goto Exit;
1332 }
1333 effectCreated = true;
1334
1335 effect->setDevice(mOutDevice);
1336 effect->setDevice(mInDevice);
1337 effect->setMode(mAudioFlinger->getMode());
1338 effect->setAudioSource(mAudioSource);
1339 }
1340 // create effect handle and connect it to effect module
1341 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001342 lStatus = handle->initCheck();
1343 if (lStatus == OK) {
1344 lStatus = effect->addHandle(handle.get());
1345 }
Eric Laurent81784c32012-11-19 14:55:58 -08001346 if (enabled != NULL) {
1347 *enabled = (int)effect->isEnabled();
1348 }
1349 }
1350
1351Exit:
1352 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1353 Mutex::Autolock _l(mLock);
1354 if (effectCreated) {
1355 chain->removeEffect_l(effect);
1356 }
1357 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001358 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001359 }
1360 if (chainCreated) {
1361 removeEffectChain_l(chain);
1362 }
1363 handle.clear();
1364 }
1365
Glenn Kasten9156ef32013-08-06 15:39:08 -07001366 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001367 return handle;
1368}
1369
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001370void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1371 bool unpinIfLast)
1372{
1373 bool remove = false;
1374 sp<EffectModule> effect;
1375 {
1376 Mutex::Autolock _l(mLock);
1377
1378 effect = handle->effect().promote();
1379 if (effect == 0) {
1380 return;
1381 }
1382 // restore suspended effects if the disconnected handle was enabled and the last one.
1383 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1384 if (remove) {
1385 removeEffect_l(effect, true);
1386 }
1387 }
1388 if (remove) {
1389 mAudioFlinger->updateOrphanEffectChains(effect);
1390 AudioSystem::unregisterEffect(effect->id());
1391 if (handle->enabled()) {
1392 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1393 }
1394 }
1395}
1396
Glenn Kastend848eb42016-03-08 13:42:11 -08001397sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1398 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001399{
1400 Mutex::Autolock _l(mLock);
1401 return getEffect_l(sessionId, effectId);
1402}
1403
Glenn Kastend848eb42016-03-08 13:42:11 -08001404sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1405 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001406{
1407 sp<EffectChain> chain = getEffectChain_l(sessionId);
1408 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1409}
1410
1411// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1412// PlaybackThread::mLock held
1413status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1414{
1415 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001417 sp<EffectChain> chain = getEffectChain_l(sessionId);
1418 bool chainCreated = false;
1419
Eric Laurent5baf2af2013-09-12 17:37:00 -07001420 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1421 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1422 this, effect->desc().name, effect->desc().flags);
1423
Eric Laurent81784c32012-11-19 14:55:58 -08001424 if (chain == 0) {
1425 // create a new chain for this session
1426 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1427 chain = new EffectChain(this, sessionId);
1428 addEffectChain_l(chain);
1429 chain->setStrategy(getStrategyForSession_l(sessionId));
1430 chainCreated = true;
1431 }
1432 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1433
1434 if (chain->getEffectFromId_l(effect->id()) != 0) {
1435 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1436 this, effect->desc().name, chain.get());
1437 return BAD_VALUE;
1438 }
1439
Eric Laurent5baf2af2013-09-12 17:37:00 -07001440 effect->setOffloaded(mType == OFFLOAD, mId);
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442 status_t status = chain->addEffect_l(effect);
1443 if (status != NO_ERROR) {
1444 if (chainCreated) {
1445 removeEffectChain_l(chain);
1446 }
1447 return status;
1448 }
1449
1450 effect->setDevice(mOutDevice);
1451 effect->setDevice(mInDevice);
1452 effect->setMode(mAudioFlinger->getMode());
1453 effect->setAudioSource(mAudioSource);
1454 return NO_ERROR;
1455}
1456
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001457void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001458
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001459 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001460 effect_descriptor_t desc = effect->desc();
1461 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1462 detachAuxEffect_l(effect->id());
1463 }
1464
1465 sp<EffectChain> chain = effect->chain().promote();
1466 if (chain != 0) {
1467 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001468 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001469 removeEffectChain_l(chain);
1470 }
1471 } else {
1472 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1473 }
1474}
1475
1476void AudioFlinger::ThreadBase::lockEffectChains_l(
1477 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1478{
1479 effectChains = mEffectChains;
1480 for (size_t i = 0; i < mEffectChains.size(); i++) {
1481 mEffectChains[i]->lock();
1482 }
1483}
1484
1485void AudioFlinger::ThreadBase::unlockEffectChains(
1486 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1487{
1488 for (size_t i = 0; i < effectChains.size(); i++) {
1489 effectChains[i]->unlock();
1490 }
1491}
1492
Glenn Kastend848eb42016-03-08 13:42:11 -08001493sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001494{
1495 Mutex::Autolock _l(mLock);
1496 return getEffectChain_l(sessionId);
1497}
1498
Glenn Kastend848eb42016-03-08 13:42:11 -08001499sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1500 const
Eric Laurent81784c32012-11-19 14:55:58 -08001501{
1502 size_t size = mEffectChains.size();
1503 for (size_t i = 0; i < size; i++) {
1504 if (mEffectChains[i]->sessionId() == sessionId) {
1505 return mEffectChains[i];
1506 }
1507 }
1508 return 0;
1509}
1510
1511void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1512{
1513 Mutex::Autolock _l(mLock);
1514 size_t size = mEffectChains.size();
1515 for (size_t i = 0; i < size; i++) {
1516 mEffectChains[i]->setMode_l(mode);
1517 }
1518}
1519
Eric Laurent83b88082014-06-20 18:31:16 -07001520void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1521{
1522 config->type = AUDIO_PORT_TYPE_MIX;
1523 config->ext.mix.handle = mId;
1524 config->sample_rate = mSampleRate;
1525 config->format = mFormat;
1526 config->channel_mask = mChannelMask;
1527 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1528 AUDIO_PORT_CONFIG_FORMAT;
1529}
1530
Eric Laurent72e3f392015-05-20 14:43:50 -07001531void AudioFlinger::ThreadBase::systemReady()
1532{
1533 Mutex::Autolock _l(mLock);
1534 if (mSystemReady) {
1535 return;
1536 }
1537 mSystemReady = true;
1538
1539 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1540 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1541 }
1542 mPendingConfigEvents.clear();
1543}
1544
Andy Hungdae27702016-10-31 14:01:16 -07001545template <typename T>
1546ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1547 ssize_t index = mActiveTracks.indexOf(track);
1548 if (index >= 0) {
1549 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1550 return index;
1551 }
1552 mActiveTracksGeneration++;
1553 mLatestActiveTrack = track;
1554 ++mBatteryCounter[track->uid()].second;
1555 return mActiveTracks.add(track);
1556}
1557
1558template <typename T>
1559ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1560 ssize_t index = mActiveTracks.remove(track);
1561 if (index < 0) {
1562 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1563 return index;
1564 }
1565 mActiveTracksGeneration++;
1566 --mBatteryCounter[track->uid()].second;
1567 // mLatestActiveTrack is not cleared even if is the same as track.
1568 return index;
1569}
1570
1571template <typename T>
1572void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1573 for (const sp<T> &track : mActiveTracks) {
1574 BatteryNotifier::getInstance().noteStopAudio(track->uid());
1575 }
1576 mLastActiveTracksGeneration = mActiveTracksGeneration;
1577 mActiveTracks.clear();
1578 mLatestActiveTrack.clear();
1579 mBatteryCounter.clear();
1580}
1581
1582template <typename T>
1583void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1584 sp<ThreadBase> thread, bool force) {
1585 // Updates ActiveTracks client uids to the thread wakelock.
1586 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1587 thread->updateWakeLockUids_l(getWakeLockUids());
1588 mLastActiveTracksGeneration = mActiveTracksGeneration;
1589 }
1590
1591 // Updates BatteryNotifier uids
1592 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1593 const uid_t uid = it->first;
1594 ssize_t &previous = it->second.first;
1595 ssize_t &current = it->second.second;
1596 if (current > 0) {
1597 if (previous == 0) {
1598 BatteryNotifier::getInstance().noteStartAudio(uid);
1599 }
1600 previous = current;
1601 ++it;
1602 } else if (current == 0) {
1603 if (previous > 0) {
1604 BatteryNotifier::getInstance().noteStopAudio(uid);
1605 }
1606 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1607 } else /* (current < 0) */ {
1608 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1609 }
1610 }
1611}
Eric Laurent83b88082014-06-20 18:31:16 -07001612
Eric Laurent6acd1d42017-01-04 14:23:29 -08001613void AudioFlinger::ThreadBase::broadcast_l()
1614{
1615 // Thread could be blocked waiting for async
1616 // so signal it to handle state changes immediately
1617 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1618 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1619 mSignalPending = true;
1620 mWaitWorkCV.broadcast();
1621}
1622
Eric Laurent81784c32012-11-19 14:55:58 -08001623// ----------------------------------------------------------------------------
1624// Playback
1625// ----------------------------------------------------------------------------
1626
1627AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1628 AudioStreamOut* output,
1629 audio_io_handle_t id,
1630 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001631 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001632 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001633 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001634 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001635 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001636 mMixerBuffer(NULL),
1637 mMixerBufferSize(0),
1638 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1639 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001640 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001641 mEffectBuffer(NULL),
1642 mEffectBufferSize(0),
1643 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1644 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001645 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001646 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001647 mSuspendedFrames(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001648 // mStreamTypes[] initialized in constructor body
1649 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001650 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001651 mMixerStatus(MIXER_IDLE),
1652 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001653 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001654 mBytesRemaining(0),
1655 mCurrentWriteLength(0),
1656 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001657 mWriteAckSequence(0),
1658 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001659 mScreenState(AudioFlinger::mScreenState),
1660 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001661 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001662 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001663{
Glenn Kastend7dca052015-03-05 16:05:54 -08001664 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1665 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001666
1667 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1668 // it would be safer to explicitly pass initial masterVolume/masterMute as
1669 // parameter.
1670 //
1671 // If the HAL we are using has support for master volume or master mute,
1672 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1673 // and the mute set to false).
1674 mMasterVolume = audioFlinger->masterVolume_l();
1675 mMasterMute = audioFlinger->masterMute_l();
1676 if (mOutput && mOutput->audioHwDev) {
1677 if (mOutput->audioHwDev->canSetMasterVolume()) {
1678 mMasterVolume = 1.0;
1679 }
1680
1681 if (mOutput->audioHwDev->canSetMasterMute()) {
1682 mMasterMute = false;
1683 }
1684 }
1685
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001686 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001687
Eric Laurent223fd5c2014-11-11 13:43:36 -08001688 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001689 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001690 stream = (audio_stream_type_t) (stream + 1)) {
1691 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1692 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1693 }
Eric Laurent81784c32012-11-19 14:55:58 -08001694}
1695
1696AudioFlinger::PlaybackThread::~PlaybackThread()
1697{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001698 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001699 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001700 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001701 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001702}
1703
1704void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1705{
1706 dumpInternals(fd, args);
1707 dumpTracks(fd, args);
1708 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001709 dprintf(fd, " Local log:\n");
1710 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001711}
1712
Glenn Kasten0f11b512014-01-31 16:18:54 -08001713void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001714{
1715 const size_t SIZE = 256;
1716 char buffer[SIZE];
1717 String8 result;
1718
Marco Nelissenb2208842014-02-07 14:00:50 -08001719 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001720 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1721 const stream_type_t *st = &mStreamTypes[i];
1722 if (i > 0) {
1723 result.appendFormat(", ");
1724 }
1725 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1726 if (st->mute) {
1727 result.append("M");
1728 }
1729 }
1730 result.append("\n");
1731 write(fd, result.string(), result.length());
1732 result.clear();
1733
Eric Laurent81784c32012-11-19 14:55:58 -08001734 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1735 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001736 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001737 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001738
1739 size_t numtracks = mTracks.size();
1740 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001741 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001742 size_t numactiveseen = 0;
1743 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001744 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08001745 Track::appendDumpHeader(result);
1746 for (size_t i = 0; i < numtracks; ++i) {
1747 sp<Track> track = mTracks[i];
1748 if (track != 0) {
1749 bool active = mActiveTracks.indexOf(track) >= 0;
1750 if (active) {
1751 numactiveseen++;
1752 }
1753 track->dump(buffer, SIZE, active);
1754 result.append(buffer);
1755 }
1756 }
1757 } else {
1758 result.append("\n");
1759 }
1760 if (numactiveseen != numactive) {
1761 // some tracks in the active list were not in the tracks list
1762 snprintf(buffer, SIZE, " The following tracks are in the active list but"
1763 " not in the track list\n");
1764 result.append(buffer);
1765 Track::appendDumpHeader(result);
1766 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001767 sp<Track> track = mActiveTracks[i];
1768 if (mTracks.indexOf(track) < 0) {
Marco Nelissenb2208842014-02-07 14:00:50 -08001769 track->dump(buffer, SIZE, true);
1770 result.append(buffer);
1771 }
1772 }
1773 }
1774
1775 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001776}
1777
1778void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1779{
Glenn Kasten44182c22015-03-05 17:12:23 -08001780 dumpBase(fd, args);
1781
Elliott Hughes87cebad2014-05-22 10:14:43 -07001782 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001783 dprintf(fd, " Last write occurred (msecs): %llu\n",
1784 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001785 dprintf(fd, " Total writes: %d\n", mNumWrites);
1786 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1787 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1788 dprintf(fd, " Suspend count: %d\n", mSuspended);
1789 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1790 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1791 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1792 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001793 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001794 AudioStreamOut *output = mOutput;
1795 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001796 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1797 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001798 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1799 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1800 if (mPipeSink.get() != nullptr) {
1801 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1802 }
1803 if (output != nullptr) {
1804 dprintf(fd, " Hal stream dump:\n");
1805 (void)output->stream->dump(fd);
1806 }
Eric Laurent81784c32012-11-19 14:55:58 -08001807}
1808
1809// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001810
1811void AudioFlinger::PlaybackThread::onFirstRef()
1812{
Glenn Kastend7dca052015-03-05 16:05:54 -08001813 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001814}
1815
1816// ThreadBase virtuals
1817void AudioFlinger::PlaybackThread::preExit()
1818{
1819 ALOGV(" preExit()");
1820 // FIXME this is using hard-coded strings but in the future, this functionality will be
1821 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001822 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1823 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001824}
1825
1826// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1827sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1828 const sp<AudioFlinger::Client>& client,
1829 audio_stream_type_t streamType,
1830 uint32_t sampleRate,
1831 audio_format_t format,
1832 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001833 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001834 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001835 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001836 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001837 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001838 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001839 status_t *status,
1840 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001841{
Glenn Kasten74935e42013-12-19 08:56:45 -08001842 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001843 sp<Track> track;
1844 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001845 audio_output_flags_t outputFlags = mOutput->flags;
1846
1847 // special case for FAST flag considered OK if fast mixer is present
1848 if (hasFastMixer()) {
1849 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1850 }
1851
1852 // Check if requested flags are compatible with output stream flags
1853 if ((*flags & outputFlags) != *flags) {
1854 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1855 *flags, outputFlags);
1856 *flags = (audio_output_flags_t)(*flags & outputFlags);
1857 }
Eric Laurent81784c32012-11-19 14:55:58 -08001858
Eric Laurent81784c32012-11-19 14:55:58 -08001859 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001860 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001861 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001862 // PCM data
1863 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001864 // TODO: extract as a data library function that checks that a computationally
1865 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001866 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001867 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1868 (channelMask == AUDIO_CHANNEL_OUT_MONO
1869 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001870 // hardware sample rate
1871 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001872 // normal mixer has an associated fast mixer
1873 hasFastMixer() &&
1874 // there are sufficient fast track slots available
1875 (mFastTrackAvailMask != 0)
1876 // FIXME test that MixerThread for this fast track has a capable output HAL
1877 // FIXME add a permission test also?
1878 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001879 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1880 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001881 // read the fast track multiplier property the first time it is needed
1882 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1883 if (ok != 0) {
1884 ALOGE("%s pthread_once failed: %d", __func__, ok);
1885 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001886 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001887 }
Eric Laurent4c415062016-06-17 16:14:16 -07001888
1889 // check compatibility with audio effects.
1890 { // scope for mLock
1891 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001892 for (audio_session_t session : {
1893 AUDIO_SESSION_OUTPUT_STAGE,
1894 AUDIO_SESSION_OUTPUT_MIX,
1895 sessionId,
1896 }) {
1897 sp<EffectChain> chain = getEffectChain_l(session);
1898 if (chain.get() != nullptr) {
1899 audio_output_flags_t old = *flags;
1900 chain->checkOutputFlagCompatibility(flags);
1901 if (old != *flags) {
1902 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1903 (int)session, (int)old, (int)*flags);
1904 }
Eric Laurent4c415062016-06-17 16:14:16 -07001905 }
1906 }
1907 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001908 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001909 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1910 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001911 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001912 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1913 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001914 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001915 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001916 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001917 audio_is_linear_pcm(format),
1918 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001919 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001920 }
1921 }
1922 // For normal PCM streaming tracks, update minimum frame count.
1923 // For compatibility with AudioTrack calculation, buffer depth is forced
1924 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1925 // This is probably too conservative, but legacy application code may depend on it.
1926 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001927 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001928 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001929 // this must match AudioTrack.cpp calculateMinFrameCount().
1930 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001931 uint32_t latencyMs = 0;
1932 lStatus = mOutput->stream->getLatency(&latencyMs);
1933 if (lStatus != OK) {
1934 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1935 goto Exit;
1936 }
Eric Laurent81784c32012-11-19 14:55:58 -08001937 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1938 if (minBufCount < 2) {
1939 minBufCount = 2;
1940 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001941 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1942 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001943 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001944 minBufCount * sourceFramesNeededWithTimestretch(
1945 sampleRate, mNormalFrameCount,
1946 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001947 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001948 frameCount = minFrameCount;
1949 }
Eric Laurent81784c32012-11-19 14:55:58 -08001950 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001951 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001952
Glenn Kastenc3df8382014-03-13 15:05:25 -07001953 switch (mType) {
1954
1955 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001956 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001957 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001958 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1959 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001960 sampleRate, format, channelMask, mOutput, mFormat);
1961 lStatus = BAD_VALUE;
1962 goto Exit;
1963 }
1964 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001965 break;
1966
1967 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001968 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001969 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1970 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001971 sampleRate, format, channelMask, mOutput, mFormat);
1972 lStatus = BAD_VALUE;
1973 goto Exit;
1974 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001975 break;
1976
1977 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001978 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001979 ALOGE("createTrack_l() Bad parameter: format %#x \""
1980 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001981 format, mOutput, mFormat);
1982 lStatus = BAD_VALUE;
1983 goto Exit;
1984 }
Andy Hungcd044842014-08-07 11:04:34 -07001985 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001986 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1987 lStatus = BAD_VALUE;
1988 goto Exit;
1989 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001990 break;
1991
Eric Laurent81784c32012-11-19 14:55:58 -08001992 }
1993
1994 lStatus = initCheck();
1995 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07001996 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08001997 goto Exit;
1998 }
1999
2000 { // scope for mLock
2001 Mutex::Autolock _l(mLock);
2002
2003 // all tracks in same audio session must share the same routing strategy otherwise
2004 // conflicts will happen when tracks are moved from one output to another by audio policy
2005 // manager
2006 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2007 for (size_t i = 0; i < mTracks.size(); ++i) {
2008 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002009 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002010 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2011 if (sessionId == t->sessionId() && strategy != actual) {
2012 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2013 strategy, actual);
2014 lStatus = BAD_VALUE;
2015 goto Exit;
2016 }
2017 }
2018 }
2019
Glenn Kastend79072e2016-01-06 08:41:20 -08002020 track = new Track(this, client, streamType, sampleRate, format,
2021 channelMask, frameCount, NULL, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002022 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002023
Glenn Kasten03003332013-08-06 15:40:54 -07002024 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2025 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002026 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002027 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002028 goto Exit;
2029 }
2030 mTracks.add(track);
2031
2032 sp<EffectChain> chain = getEffectChain_l(sessionId);
2033 if (chain != 0) {
2034 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2035 track->setMainBuffer(chain->inBuffer());
2036 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2037 chain->incTrackCnt();
2038 }
2039
Eric Laurent05067782016-06-01 18:27:28 -07002040 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002041 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2042 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2043 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002044 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002045 }
2046 }
2047
2048 lStatus = NO_ERROR;
2049
2050Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002051 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002052 return track;
2053}
2054
2055uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2056{
2057 return latency;
2058}
2059
2060uint32_t AudioFlinger::PlaybackThread::latency() const
2061{
2062 Mutex::Autolock _l(mLock);
2063 return latency_l();
2064}
2065uint32_t AudioFlinger::PlaybackThread::latency_l() const
2066{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002067 uint32_t latency;
2068 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2069 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002070 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002071 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002072}
2073
2074void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2075{
2076 Mutex::Autolock _l(mLock);
2077 // Don't apply master volume in SW if our HAL can do it for us.
2078 if (mOutput && mOutput->audioHwDev &&
2079 mOutput->audioHwDev->canSetMasterVolume()) {
2080 mMasterVolume = 1.0;
2081 } else {
2082 mMasterVolume = value;
2083 }
2084}
2085
2086void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2087{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002088 if (isDuplicating()) {
2089 return;
2090 }
Eric Laurent81784c32012-11-19 14:55:58 -08002091 Mutex::Autolock _l(mLock);
2092 // Don't apply master mute in SW if our HAL can do it for us.
2093 if (mOutput && mOutput->audioHwDev &&
2094 mOutput->audioHwDev->canSetMasterMute()) {
2095 mMasterMute = false;
2096 } else {
2097 mMasterMute = muted;
2098 }
2099}
2100
2101void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2102{
2103 Mutex::Autolock _l(mLock);
2104 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002105 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002106}
2107
2108void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2109{
2110 Mutex::Autolock _l(mLock);
2111 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002112 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002113}
2114
2115float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2116{
2117 Mutex::Autolock _l(mLock);
2118 return mStreamTypes[stream].volume;
2119}
2120
2121// addTrack_l() must be called with ThreadBase::mLock held
2122status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2123{
2124 status_t status = ALREADY_EXISTS;
2125
Eric Laurent81784c32012-11-19 14:55:58 -08002126 if (mActiveTracks.indexOf(track) < 0) {
2127 // the track is newly added, make sure it fills up all its
2128 // buffers before playing. This is to ensure the client will
2129 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002130 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002131 TrackBase::track_state state = track->mState;
2132 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002133 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002134 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002135 mLock.lock();
2136 // abort track was stopped/paused while we released the lock
2137 if (state != track->mState) {
2138 if (status == NO_ERROR) {
2139 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002140 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002141 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002142 mLock.lock();
2143 }
2144 return INVALID_OPERATION;
2145 }
2146 // abort if start is rejected by audio policy manager
2147 if (status != NO_ERROR) {
2148 return PERMISSION_DENIED;
2149 }
2150#ifdef ADD_BATTERY_DATA
2151 // to track the speaker usage
2152 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2153#endif
2154 }
2155
Eric Laurent51716182016-02-29 18:00:56 -08002156 // set retry count for buffer fill
2157 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002158 if (track->isStopping_1()) {
2159 track->mRetryCount = kMaxTrackStopRetriesOffload;
2160 } else {
2161 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2162 }
2163 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002164 } else {
2165 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002166 track->mFillingUpStatus =
2167 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002168 }
2169
Eric Laurent81784c32012-11-19 14:55:58 -08002170 track->mResetDone = false;
2171 track->mPresentationCompleteFrames = 0;
2172 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002173 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2174 if (chain != 0) {
2175 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2176 track->sessionId());
2177 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002178 }
2179
Andy Hung2148bf02016-11-28 19:01:02 -08002180 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07002181 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08002182 mLocalLog.log("addTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2183
Eric Laurent81784c32012-11-19 14:55:58 -08002184 status = NO_ERROR;
2185 }
2186
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002187 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002188 return status;
2189}
2190
Eric Laurentbfb1b832013-01-07 09:53:42 -08002191bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002192{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002193 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002194 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002195 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2196 track->mState = TrackBase::STOPPED;
2197 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002198 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002199 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002201 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202
2203 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002204}
2205
2206void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2207{
2208 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002209
2210 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07002211 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08002212 mLocalLog.log("removeTrack_l (%p) %s", track.get(), buffer + 4); // log for analysis
2213
Eric Laurent81784c32012-11-19 14:55:58 -08002214 mTracks.remove(track);
2215 deleteTrackName_l(track->name());
2216 // redundant as track is about to be destroyed, for dumpsys only
2217 track->mName = -1;
2218 if (track->isFastTrack()) {
2219 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002220 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002221 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2222 mFastTrackAvailMask |= 1 << index;
2223 // redundant as track is about to be destroyed, for dumpsys only
2224 track->mFastIndex = -1;
2225 }
2226 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2227 if (chain != 0) {
2228 chain->decTrackCnt();
2229 }
2230}
2231
2232String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2233{
Eric Laurent81784c32012-11-19 14:55:58 -08002234 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002235 String8 out_s8;
2236 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2237 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002238 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002239 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002240}
2241
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002242void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002243 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2244 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002245
Eric Laurent73e26b62015-04-27 16:55:58 -07002246 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002247
2248 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002249 case AUDIO_OUTPUT_OPENED:
2250 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002251 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002252 desc->mChannelMask = mChannelMask;
2253 desc->mSamplingRate = mSampleRate;
2254 desc->mFormat = mFormat;
2255 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002256 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002257 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002258 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002259 break;
2260
Eric Laurent73e26b62015-04-27 16:55:58 -07002261 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002262 default:
2263 break;
2264 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002265 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002266}
2267
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002268void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002269{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002270 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002271}
2272
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002273void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002275 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002276}
2277
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002278void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002279{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002280 mCallbackThread->setAsyncError();
2281}
2282
Eric Laurent3b4529e2013-09-05 18:09:19 -07002283void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002284{
2285 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002286 // reject out of sequence requests
2287 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2288 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002289 mWaitWorkCV.signal();
2290 }
2291}
2292
Eric Laurent3b4529e2013-09-05 18:09:19 -07002293void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002294{
2295 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002296 // reject out of sequence requests
2297 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2298 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299 mWaitWorkCV.signal();
2300 }
2301}
2302
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002303void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002304{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002305 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002306 mSampleRate = mOutput->getSampleRate();
2307 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002308 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002309 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002310 }
Andy Hung9a592762014-07-21 21:56:01 -07002311 if ((mType == MIXER || mType == DUPLICATING)
2312 && !isValidPcmSinkChannelMask(mChannelMask)) {
2313 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2314 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 }
Andy Hunge5412692014-05-16 11:25:07 -07002316 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002317
2318 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002319 status_t result = mOutput->stream->getFormat(&mHALFormat);
2320 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002321 // Get format from the shim, which will be different than the HAL format
2322 // if playing compressed audio over HDMI passthrough.
2323 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002324 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002325 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002326 }
Andy Hung6146c082014-03-18 11:56:15 -07002327 if ((mType == MIXER || mType == DUPLICATING)
2328 && !isValidPcmSinkFormat(mFormat)) {
2329 LOG_FATAL("HAL format %#x not supported for mixed output",
2330 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002331 }
Phil Burk062e67a2015-02-11 13:40:50 -08002332 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002333 result = mOutput->stream->getBufferSize(&mBufferSize);
2334 LOG_ALWAYS_FATAL_IF(result != OK,
2335 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002336 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002337 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002338 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002339 mFrameCount);
2340 }
2341
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002342 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2343 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002344 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002345 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002346 }
2347 }
2348
Eric Laurentd1f69b02014-12-15 14:33:13 -08002349 mHwSupportsPause = false;
2350 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002351 bool supportsPause = false, supportsResume = false;
2352 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2353 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002354 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002355 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002356 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002357 } else if (supportsResume) {
2358 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002359 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002360 }
2361 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002362 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2363 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2364 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002365
Andy Hungfbfc3952015-01-15 13:33:51 -08002366 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2367 // For best precision, we use float instead of the associated output
2368 // device format (typically PCM 16 bit).
2369
2370 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2371 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2372 mBufferSize = mFrameSize * mFrameCount;
2373
2374 // TODO: We currently use the associated output device channel mask and sample rate.
2375 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2376 // (if a valid mask) to avoid premature downmix.
2377 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2378 // instead of the output device sample rate to avoid loss of high frequency information.
2379 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2380 }
2381
Andy Hung09a50072014-02-27 14:30:47 -08002382 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002383 double multiplier = 1.0;
2384 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2385 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002386 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2387 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002388
Eric Laurent81784c32012-11-19 14:55:58 -08002389 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2390 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2391 maxNormalFrameCount = maxNormalFrameCount & ~15;
2392 if (maxNormalFrameCount < minNormalFrameCount) {
2393 maxNormalFrameCount = minNormalFrameCount;
2394 }
2395 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2396 if (multiplier <= 1.0) {
2397 multiplier = 1.0;
2398 } else if (multiplier <= 2.0) {
2399 if (2 * mFrameCount <= maxNormalFrameCount) {
2400 multiplier = 2.0;
2401 } else {
2402 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2403 }
2404 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002405 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002406 }
2407 }
2408 mNormalFrameCount = multiplier * mFrameCount;
2409 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002410 if (mType == MIXER || mType == DUPLICATING) {
2411 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2412 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002413 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002414 mNormalFrameCount);
2415
Andy Hung08fb1742015-05-31 23:22:10 -07002416 // Check if we want to throttle the processing to no more than 2x normal rate
2417 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002418 mThreadThrottleTimeMs = 0;
2419 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002420 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2421
Andy Hung010a1a12014-03-13 13:57:33 -07002422 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2423 // Originally this was int16_t[] array, need to remove legacy implications.
2424 free(mSinkBuffer);
2425 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002426 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2427 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2428 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002429 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002430
Andy Hung69aed5f2014-02-25 17:24:40 -08002431 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2432 // drives the output.
2433 free(mMixerBuffer);
2434 mMixerBuffer = NULL;
2435 if (mMixerBufferEnabled) {
2436 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2437 mMixerBufferSize = mNormalFrameCount * mChannelCount
2438 * audio_bytes_per_sample(mMixerBufferFormat);
2439 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2440 }
Andy Hung98ef9782014-03-04 14:46:50 -08002441 free(mEffectBuffer);
2442 mEffectBuffer = NULL;
2443 if (mEffectBufferEnabled) {
2444 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2445 mEffectBufferSize = mNormalFrameCount * mChannelCount
2446 * audio_bytes_per_sample(mEffectBufferFormat);
2447 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2448 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002449
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // force reconfiguration of effect chains and engines to take new buffer size and audio
2451 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002452 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2454 // matter.
2455 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2456 Vector< sp<EffectChain> > effectChains = mEffectChains;
2457 for (size_t i = 0; i < effectChains.size(); i ++) {
2458 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2459 }
2460}
2461
2462
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002463status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002464{
2465 if (halFrames == NULL || dspFrames == NULL) {
2466 return BAD_VALUE;
2467 }
2468 Mutex::Autolock _l(mLock);
2469 if (initCheck() != NO_ERROR) {
2470 return INVALID_OPERATION;
2471 }
Andy Hung818e7a32016-02-16 18:08:07 -08002472 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002473 *halFrames = framesWritten;
2474
2475 if (isSuspended()) {
2476 // return an estimation of rendered frames when the output is suspended
2477 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002478 *dspFrames = (uint32_t)
2479 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002480 return NO_ERROR;
2481 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002482 status_t status;
2483 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002484 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002485 *dspFrames = (size_t)frames;
2486 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002487 }
2488}
2489
Eric Laurent4c415062016-06-17 16:14:16 -07002490// hasAudioSession_l() must be called with ThreadBase::mLock held
2491uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002492{
Eric Laurent81784c32012-11-19 14:55:58 -08002493 uint32_t result = 0;
2494 if (getEffectChain_l(sessionId) != 0) {
2495 result = EFFECT_SESSION;
2496 }
2497
2498 for (size_t i = 0; i < mTracks.size(); ++i) {
2499 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002500 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002501 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002502 if (track->isFastTrack()) {
2503 result |= FAST_SESSION;
2504 }
Eric Laurent81784c32012-11-19 14:55:58 -08002505 break;
2506 }
2507 }
2508
2509 return result;
2510}
2511
Glenn Kastend848eb42016-03-08 13:42:11 -08002512uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002513{
2514 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2515 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2516 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2517 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2518 }
2519 for (size_t i = 0; i < mTracks.size(); i++) {
2520 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002521 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002522 return AudioSystem::getStrategyForStream(track->streamType());
2523 }
2524 }
2525 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2526}
2527
2528
Phil Burk062e67a2015-02-11 13:40:50 -08002529AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002530{
2531 Mutex::Autolock _l(mLock);
2532 return mOutput;
2533}
2534
Phil Burk062e67a2015-02-11 13:40:50 -08002535AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002536{
2537 Mutex::Autolock _l(mLock);
2538 AudioStreamOut *output = mOutput;
2539 mOutput = NULL;
2540 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2541 // must push a NULL and wait for ack
2542 mOutputSink.clear();
2543 mPipeSink.clear();
2544 mNormalSink.clear();
2545 return output;
2546}
2547
2548// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002550{
2551 if (mOutput == NULL) {
2552 return NULL;
2553 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002554 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002555}
2556
2557uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2558{
2559 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2560}
2561
2562status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2563{
2564 if (!isValidSyncEvent(event)) {
2565 return BAD_VALUE;
2566 }
2567
2568 Mutex::Autolock _l(mLock);
2569
2570 for (size_t i = 0; i < mTracks.size(); ++i) {
2571 sp<Track> track = mTracks[i];
2572 if (event->triggerSession() == track->sessionId()) {
2573 (void) track->setSyncEvent(event);
2574 return NO_ERROR;
2575 }
2576 }
2577
2578 return NAME_NOT_FOUND;
2579}
2580
2581bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2582{
2583 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2584}
2585
2586void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2587 const Vector< sp<Track> >& tracksToRemove)
2588{
2589 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002590 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002591 for (size_t i = 0 ; i < count ; i++) {
2592 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002593 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002594 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002595 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002596#ifdef ADD_BATTERY_DATA
2597 // to track the speaker usage
2598 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2599#endif
2600 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002601 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002602 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603 }
Eric Laurent81784c32012-11-19 14:55:58 -08002604 }
2605 }
2606 }
Eric Laurent81784c32012-11-19 14:55:58 -08002607}
2608
2609void AudioFlinger::PlaybackThread::checkSilentMode_l()
2610{
2611 if (!mMasterMute) {
2612 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002613 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2614 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2615 return;
2616 }
Eric Laurent81784c32012-11-19 14:55:58 -08002617 if (property_get("ro.audio.silent", value, "0") > 0) {
2618 char *endptr;
2619 unsigned long ul = strtoul(value, &endptr, 0);
2620 if (*endptr == '\0' && ul != 0) {
2621 ALOGD("Silence is golden");
2622 // The setprop command will not allow a property to be changed after
2623 // the first time it is set, so we don't have to worry about un-muting.
2624 setMasterMute_l(true);
2625 }
2626 }
2627 }
2628}
2629
2630// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002631ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002632{
Eric Laurent81784c32012-11-19 14:55:58 -08002633 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002634 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002635 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002636
2637 // If an NBAIO sink is present, use it to write the normal mixer's submix
2638 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002639
Andy Hung010a1a12014-03-13 13:57:33 -07002640 const size_t count = mBytesRemaining / mFrameSize;
2641
Simon Wilson2d590962012-11-29 15:18:50 -08002642 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002643 // update the setpoint when AudioFlinger::mScreenState changes
2644 uint32_t screenState = AudioFlinger::mScreenState;
2645 if (screenState != mScreenState) {
2646 mScreenState = screenState;
2647 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2648 if (pipe != NULL) {
2649 pipe->setAvgFrames((mScreenState & 1) ?
2650 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2651 }
2652 }
Andy Hung010a1a12014-03-13 13:57:33 -07002653 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002654 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002655 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002656 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002657 } else {
2658 bytesWritten = framesWritten;
2659 }
2660 // otherwise use the HAL / AudioStreamOut directly
2661 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002663
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002665 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2666 mWriteAckSequence += 2;
2667 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002669 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002670 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002671 // FIXME We should have an implementation of timestamps for direct output threads.
2672 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002673 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002674
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 if (mUseAsyncWrite &&
2676 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2677 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002678 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002680 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 }
Eric Laurent81784c32012-11-19 14:55:58 -08002682 }
2683
Eric Laurent81784c32012-11-19 14:55:58 -08002684 mNumWrites++;
2685 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002686 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002687 return bytesWritten;
2688}
2689
2690void AudioFlinger::PlaybackThread::threadLoop_drain()
2691{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002692 bool supportsDrain = false;
2693 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002694 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2695 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002696 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2697 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002699 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002700 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002701 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002702 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 }
2704}
2705
2706void AudioFlinger::PlaybackThread::threadLoop_exit()
2707{
Eric Laurent275e8e92014-11-30 15:14:47 -08002708 {
2709 Mutex::Autolock _l(mLock);
2710 for (size_t i = 0; i < mTracks.size(); i++) {
2711 sp<Track> track = mTracks[i];
2712 track->invalidate();
2713 }
Andy Hungdae27702016-10-31 14:01:16 -07002714 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2715 // After we exit there are no more track changes sent to BatteryNotifier
2716 // because that requires an active threadLoop.
2717 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2718 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002719 }
Eric Laurent81784c32012-11-19 14:55:58 -08002720}
2721
2722/*
2723The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002724 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002725 - mActiveSleepTimeUs from activeSleepTimeUs()
2726 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002727 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2728 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002729 - maxPeriod from frame count and sample rate (MIXER only)
2730
2731The parameters that affect these derived values are:
2732 - frame count
2733 - frame size
2734 - sample rate
2735 - device type: A2DP or not
2736 - device latency
2737 - format: PCM or not
2738 - active sleep time
2739 - idle sleep time
2740*/
2741
2742void AudioFlinger::PlaybackThread::cacheParameters_l()
2743{
Andy Hung25c2dac2014-02-27 14:56:00 -08002744 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002745 mActiveSleepTimeUs = activeSleepTimeUs();
2746 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002747
2748 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2749 // truncating audio when going to standby.
2750 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2751 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2752 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2753 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2754 }
2755 }
Eric Laurent81784c32012-11-19 14:55:58 -08002756}
2757
Eric Laurent13084622016-05-17 10:51:49 -07002758bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002759{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002760 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002761 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002762 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002763 size_t size = mTracks.size();
2764 for (size_t i = 0; i < size; i++) {
2765 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002766 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002767 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002768 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002769 }
2770 }
Eric Laurent13084622016-05-17 10:51:49 -07002771 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002772}
2773
Haynes Mathew George05317d22016-05-03 16:34:26 -07002774void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2775{
2776 Mutex::Autolock _l(mLock);
2777 invalidateTracks_l(streamType);
2778}
2779
Eric Laurent81784c32012-11-19 14:55:58 -08002780status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2781{
Glenn Kastend848eb42016-03-08 13:42:11 -08002782 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002783 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2784 status_t result = EffectBufferHalInterface::mirror(
2785 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2786 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2787 &halInBuffer);
2788 if (result != OK) return result;
2789 halOutBuffer = halInBuffer;
2790 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002791
2792 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002793 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002794 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002795 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002796 if (mType != DIRECT) {
2797 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002798 status_t result = EffectBufferHalInterface::allocate(
2799 numSamples * sizeof(int16_t),
2800 &halInBuffer);
2801 if (result != OK) return result;
2802 buffer = halInBuffer->audioBuffer()->s16;
2803 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2804 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002805 }
2806
2807 // Attach all tracks with same session ID to this chain.
2808 for (size_t i = 0; i < mTracks.size(); ++i) {
2809 sp<Track> track = mTracks[i];
2810 if (session == track->sessionId()) {
2811 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2812 buffer);
2813 track->setMainBuffer(buffer);
2814 chain->incTrackCnt();
2815 }
2816 }
2817
2818 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002819 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002820 if (session == track->sessionId()) {
2821 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2822 chain->incActiveTrackCnt();
2823 }
2824 }
2825 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002826 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002827 chain->setInBuffer(halInBuffer);
2828 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002829 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002830 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2832 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002833 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002834 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002835 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002836 // Effect chain for other sessions are inserted at beginning of effect
2837 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002838 // sessions is not important.
2839 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2840 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2841 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002842 size_t size = mEffectChains.size();
2843 size_t i = 0;
2844 for (i = 0; i < size; i++) {
2845 if (mEffectChains[i]->sessionId() < session) {
2846 break;
2847 }
2848 }
2849 mEffectChains.insertAt(chain, i);
2850 checkSuspendOnAddEffectChain_l(chain);
2851
2852 return NO_ERROR;
2853}
2854
2855size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2856{
Glenn Kastend848eb42016-03-08 13:42:11 -08002857 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002858
2859 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2860
2861 for (size_t i = 0; i < mEffectChains.size(); i++) {
2862 if (chain == mEffectChains[i]) {
2863 mEffectChains.removeAt(i);
2864 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002865 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002866 if (session == track->sessionId()) {
2867 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2868 chain.get(), session);
2869 chain->decActiveTrackCnt();
2870 }
2871 }
2872
2873 // detach all tracks with same session ID from this chain
2874 for (size_t i = 0; i < mTracks.size(); ++i) {
2875 sp<Track> track = mTracks[i];
2876 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002877 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002878 chain->decTrackCnt();
2879 }
2880 }
2881 break;
2882 }
2883 }
2884 return mEffectChains.size();
2885}
2886
2887status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002888 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002889{
2890 Mutex::Autolock _l(mLock);
2891 return attachAuxEffect_l(track, EffectId);
2892}
2893
2894status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002895 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002896{
2897 status_t status = NO_ERROR;
2898
2899 if (EffectId == 0) {
2900 track->setAuxBuffer(0, NULL);
2901 } else {
2902 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2903 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2904 if (effect != 0) {
2905 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2906 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2907 } else {
2908 status = INVALID_OPERATION;
2909 }
2910 } else {
2911 status = BAD_VALUE;
2912 }
2913 }
2914 return status;
2915}
2916
2917void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2918{
2919 for (size_t i = 0; i < mTracks.size(); ++i) {
2920 sp<Track> track = mTracks[i];
2921 if (track->auxEffectId() == effectId) {
2922 attachAuxEffect_l(track, 0);
2923 }
2924 }
2925}
2926
2927bool AudioFlinger::PlaybackThread::threadLoop()
2928{
Glenn Kasten388d5712017-04-07 14:38:41 -07002929 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002930
Eric Laurent81784c32012-11-19 14:55:58 -08002931 Vector< sp<Track> > tracksToRemove;
2932
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002933 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002934 nsecs_t lastWriteFinished = -1; // time last server write completed
2935 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002936
2937 // MIXER
2938 nsecs_t lastWarning = 0;
2939
2940 // DUPLICATING
2941 // FIXME could this be made local to while loop?
2942 writeFrames = 0;
2943
2944 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002945 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002946
2947 if (mType == MIXER) {
2948 sleepTimeShift = 0;
2949 }
2950
2951 CpuStats cpuStats;
2952 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2953
2954 acquireWakeLock();
2955
Glenn Kasteneef598c2017-04-03 14:41:13 -07002956 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2957 // thread associated with this PlaybackThread.
2958 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2959 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002960 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2961 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002962 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002963 const char *logString = NULL;
2964
rago1bb90822017-05-02 18:31:48 -07002965 // Estimated time for next buffer to be written to hal. This is used only on
2966 // suspended mode (for now) to help schedule the wait time until next iteration.
2967 nsecs_t timeLoopNextNs = 0;
2968
Eric Laurent664539d2013-09-23 18:24:31 -07002969 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002970
Eric Laurent81784c32012-11-19 14:55:58 -08002971 while (!exitPending())
2972 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002973 // Log merge requests are performed during AudioFlinger binder transactions, but
2974 // that does not cover audio playback. It's requested here for that reason.
2975 mAudioFlinger->requestLogMerge();
2976
Eric Laurent81784c32012-11-19 14:55:58 -08002977 cpuStats.sample(myName);
2978
2979 Vector< sp<EffectChain> > effectChains;
2980
Eric Laurent81784c32012-11-19 14:55:58 -08002981 { // scope for mLock
2982
2983 Mutex::Autolock _l(mLock);
2984
Eric Laurent021cf962014-05-13 10:18:14 -07002985 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002986
Glenn Kasteneef598c2017-04-03 14:41:13 -07002987 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002988 if (logString != NULL) {
2989 mNBLogWriter->logTimestamp();
2990 mNBLogWriter->log(logString);
2991 logString = NULL;
2992 }
2993
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002994 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07002995 // and associate with the sink frames written out. We need
2996 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07002997 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07002998 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08002999 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003000 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003001 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003002 ExtendedTimestamp timestamp; // use private copy to fetch
3003 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003004
3005 // We keep track of the last valid kernel position in case we are in underrun
3006 // and the normal mixer period is the same as the fast mixer period, or there
3007 // is some error from the HAL.
3008 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3009 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3010 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3011 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3012 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3013
3014 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3016 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3017 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003018 }
3019
3020 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3021 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003022 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003023 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003024 }
3025
Andy Hung818e7a32016-02-16 18:08:07 -08003026 // copy over kernel info
3027 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003028 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3029 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003030 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3031 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003032 }
3033 // mFramesWritten for non-offloaded tracks are contiguous
3034 // even after standby() is called. This is useful for the track frame
3035 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003036 bool serverLocationUpdate = false;
3037 if (mFramesWritten != lastFramesWritten) {
3038 serverLocationUpdate = true;
3039 lastFramesWritten = mFramesWritten;
3040 }
3041 // Only update timestamps if there is a meaningful change.
3042 // Either the kernel timestamp must be valid or we have written something.
3043 if (kernelLocationUpdate || serverLocationUpdate) {
3044 if (serverLocationUpdate) {
3045 // use the time before we called the HAL write - it is a bit more accurate
3046 // to when the server last read data than the current time here.
3047 //
3048 // If we haven't written anything, mLastWriteTime will be -1
3049 // and we use systemTime().
3050 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3051 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3052 ? systemTime() : mLastWriteTime;
3053 }
Andy Hungdae27702016-10-31 14:01:16 -07003054
3055 for (const sp<Track> &t : mActiveTracks) {
3056 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003057 t->updateTrackFrameInfo(
3058 t->mAudioTrackServerProxy->framesReleased(),
3059 mFramesWritten,
3060 mTimestamp);
3061 }
Andy Hunge10393e2015-06-12 13:59:33 -07003062 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003063 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003064#if 0
3065 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003066 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003067 timespec ts;
3068 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003069 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003070 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003071 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003072 }
3073 ++z;
3074#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003075 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076 if (mSignalPending) {
3077 // A signal was raised while we were unlocked
3078 mSignalPending = false;
3079 } else if (waitingAsyncCallback_l()) {
3080 if (exitPending()) {
3081 break;
3082 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003083 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003084 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003085 releaseWakeLock_l();
3086 released = true;
3087 }
Andy Hung10cbff12017-02-21 17:30:14 -08003088
3089 const int64_t waitNs = computeWaitTimeNs_l();
3090 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3091 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3092 if (status == TIMED_OUT) {
3093 mSignalPending = true; // if timeout recheck everything
3094 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003095 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003096 if (released) {
3097 acquireWakeLock_l();
3098 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003099 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3100 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003101
3102 continue;
3103 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003104 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105 isSuspended()) {
3106 // put audio hardware into standby after short delay
3107 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003108
3109 threadLoop_standby();
3110
3111 mStandby = true;
3112 }
3113
3114 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3115 // we're about to wait, flush the binder command buffer
3116 IPCThreadState::self()->flushCommands();
3117
3118 clearOutputTracks();
3119
3120 if (exitPending()) {
3121 break;
3122 }
3123
3124 releaseWakeLock_l();
3125 // wait until we have something to do...
3126 ALOGV("%s going to sleep", myName.string());
3127 mWaitWorkCV.wait(mLock);
3128 ALOGV("%s waking up", myName.string());
3129 acquireWakeLock_l();
3130
3131 mMixerStatus = MIXER_IDLE;
3132 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3133 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003135 checkSilentMode_l();
3136
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003137 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3138 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003139 if (mType == MIXER) {
3140 sleepTimeShift = 0;
3141 }
3142
3143 continue;
3144 }
3145 }
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // mMixerStatusIgnoringFastTracks is also updated internally
3147 mMixerStatus = prepareTracks_l(&tracksToRemove);
3148
Andy Hungdae27702016-10-31 14:01:16 -07003149 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003150
Eric Laurent81784c32012-11-19 14:55:58 -08003151 // prevent any changes in effect chain list and in each effect chain
3152 // during mixing and effect process as the audio buffers could be deleted
3153 // or modified if an effect is created or deleted
3154 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003155 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003156
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157 if (mBytesRemaining == 0) {
3158 mCurrentWriteLength = 0;
3159 if (mMixerStatus == MIXER_TRACKS_READY) {
3160 // threadLoop_mix() sets mCurrentWriteLength
3161 threadLoop_mix();
3162 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3163 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003164 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003165 // must be written to HAL
3166 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003167 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003168 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003169 }
3170 }
Andy Hung98ef9782014-03-04 14:46:50 -08003171 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003172 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003173 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3174 // or mSinkBuffer (if there are no effects).
3175 //
3176 // This is done pre-effects computation; if effects change to
3177 // support higher precision, this needs to move.
3178 //
3179 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003180 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003181 if (mMixerBufferValid) {
3182 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3183 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3184
Andy Hung2ddee192015-12-18 17:34:44 -08003185 // mono blend occurs for mixer threads only (not direct or offloaded)
3186 // and is handled here if we're going directly to the sink.
3187 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003188 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3189 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003190 }
3191
Andy Hung98ef9782014-03-04 14:46:50 -08003192 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3193 mNormalFrameCount * mChannelCount);
3194 }
3195
Eric Laurentbfb1b832013-01-07 09:53:42 -08003196 mBytesRemaining = mCurrentWriteLength;
3197 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003198 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3199 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3200 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3201 mBytesWritten += mBytesRemaining;
3202 mFramesWritten += framesRemaining;
3203 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003204 mBytesRemaining = 0;
3205 }
Eric Laurent81784c32012-11-19 14:55:58 -08003206
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003208 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 for (size_t i = 0; i < effectChains.size(); i ++) {
3210 effectChains[i]->process_l();
3211 }
Eric Laurent81784c32012-11-19 14:55:58 -08003212 }
3213 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003214 // Process effect chains for offloaded thread even if no audio
3215 // was read from audio track: process only updates effect state
3216 // and thus does have to be synchronized with audio writes but may have
3217 // to be called while waiting for async write callback
3218 if (mType == OFFLOAD) {
3219 for (size_t i = 0; i < effectChains.size(); i ++) {
3220 effectChains[i]->process_l();
3221 }
3222 }
Eric Laurent81784c32012-11-19 14:55:58 -08003223
Andy Hung98ef9782014-03-04 14:46:50 -08003224 // Only if the Effects buffer is enabled and there is data in the
3225 // Effects buffer (buffer valid), we need to
3226 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003227 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003228 if (mEffectBufferValid) {
3229 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003230
3231 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003232 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3233 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003234 }
3235
Andy Hung98ef9782014-03-04 14:46:50 -08003236 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3237 mNormalFrameCount * mChannelCount);
3238 }
3239
Eric Laurent81784c32012-11-19 14:55:58 -08003240 // enable changes in effect chain
3241 unlockEffectChains(effectChains);
3242
Eric Laurentbfb1b832013-01-07 09:53:42 -08003243 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003244 // mSleepTimeUs == 0 means we must write to audio hardware
3245 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003246 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003247 // We save lastWriteFinished here, as previousLastWriteFinished,
3248 // for throttling. On thread start, previousLastWriteFinished will be
3249 // set to -1, which properly results in no throttling after the first write.
3250 nsecs_t previousLastWriteFinished = lastWriteFinished;
3251 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003252 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003253 // FIXME rewrite to reduce number of system calls
3254 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003255 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003256 lastWriteFinished = systemTime();
3257 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003258 if (ret < 0) {
3259 mBytesRemaining = 0;
3260 } else {
3261 mBytesWritten += ret;
3262 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003263 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003264 }
3265 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3266 (mMixerStatus == MIXER_DRAIN_ALL)) {
3267 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003268 }
Andy Hung08fb1742015-05-31 23:22:10 -07003269 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003270 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003271 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003272 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003273 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003274 ATRACE_NAME("underrun");
3275 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003276 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003277 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003278 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003279 }
Andy Hung08fb1742015-05-31 23:22:10 -07003280
3281 if (mThreadThrottle
3282 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3283 && ret > 0) { // we wrote something
3284 // Limit MixerThread data processing to no more than twice the
3285 // expected processing rate.
3286 //
3287 // This helps prevent underruns with NuPlayer and other applications
3288 // which may set up buffers that are close to the minimum size, or use
3289 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3290 //
3291 // The throttle smooths out sudden large data drains from the device,
3292 // e.g. when it comes out of standby, which often causes problems with
3293 // (1) mixer threads without a fast mixer (which has its own warm-up)
3294 // (2) minimum buffer sized tracks (even if the track is full,
3295 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003296 //
3297 // Total time spent in last processing cycle equals time spent in
3298 // 1. threadLoop_write, as well as time spent in
3299 // 2. threadLoop_mix (significant for heavy mixing, especially
3300 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003301
Andy Hung69488c42016-05-16 18:43:33 -07003302 // it's OK if deltaMs is an overestimate.
3303 const int32_t deltaMs =
3304 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003305 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3306 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3307 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003308 // notify of throttle start on verbose log
3309 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3310 "mixer(%p) throttle begin:"
3311 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003312 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003313 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003314 // Throttle must be attributed to the previous mixer loop's write time
3315 // to allow back-to-back throttling.
3316 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003317 } else {
3318 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3319 if (diff > 0) {
3320 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003321 // but prevent spamming for bluetooth
3322 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3323 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003324 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3325 }
Andy Hung08fb1742015-05-31 23:22:10 -07003326 }
3327 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003328 }
Eric Laurent81784c32012-11-19 14:55:58 -08003329
Eric Laurentbfb1b832013-01-07 09:53:42 -08003330 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003331 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003332 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003333 // suspended requires accurate metering of sleep time.
3334 if (isSuspended()) {
3335 // advance by expected sleepTime
3336 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3337 const nsecs_t nowNs = systemTime();
3338
3339 // compute expected next time vs current time.
3340 // (negative deltas are treated as delays).
3341 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3342 if (deltaNs < -kMaxNextBufferDelayNs) {
3343 // Delays longer than the max allowed trigger a reset.
3344 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3345 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3346 timeLoopNextNs = nowNs + deltaNs;
3347 } else if (deltaNs < 0) {
3348 // Delays within the max delay allowed: zero the delta/sleepTime
3349 // to help the system catch up in the next iteration(s)
3350 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3351 deltaNs = 0;
3352 }
3353 // update sleep time (which is >= 0)
3354 mSleepTimeUs = deltaNs / 1000;
3355 }
Eric Laurente93cc032016-05-05 10:15:10 -07003356 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3357 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003358 }
Glenn Kastene7754022014-10-31 12:11:26 -07003359 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 }
Eric Laurent81784c32012-11-19 14:55:58 -08003361 }
3362
3363 // Finally let go of removed track(s), without the lock held
3364 // since we can't guarantee the destructors won't acquire that
3365 // same lock. This will also mutate and push a new fast mixer state.
3366 threadLoop_removeTracks(tracksToRemove);
3367 tracksToRemove.clear();
3368
3369 // FIXME I don't understand the need for this here;
3370 // it was in the original code but maybe the
3371 // assignment in saveOutputTracks() makes this unnecessary?
3372 clearOutputTracks();
3373
3374 // Effect chains will be actually deleted here if they were removed from
3375 // mEffectChains list during mixing or effects processing
3376 effectChains.clear();
3377
3378 // FIXME Note that the above .clear() is no longer necessary since effectChains
3379 // is now local to this block, but will keep it for now (at least until merge done).
3380 }
3381
Eric Laurentbfb1b832013-01-07 09:53:42 -08003382 threadLoop_exit();
3383
Eric Laurentcf817a22014-08-04 20:36:31 -07003384 if (!mStandby) {
3385 threadLoop_standby();
3386 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003387 }
3388
3389 releaseWakeLock();
3390
3391 ALOGV("Thread %p type %d exiting", this, mType);
3392 return false;
3393}
3394
Eric Laurentbfb1b832013-01-07 09:53:42 -08003395// removeTracks_l() must be called with ThreadBase::mLock held
3396void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3397{
3398 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003399 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400 for (size_t i=0 ; i<count ; i++) {
3401 const sp<Track>& track = tracksToRemove.itemAt(i);
3402 mActiveTracks.remove(track);
3403 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3404 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3405 if (chain != 0) {
3406 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3407 track->sessionId());
3408 chain->decActiveTrackCnt();
3409 }
3410 if (track->isTerminated()) {
3411 removeTrack_l(track);
Andy Hung2148bf02016-11-28 19:01:02 -08003412 } else { // inactive but not terminated
3413 char buffer[256];
Mikhail Naganovbf493082017-04-17 17:37:12 -07003414 track->dump(buffer, arraysize(buffer), false /* active */);
Andy Hung2148bf02016-11-28 19:01:02 -08003415 mLocalLog.log("removeTracks_l(%p) %s", track.get(), buffer + 4);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003416 }
3417 }
3418 }
3419
3420}
Eric Laurent81784c32012-11-19 14:55:58 -08003421
Eric Laurentaccc1472013-09-20 09:36:34 -07003422status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3423{
3424 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003425 ExtendedTimestamp ets;
3426 status_t status = mNormalSink->getTimestamp(ets);
3427 if (status == NO_ERROR) {
3428 status = ets.getBestTimestamp(&timestamp);
3429 }
3430 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003431 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003432 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003433 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003434 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003435 timestamp.mPosition = (uint32_t)position64;
3436 return NO_ERROR;
3437 }
3438 }
3439 return INVALID_OPERATION;
3440}
Eric Laurent1c333e22014-05-20 10:48:17 -07003441
Eric Laurent054d9d32015-04-24 08:48:48 -07003442status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3443 audio_patch_handle_t *handle)
3444{
Andy Hungf60abce2016-08-26 11:37:54 -07003445 status_t status;
3446 if (property_get_bool("af.patch_park", false /* default_value */)) {
3447 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3448 // or if HAL does not properly lock against access.
3449 AutoPark<FastMixer> park(mFastMixer);
3450 status = PlaybackThread::createAudioPatch_l(patch, handle);
3451 } else {
3452 status = PlaybackThread::createAudioPatch_l(patch, handle);
3453 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003454 return status;
3455}
3456
Eric Laurent1c333e22014-05-20 10:48:17 -07003457status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3458 audio_patch_handle_t *handle)
3459{
3460 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003461
3462 // store new device and send to effects
3463 audio_devices_t type = AUDIO_DEVICE_NONE;
3464 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3465 type |= patch->sinks[i].ext.device.type;
3466 }
3467
3468#ifdef ADD_BATTERY_DATA
3469 // when changing the audio output device, call addBatteryData to notify
3470 // the change
3471 if (mOutDevice != type) {
3472 uint32_t params = 0;
3473 // check whether speaker is on
3474 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3475 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003476 }
3477
Eric Laurent054d9d32015-04-24 08:48:48 -07003478 audio_devices_t deviceWithoutSpeaker
3479 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3480 // check if any other device (except speaker) is on
3481 if (type & deviceWithoutSpeaker) {
3482 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3483 }
3484
3485 if (params != 0) {
3486 addBatteryData(params);
3487 }
3488 }
3489#endif
3490
3491 for (size_t i = 0; i < mEffectChains.size(); i++) {
3492 mEffectChains[i]->setDevice_l(type);
3493 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003494
3495 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3496 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3497 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003498 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003499 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003500
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003501 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003502 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3503 status = hwDevice->createAudioPatch(patch->num_sources,
3504 patch->sources,
3505 patch->num_sinks,
3506 patch->sinks,
3507 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003508 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003509 char *address;
3510 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3511 //FIXME: we only support address on first sink with HAL version < 3.0
3512 address = audio_device_address_to_parameter(
3513 patch->sinks[0].ext.device.type,
3514 patch->sinks[0].ext.device.address);
3515 } else {
3516 address = (char *)calloc(1, 1);
3517 }
3518 AudioParameter param = AudioParameter(String8(address));
3519 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003520 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003521 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003522 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003523 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003524 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003525 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003526 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3527 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003528 return status;
3529}
3530
Eric Laurent054d9d32015-04-24 08:48:48 -07003531status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3532{
Andy Hungf60abce2016-08-26 11:37:54 -07003533 status_t status;
3534 if (property_get_bool("af.patch_park", false /* default_value */)) {
3535 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3536 // or if HAL does not properly lock against access.
3537 AutoPark<FastMixer> park(mFastMixer);
3538 status = PlaybackThread::releaseAudioPatch_l(handle);
3539 } else {
3540 status = PlaybackThread::releaseAudioPatch_l(handle);
3541 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003542 return status;
3543}
3544
Eric Laurent1c333e22014-05-20 10:48:17 -07003545status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3546{
3547 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003548
3549 mOutDevice = AUDIO_DEVICE_NONE;
3550
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003551 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003552 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3553 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003554 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003555 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003556 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003557 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003558 }
3559 return status;
3560}
3561
Eric Laurent83b88082014-06-20 18:31:16 -07003562void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3563{
3564 Mutex::Autolock _l(mLock);
3565 mTracks.add(track);
3566}
3567
3568void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3569{
3570 Mutex::Autolock _l(mLock);
3571 destroyTrack_l(track);
3572}
3573
3574void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3575{
3576 ThreadBase::getAudioPortConfig(config);
3577 config->role = AUDIO_PORT_ROLE_SOURCE;
3578 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3579 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3580}
3581
Eric Laurent81784c32012-11-19 14:55:58 -08003582// ----------------------------------------------------------------------------
3583
3584AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003585 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3586 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003587 // mAudioMixer below
3588 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003589 mFastMixerFutex(0),
3590 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003591 // mOutputSink below
3592 // mPipeSink below
3593 // mNormalSink below
3594{
3595 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003596 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3597 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003598 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3599 mNormalFrameCount);
3600 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3601
Andy Hungfbfc3952015-01-15 13:33:51 -08003602 if (type == DUPLICATING) {
3603 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3604 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3605 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3606 return;
3607 }
Eric Laurent81784c32012-11-19 14:55:58 -08003608 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003609 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003610 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003611 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003612#if !LOG_NDEBUG
3613 ssize_t index =
3614#else
3615 (void)
3616#endif
3617 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003618 ALOG_ASSERT(index == 0);
3619
3620 // initialize fast mixer depending on configuration
3621 bool initFastMixer;
3622 switch (kUseFastMixer) {
3623 case FastMixer_Never:
3624 initFastMixer = false;
3625 break;
3626 case FastMixer_Always:
3627 initFastMixer = true;
3628 break;
3629 case FastMixer_Static:
3630 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003631 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3632 // where the period is less than an experimentally determined threshold that can be
3633 // scheduled reliably with CFS. However, the BT A2DP HAL is
3634 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3635 initFastMixer = mFrameCount < mNormalFrameCount
3636 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003637 break;
3638 }
Andy Hungfda69402017-02-15 14:33:12 -08003639 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3640 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3641 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003642 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003643 audio_format_t fastMixerFormat;
3644 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3645 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3646 } else {
3647 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3648 }
3649 if (mFormat != fastMixerFormat) {
3650 // change our Sink format to accept our intermediate precision
3651 mFormat = fastMixerFormat;
3652 free(mSinkBuffer);
3653 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3654 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3655 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3656 }
Eric Laurent81784c32012-11-19 14:55:58 -08003657
3658 // create a MonoPipe to connect our submix to FastMixer
3659 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003660#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003661 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003662#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003663 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003664 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003665 format.mFormat = fastMixerFormat;
3666 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3667
Eric Laurent81784c32012-11-19 14:55:58 -08003668 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3669 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3670 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3671 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3672 const NBAIO_Format offers[1] = {format};
3673 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003674#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003675 ssize_t index =
3676#else
3677 (void)
3678#endif
3679 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003680 ALOG_ASSERT(index == 0);
3681 monoPipe->setAvgFrames((mScreenState & 1) ?
3682 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3683 mPipeSink = monoPipe;
3684
Glenn Kasten46909e72013-02-26 09:20:22 -08003685#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003686 if (mTeeSinkOutputEnabled) {
3687 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003688 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3689 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003690 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003691 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003692 ALOG_ASSERT(index == 0);
3693 mTeeSink = teeSink;
3694 PipeReader *teeSource = new PipeReader(*teeSink);
3695 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003696 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003697 ALOG_ASSERT(index == 0);
3698 mTeeSource = teeSource;
3699 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003700#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003701
3702 // create fast mixer and configure it initially with just one fast track for our submix
3703 mFastMixer = new FastMixer();
3704 FastMixerStateQueue *sq = mFastMixer->sq();
3705#ifdef STATE_QUEUE_DUMP
3706 sq->setObserverDump(&mStateQueueObserverDump);
3707 sq->setMutatorDump(&mStateQueueMutatorDump);
3708#endif
3709 FastMixerState *state = sq->begin();
3710 FastTrack *fastTrack = &state->mFastTracks[0];
3711 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3712 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3713 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003714 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3715 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003716 fastTrack->mGeneration++;
3717 state->mFastTracksGen++;
3718 state->mTrackMask = 1;
3719 // fast mixer will use the HAL output sink
3720 state->mOutputSink = mOutputSink.get();
3721 state->mOutputSinkGen++;
3722 state->mFrameCount = mFrameCount;
3723 state->mCommand = FastMixerState::COLD_IDLE;
3724 // already done in constructor initialization list
3725 //mFastMixerFutex = 0;
3726 state->mColdFutexAddr = &mFastMixerFutex;
3727 state->mColdGen++;
3728 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003729#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003730 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003731#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003732 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3733 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003734 sq->end();
3735 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3736
3737 // start the fast mixer
3738 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3739 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003740 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003741 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003742
3743#ifdef AUDIO_WATCHDOG
3744 // create and start the watchdog
3745 mAudioWatchdog = new AudioWatchdog();
3746 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3747 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3748 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003749 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003750#endif
3751
Eric Laurent81784c32012-11-19 14:55:58 -08003752 }
3753
3754 switch (kUseFastMixer) {
3755 case FastMixer_Never:
3756 case FastMixer_Dynamic:
3757 mNormalSink = mOutputSink;
3758 break;
3759 case FastMixer_Always:
3760 mNormalSink = mPipeSink;
3761 break;
3762 case FastMixer_Static:
3763 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3764 break;
3765 }
3766}
3767
3768AudioFlinger::MixerThread::~MixerThread()
3769{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003770 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003771 FastMixerStateQueue *sq = mFastMixer->sq();
3772 FastMixerState *state = sq->begin();
3773 if (state->mCommand == FastMixerState::COLD_IDLE) {
3774 int32_t old = android_atomic_inc(&mFastMixerFutex);
3775 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003776 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003777 }
3778 }
3779 state->mCommand = FastMixerState::EXIT;
3780 sq->end();
3781 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3782 mFastMixer->join();
3783 // Though the fast mixer thread has exited, it's state queue is still valid.
3784 // We'll use that extract the final state which contains one remaining fast track
3785 // corresponding to our sub-mix.
3786 state = sq->begin();
3787 ALOG_ASSERT(state->mTrackMask == 1);
3788 FastTrack *fastTrack = &state->mFastTracks[0];
3789 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3790 delete fastTrack->mBufferProvider;
3791 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003792 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003793#ifdef AUDIO_WATCHDOG
3794 if (mAudioWatchdog != 0) {
3795 mAudioWatchdog->requestExit();
3796 mAudioWatchdog->requestExitAndWait();
3797 mAudioWatchdog.clear();
3798 }
3799#endif
3800 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003801 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003802 delete mAudioMixer;
3803}
3804
3805
3806uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3807{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003808 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003809 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3810 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3811 }
3812 return latency;
3813}
3814
3815
3816void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3817{
3818 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3819}
3820
Eric Laurentbfb1b832013-01-07 09:53:42 -08003821ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003822{
3823 // FIXME we should only do one push per cycle; confirm this is true
3824 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003825 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003826 FastMixerStateQueue *sq = mFastMixer->sq();
3827 FastMixerState *state = sq->begin();
3828 if (state->mCommand != FastMixerState::MIX_WRITE &&
3829 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3830 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003831
3832 // FIXME workaround for first HAL write being CPU bound on some devices
3833 ATRACE_BEGIN("write");
3834 mOutput->write((char *)mSinkBuffer, 0);
3835 ATRACE_END();
3836
Eric Laurent81784c32012-11-19 14:55:58 -08003837 int32_t old = android_atomic_inc(&mFastMixerFutex);
3838 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003839 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003840 }
3841#ifdef AUDIO_WATCHDOG
3842 if (mAudioWatchdog != 0) {
3843 mAudioWatchdog->resume();
3844 }
3845#endif
3846 }
3847 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003848#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003849 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003850 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003851#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003852 sq->end();
3853 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3854 if (kUseFastMixer == FastMixer_Dynamic) {
3855 mNormalSink = mPipeSink;
3856 }
3857 } else {
3858 sq->end(false /*didModify*/);
3859 }
3860 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003862}
3863
3864void AudioFlinger::MixerThread::threadLoop_standby()
3865{
3866 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003867 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003868 FastMixerStateQueue *sq = mFastMixer->sq();
3869 FastMixerState *state = sq->begin();
3870 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003871 // Report any frames trapped in the Monopipe
3872 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3873 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3874 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3875 "monoPipeWritten:%lld monoPipeLeft:%lld",
3876 (long long)mFramesWritten, (long long)mSuspendedFrames,
3877 (long long)mPipeSink->framesWritten(), pipeFrames);
3878 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3879
Eric Laurent81784c32012-11-19 14:55:58 -08003880 state->mCommand = FastMixerState::COLD_IDLE;
3881 state->mColdFutexAddr = &mFastMixerFutex;
3882 state->mColdGen++;
3883 mFastMixerFutex = 0;
3884 sq->end();
3885 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3886 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3887 if (kUseFastMixer == FastMixer_Dynamic) {
3888 mNormalSink = mOutputSink;
3889 }
3890#ifdef AUDIO_WATCHDOG
3891 if (mAudioWatchdog != 0) {
3892 mAudioWatchdog->pause();
3893 }
3894#endif
3895 } else {
3896 sq->end(false /*didModify*/);
3897 }
3898 }
3899 PlaybackThread::threadLoop_standby();
3900}
3901
Eric Laurentbfb1b832013-01-07 09:53:42 -08003902bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3903{
3904 return false;
3905}
3906
3907bool AudioFlinger::PlaybackThread::shouldStandby_l()
3908{
3909 return !mStandby;
3910}
3911
3912bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3913{
3914 Mutex::Autolock _l(mLock);
3915 return waitingAsyncCallback_l();
3916}
3917
Eric Laurent81784c32012-11-19 14:55:58 -08003918// shared by MIXER and DIRECT, overridden by DUPLICATING
3919void AudioFlinger::PlaybackThread::threadLoop_standby()
3920{
3921 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003922 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003923 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003924 // discard any pending drain or write ack by incrementing sequence
3925 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3926 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003927 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003928 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3929 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003931 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003932}
3933
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003934void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3935{
3936 ALOGV("signal playback thread");
3937 broadcast_l();
3938}
3939
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003940void AudioFlinger::PlaybackThread::onAsyncError()
3941{
3942 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3943 invalidateTracks((audio_stream_type_t)i);
3944 }
3945}
3946
Eric Laurent81784c32012-11-19 14:55:58 -08003947void AudioFlinger::MixerThread::threadLoop_mix()
3948{
Eric Laurent81784c32012-11-19 14:55:58 -08003949 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003950 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003951 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003952 // increase sleep time progressively when application underrun condition clears.
3953 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3954 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3955 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003956 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003957 sleepTimeShift--;
3958 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003959 mSleepTimeUs = 0;
3960 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003961 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003962
Eric Laurent81784c32012-11-19 14:55:58 -08003963}
3964
3965void AudioFlinger::MixerThread::threadLoop_sleepTime()
3966{
3967 // If no tracks are ready, sleep once for the duration of an output
3968 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003969 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003970 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003971 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3972 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3973 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003974 }
3975 // reduce sleep time in case of consecutive application underruns to avoid
3976 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3977 // duration we would end up writing less data than needed by the audio HAL if
3978 // the condition persists.
3979 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3980 sleepTimeShift++;
3981 }
3982 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003983 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003984 }
3985 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003986 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3987 // before effects processing or output.
3988 if (mMixerBufferValid) {
3989 memset(mMixerBuffer, 0, mMixerBufferSize);
3990 } else {
3991 memset(mSinkBuffer, 0, mSinkBufferSize);
3992 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003993 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003994 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3995 "anticipated start");
3996 }
3997 // TODO add standby time extension fct of effect tail
3998}
3999
4000// prepareTracks_l() must be called with ThreadBase::mLock held
4001AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4002 Vector< sp<Track> > *tracksToRemove)
4003{
4004
4005 mixer_state mixerStatus = MIXER_IDLE;
4006 // find out which tracks need to be processed
4007 size_t count = mActiveTracks.size();
4008 size_t mixedTracks = 0;
4009 size_t tracksWithEffect = 0;
4010 // counts only _active_ fast tracks
4011 size_t fastTracks = 0;
4012 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4013
4014 float masterVolume = mMasterVolume;
4015 bool masterMute = mMasterMute;
4016
4017 if (masterMute) {
4018 masterVolume = 0;
4019 }
4020 // Delegate master volume control to effect in output mix effect chain if needed
4021 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4022 if (chain != 0) {
4023 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4024 chain->setVolume_l(&v, &v);
4025 masterVolume = (float)((v + (1 << 23)) >> 24);
4026 chain.clear();
4027 }
4028
4029 // prepare a new state to push
4030 FastMixerStateQueue *sq = NULL;
4031 FastMixerState *state = NULL;
4032 bool didModify = false;
4033 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004034 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004035 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004036 sq = mFastMixer->sq();
4037 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004038 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004039 }
4040
Andy Hung69aed5f2014-02-25 17:24:40 -08004041 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004042 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004043
Eric Laurent81784c32012-11-19 14:55:58 -08004044 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004045 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004046
4047 // this const just means the local variable doesn't change
4048 Track* const track = t.get();
4049
4050 // process fast tracks
4051 if (track->isFastTrack()) {
4052
4053 // It's theoretically possible (though unlikely) for a fast track to be created
4054 // and then removed within the same normal mix cycle. This is not a problem, as
4055 // the track never becomes active so it's fast mixer slot is never touched.
4056 // The converse, of removing an (active) track and then creating a new track
4057 // at the identical fast mixer slot within the same normal mix cycle,
4058 // is impossible because the slot isn't marked available until the end of each cycle.
4059 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004060 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004061 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4062 FastTrack *fastTrack = &state->mFastTracks[j];
4063
4064 // Determine whether the track is currently in underrun condition,
4065 // and whether it had a recent underrun.
4066 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4067 FastTrackUnderruns underruns = ftDump->mUnderruns;
4068 uint32_t recentFull = (underruns.mBitFields.mFull -
4069 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4070 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4071 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4072 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4073 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4074 uint32_t recentUnderruns = recentPartial + recentEmpty;
4075 track->mObservedUnderruns = underruns;
4076 // don't count underruns that occur while stopping or pausing
4077 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004078 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4079 recentUnderruns > 0) {
4080 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4081 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004082 } else {
4083 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004084 }
4085
4086 // This is similar to the state machine for normal tracks,
4087 // with a few modifications for fast tracks.
4088 bool isActive = true;
4089 switch (track->mState) {
4090 case TrackBase::STOPPING_1:
4091 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004092 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004093 track->mState = TrackBase::STOPPING_2;
4094 }
4095 break;
4096 case TrackBase::PAUSING:
4097 // ramp down is not yet implemented
4098 track->setPaused();
4099 break;
4100 case TrackBase::RESUMING:
4101 // ramp up is not yet implemented
4102 track->mState = TrackBase::ACTIVE;
4103 break;
4104 case TrackBase::ACTIVE:
4105 if (recentFull > 0 || recentPartial > 0) {
4106 // track has provided at least some frames recently: reset retry count
4107 track->mRetryCount = kMaxTrackRetries;
4108 }
4109 if (recentUnderruns == 0) {
4110 // no recent underruns: stay active
4111 break;
4112 }
4113 // there has recently been an underrun of some kind
4114 if (track->sharedBuffer() == 0) {
4115 // were any of the recent underruns "empty" (no frames available)?
4116 if (recentEmpty == 0) {
4117 // no, then ignore the partial underruns as they are allowed indefinitely
4118 break;
4119 }
4120 // there has recently been an "empty" underrun: decrement the retry counter
4121 if (--(track->mRetryCount) > 0) {
4122 break;
4123 }
4124 // indicate to client process that the track was disabled because of underrun;
4125 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004126 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004127 // remove from active list, but state remains ACTIVE [confusing but true]
4128 isActive = false;
4129 break;
4130 }
4131 // fall through
4132 case TrackBase::STOPPING_2:
4133 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004134 case TrackBase::STOPPED:
4135 case TrackBase::FLUSHED: // flush() while active
4136 // Check for presentation complete if track is inactive
4137 // We have consumed all the buffers of this track.
4138 // This would be incomplete if we auto-paused on underrun
4139 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004140 uint32_t latency = 0;
4141 status_t result = mOutput->stream->getLatency(&latency);
4142 ALOGE_IF(result != OK,
4143 "Error when retrieving output stream latency: %d", result);
4144 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004145 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004146 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4147 // track stays in active list until presentation is complete
4148 break;
4149 }
4150 }
4151 if (track->isStopping_2()) {
4152 track->mState = TrackBase::STOPPED;
4153 }
4154 if (track->isStopped()) {
4155 // Can't reset directly, as fast mixer is still polling this track
4156 // track->reset();
4157 // So instead mark this track as needing to be reset after push with ack
4158 resetMask |= 1 << i;
4159 }
4160 isActive = false;
4161 break;
4162 case TrackBase::IDLE:
4163 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004164 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004165 }
4166
4167 if (isActive) {
4168 // was it previously inactive?
4169 if (!(state->mTrackMask & (1 << j))) {
4170 ExtendedAudioBufferProvider *eabp = track;
4171 VolumeProvider *vp = track;
4172 fastTrack->mBufferProvider = eabp;
4173 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004174 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004175 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004176 fastTrack->mGeneration++;
4177 state->mTrackMask |= 1 << j;
4178 didModify = true;
4179 // no acknowledgement required for newly active tracks
4180 }
4181 // cache the combined master volume and stream type volume for fast mixer; this
4182 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004183 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004184 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004185 track->mCachedVolume = masterVolume
4186 * mStreamTypes[track->streamType()].volume
4187 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004188 ++fastTracks;
4189 } else {
4190 // was it previously active?
4191 if (state->mTrackMask & (1 << j)) {
4192 fastTrack->mBufferProvider = NULL;
4193 fastTrack->mGeneration++;
4194 state->mTrackMask &= ~(1 << j);
4195 didModify = true;
4196 // If any fast tracks were removed, we must wait for acknowledgement
4197 // because we're about to decrement the last sp<> on those tracks.
4198 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4199 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004200 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4201 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4202 j, track->mState, state->mTrackMask, recentUnderruns,
4203 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004204 }
4205 tracksToRemove->add(track);
4206 // Avoids a misleading display in dumpsys
4207 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4208 }
4209 continue;
4210 }
4211
4212 { // local variable scope to avoid goto warning
4213
4214 audio_track_cblk_t* cblk = track->cblk();
4215
4216 // The first time a track is added we wait
4217 // for all its buffers to be filled before processing it
4218 int name = track->name();
4219 // make sure that we have enough frames to mix one full buffer.
4220 // enforce this condition only once to enable draining the buffer in case the client
4221 // app does not call stop() and relies on underrun to stop:
4222 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4223 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004224 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004225 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004226 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004227
4228 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004229 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004230 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4231 // add frames already consumed but not yet released by the resampler
4232 // because mAudioTrackServerProxy->framesReady() will include these frames
4233 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4234
Eric Laurent81784c32012-11-19 14:55:58 -08004235 uint32_t minFrames = 1;
4236 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4237 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004238 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004239 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004240
4241 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004242 if (ATRACE_ENABLED()) {
4243 // I wish we had formatted trace names
4244 char traceName[16];
4245 strcpy(traceName, "nRdy");
4246 int name = track->name();
4247 if (AudioMixer::TRACK0 <= name &&
4248 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4249 name -= AudioMixer::TRACK0;
4250 traceName[4] = (name / 10) + '0';
4251 traceName[5] = (name % 10) + '0';
4252 } else {
4253 traceName[4] = '?';
4254 traceName[5] = '?';
4255 }
4256 traceName[6] = '\0';
4257 ATRACE_INT(traceName, framesReady);
4258 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004259 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004260 !track->isPaused() && !track->isTerminated())
4261 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004262 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004263
4264 mixedTracks++;
4265
Andy Hung69aed5f2014-02-25 17:24:40 -08004266 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4267 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004268 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004269 if (track->mainBuffer() != mSinkBuffer &&
4270 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004271 if (mEffectBufferEnabled) {
4272 mEffectBufferValid = true; // Later can set directly.
4273 }
Eric Laurent81784c32012-11-19 14:55:58 -08004274 chain = getEffectChain_l(track->sessionId());
4275 // Delegate volume control to effect in track effect chain if needed
4276 if (chain != 0) {
4277 tracksWithEffect++;
4278 } else {
4279 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4280 "session %d",
4281 name, track->sessionId());
4282 }
4283 }
4284
4285
4286 int param = AudioMixer::VOLUME;
4287 if (track->mFillingUpStatus == Track::FS_FILLED) {
4288 // no ramp for the first volume setting
4289 track->mFillingUpStatus = Track::FS_ACTIVE;
4290 if (track->mState == TrackBase::RESUMING) {
4291 track->mState = TrackBase::ACTIVE;
4292 param = AudioMixer::RAMP_VOLUME;
4293 }
4294 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004295 // FIXME should not make a decision based on mServer
4296 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004297 // If the track is stopped before the first frame was mixed,
4298 // do not apply ramp
4299 param = AudioMixer::RAMP_VOLUME;
4300 }
4301
4302 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004303 uint32_t vl, vr; // in U8.24 integer format
4304 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004305 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004306 vl = vr = 0;
4307 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004308 if (track->isPausing()) {
4309 track->setPaused();
4310 }
4311 } else {
4312
4313 // read original volumes with volume control
4314 float typeVolume = mStreamTypes[track->streamType()].volume;
4315 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004316 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004317 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004318 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4319 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004320 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004321 if (vlf > GAIN_FLOAT_UNITY) {
4322 ALOGV("Track left volume out of range: %.3g", vlf);
4323 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004324 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004325 if (vrf > GAIN_FLOAT_UNITY) {
4326 ALOGV("Track right volume out of range: %.3g", vrf);
4327 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004328 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004329 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004330 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004331 // now apply the master volume and stream type volume and shaper volume
4332 vlf *= v * vh;
4333 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004334 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004335 // then derive vl and vr as U8.24 versions for the effect chain
4336 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4337 vl = (uint32_t) (scaleto8_24 * vlf);
4338 vr = (uint32_t) (scaleto8_24 * vrf);
4339 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004340 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004341 // send level comes from shared memory and so may be corrupt
4342 if (sendLevel > MAX_GAIN_INT) {
4343 ALOGV("Track send level out of range: %04X", sendLevel);
4344 sendLevel = MAX_GAIN_INT;
4345 }
Andy Hung6be49402014-05-30 10:42:03 -07004346 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4347 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004348 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004349
Eric Laurent81784c32012-11-19 14:55:58 -08004350 // Delegate volume control to effect in track effect chain if needed
4351 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4352 // Do not ramp volume if volume is controlled by effect
4353 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004354 // Update remaining floating point volume levels
4355 vlf = (float)vl / (1 << 24);
4356 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004357 track->mHasVolumeController = true;
4358 } else {
4359 // force no volume ramp when volume controller was just disabled or removed
4360 // from effect chain to avoid volume spike
4361 if (track->mHasVolumeController) {
4362 param = AudioMixer::VOLUME;
4363 }
4364 track->mHasVolumeController = false;
4365 }
4366
Eric Laurent81784c32012-11-19 14:55:58 -08004367 // XXX: these things DON'T need to be done each time
4368 mAudioMixer->setBufferProvider(name, track);
4369 mAudioMixer->enable(name);
4370
Andy Hung6be49402014-05-30 10:42:03 -07004371 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4372 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4373 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004374 mAudioMixer->setParameter(
4375 name,
4376 AudioMixer::TRACK,
4377 AudioMixer::FORMAT, (void *)track->format());
4378 mAudioMixer->setParameter(
4379 name,
4380 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004381 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004382 mAudioMixer->setParameter(
4383 name,
4384 AudioMixer::TRACK,
4385 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004386 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004387 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004388 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004389 if (reqSampleRate == 0) {
4390 reqSampleRate = mSampleRate;
4391 } else if (reqSampleRate > maxSampleRate) {
4392 reqSampleRate = maxSampleRate;
4393 }
Eric Laurent81784c32012-11-19 14:55:58 -08004394 mAudioMixer->setParameter(
4395 name,
4396 AudioMixer::RESAMPLE,
4397 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004398 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004399
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004400 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004401 mAudioMixer->setParameter(
4402 name,
4403 AudioMixer::TIMESTRETCH,
4404 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004405 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004406
Andy Hung69aed5f2014-02-25 17:24:40 -08004407 /*
4408 * Select the appropriate output buffer for the track.
4409 *
Andy Hung98ef9782014-03-04 14:46:50 -08004410 * Tracks with effects go into their own effects chain buffer
4411 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004412 *
4413 * Other tracks can use mMixerBuffer for higher precision
4414 * channel accumulation. If this buffer is enabled
4415 * (mMixerBufferEnabled true), then selected tracks will accumulate
4416 * into it.
4417 *
4418 */
4419 if (mMixerBufferEnabled
4420 && (track->mainBuffer() == mSinkBuffer
4421 || track->mainBuffer() == mMixerBuffer)) {
4422 mAudioMixer->setParameter(
4423 name,
4424 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004425 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004426 mAudioMixer->setParameter(
4427 name,
4428 AudioMixer::TRACK,
4429 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4430 // TODO: override track->mainBuffer()?
4431 mMixerBufferValid = true;
4432 } else {
4433 mAudioMixer->setParameter(
4434 name,
4435 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004436 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004437 mAudioMixer->setParameter(
4438 name,
4439 AudioMixer::TRACK,
4440 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4441 }
Eric Laurent81784c32012-11-19 14:55:58 -08004442 mAudioMixer->setParameter(
4443 name,
4444 AudioMixer::TRACK,
4445 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4446
4447 // reset retry count
4448 track->mRetryCount = kMaxTrackRetries;
4449
4450 // If one track is ready, set the mixer ready if:
4451 // - the mixer was not ready during previous round OR
4452 // - no other track is not ready
4453 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4454 mixerStatus != MIXER_TRACKS_ENABLED) {
4455 mixerStatus = MIXER_TRACKS_READY;
4456 }
4457 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004458 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004459 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4460 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004461 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004462 } else {
4463 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004464 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004465
Eric Laurent81784c32012-11-19 14:55:58 -08004466 // clear effect chain input buffer if an active track underruns to avoid sending
4467 // previous audio buffer again to effects
4468 chain = getEffectChain_l(track->sessionId());
4469 if (chain != 0) {
4470 chain->clearInputBuffer();
4471 }
4472
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004473 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004474 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4475 track->isStopped() || track->isPaused()) {
4476 // We have consumed all the buffers of this track.
4477 // Remove it from the list of active tracks.
4478 // TODO: use actual buffer filling status instead of latency when available from
4479 // audio HAL
4480 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004481 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004482 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4483 if (track->isStopped()) {
4484 track->reset();
4485 }
4486 tracksToRemove->add(track);
4487 }
4488 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004489 // No buffers for this track. Give it a few chances to
4490 // fill a buffer, then remove it from active list.
4491 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004492 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004493 tracksToRemove->add(track);
4494 // indicate to client process that the track was disabled because of underrun;
4495 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004496 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004497 // If one track is not ready, mark the mixer also not ready if:
4498 // - the mixer was ready during previous round OR
4499 // - no other track is ready
4500 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4501 mixerStatus != MIXER_TRACKS_READY) {
4502 mixerStatus = MIXER_TRACKS_ENABLED;
4503 }
4504 }
4505 mAudioMixer->disable(name);
4506 }
4507
4508 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004509
4510 }
4511
4512 // Push the new FastMixer state if necessary
4513 bool pauseAudioWatchdog = false;
4514 if (didModify) {
4515 state->mFastTracksGen++;
4516 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4517 if (kUseFastMixer == FastMixer_Dynamic &&
4518 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4519 state->mCommand = FastMixerState::COLD_IDLE;
4520 state->mColdFutexAddr = &mFastMixerFutex;
4521 state->mColdGen++;
4522 mFastMixerFutex = 0;
4523 if (kUseFastMixer == FastMixer_Dynamic) {
4524 mNormalSink = mOutputSink;
4525 }
4526 // If we go into cold idle, need to wait for acknowledgement
4527 // so that fast mixer stops doing I/O.
4528 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4529 pauseAudioWatchdog = true;
4530 }
Eric Laurent81784c32012-11-19 14:55:58 -08004531 }
4532 if (sq != NULL) {
4533 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004534 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4535 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4536 // when bringing the output sink into standby.)
4537 //
4538 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4539 //
4540 // This occurs with BT suspend when we idle the FastMixer with
4541 // active tracks, which may be added or removed.
4542 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004543 }
4544#ifdef AUDIO_WATCHDOG
4545 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4546 mAudioWatchdog->pause();
4547 }
4548#endif
4549
4550 // Now perform the deferred reset on fast tracks that have stopped
4551 while (resetMask != 0) {
4552 size_t i = __builtin_ctz(resetMask);
4553 ALOG_ASSERT(i < count);
4554 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004555 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004556 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4557 track->reset();
4558 }
4559
4560 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004561 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004562
Eric Laurent97d547d2014-09-02 14:45:53 -07004563 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4564 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004565 }
4566
4567 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004568 // as long as there are effects we should clear the effects buffer, to avoid
4569 // passing a non-clean buffer to the effect chain
4570 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004571 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004572 // sink or mix buffer must be cleared if all tracks are connected to an
4573 // effect chain as in this case the mixer will not write to the sink or mix buffer
4574 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004575 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4576 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004577 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004578 if (mMixerBufferValid) {
4579 memset(mMixerBuffer, 0, mMixerBufferSize);
4580 // TODO: In testing, mSinkBuffer below need not be cleared because
4581 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4582 // after mixing.
4583 //
4584 // To enforce this guarantee:
4585 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4586 // (mixedTracks == 0 && fastTracks > 0))
4587 // must imply MIXER_TRACKS_READY.
4588 // Later, we may clear buffers regardless, and skip much of this logic.
4589 }
Andy Hung98ef9782014-03-04 14:46:50 -08004590 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004591 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004592 }
4593
4594 // if any fast tracks, then status is ready
4595 mMixerStatusIgnoringFastTracks = mixerStatus;
4596 if (fastTracks > 0) {
4597 mixerStatus = MIXER_TRACKS_READY;
4598 }
4599 return mixerStatus;
4600}
4601
Eric Laurentad7dd962016-09-22 12:38:37 -07004602// trackCountForUid_l() must be called with ThreadBase::mLock held
4603uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4604{
4605 uint32_t trackCount = 0;
4606 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004607 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004608 trackCount++;
4609 }
4610 }
4611 return trackCount;
4612}
4613
Eric Laurent81784c32012-11-19 14:55:58 -08004614// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004615int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004616 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004617{
Eric Laurentad7dd962016-09-22 12:38:37 -07004618 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4619 return -1;
4620 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004621 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004622}
4623
4624// deleteTrackName_l() must be called with ThreadBase::mLock held
4625void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4626{
4627 ALOGV("remove track (%d) and delete from mixer", name);
4628 mAudioMixer->deleteTrackName(name);
4629}
4630
Eric Laurent10351942014-05-08 18:49:52 -07004631// checkForNewParameter_l() must be called with ThreadBase::mLock held
4632bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4633 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004634{
Eric Laurent81784c32012-11-19 14:55:58 -08004635 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004636 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004637
Eric Laurent10351942014-05-08 18:49:52 -07004638 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004639
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004640 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004641
Eric Laurent10351942014-05-08 18:49:52 -07004642 AudioParameter param = AudioParameter(keyValuePair);
4643 int value;
4644 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4645 reconfig = true;
4646 }
4647 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004648 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004649 status = BAD_VALUE;
4650 } else {
4651 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004652 reconfig = true;
4653 }
Eric Laurent10351942014-05-08 18:49:52 -07004654 }
4655 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004656 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004657 status = BAD_VALUE;
4658 } else {
4659 // no need to save value, since it's constant
4660 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004661 }
Eric Laurent10351942014-05-08 18:49:52 -07004662 }
4663 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4664 // do not accept frame count changes if tracks are open as the track buffer
4665 // size depends on frame count and correct behavior would not be guaranteed
4666 // if frame count is changed after track creation
4667 if (!mTracks.isEmpty()) {
4668 status = INVALID_OPERATION;
4669 } else {
4670 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004671 }
Eric Laurent10351942014-05-08 18:49:52 -07004672 }
4673 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004674#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004675 // when changing the audio output device, call addBatteryData to notify
4676 // the change
4677 if (mOutDevice != value) {
4678 uint32_t params = 0;
4679 // check whether speaker is on
4680 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4681 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
Eric Laurent10351942014-05-08 18:49:52 -07004683
4684 audio_devices_t deviceWithoutSpeaker
4685 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4686 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004687 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004688 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4689 }
4690
4691 if (params != 0) {
4692 addBatteryData(params);
4693 }
4694 }
Eric Laurent81784c32012-11-19 14:55:58 -08004695#endif
4696
Eric Laurent10351942014-05-08 18:49:52 -07004697 // forward device change to effects that have requested to be
4698 // aware of attached audio device.
4699 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004700 a2dpDeviceChanged =
4701 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004702 mOutDevice = value;
4703 for (size_t i = 0; i < mEffectChains.size(); i++) {
4704 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004705 }
4706 }
Eric Laurent10351942014-05-08 18:49:52 -07004707 }
Eric Laurent81784c32012-11-19 14:55:58 -08004708
Eric Laurent10351942014-05-08 18:49:52 -07004709 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004710 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004711 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004712 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004713 mStandby = true;
4714 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004715 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004716 }
Eric Laurent10351942014-05-08 18:49:52 -07004717 if (status == NO_ERROR && reconfig) {
4718 readOutputParameters_l();
4719 delete mAudioMixer;
4720 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4721 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004722 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004723 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004724 if (name < 0) {
4725 break;
4726 }
4727 mTracks[i]->mName = name;
4728 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004729 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004730 }
Eric Laurent81784c32012-11-19 14:55:58 -08004731 }
4732
Eric Laurent42537be2016-01-08 17:16:42 -08004733 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004734}
4735
4736
4737void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4738{
Eric Laurent81784c32012-11-19 14:55:58 -08004739 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004740 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004741 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004742 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004743
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004744 if (hasFastMixer()) {
4745 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4746
4747 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4748 // while we are dumping it. It may be inconsistent, but it won't mutate!
4749 // This is a large object so we place it on the heap.
4750 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4751 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4752 copy->dump(fd);
4753 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004754
4755#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004756 // Similar for state queue
4757 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4758 observerCopy.dump(fd);
4759 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4760 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004761#endif
4762
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004763#ifdef AUDIO_WATCHDOG
4764 if (mAudioWatchdog != 0) {
4765 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4766 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4767 wdCopy.dump(fd);
4768 }
4769#endif
4770
4771 } else {
4772 dprintf(fd, " No FastMixer\n");
4773 }
4774
Glenn Kasten46909e72013-02-26 09:20:22 -08004775#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004776 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004777 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004778#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004779
Eric Laurent81784c32012-11-19 14:55:58 -08004780}
4781
4782uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4783{
4784 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4785}
4786
4787uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4788{
4789 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4790}
4791
4792void AudioFlinger::MixerThread::cacheParameters_l()
4793{
4794 PlaybackThread::cacheParameters_l();
4795
4796 // FIXME: Relaxed timing because of a certain device that can't meet latency
4797 // Should be reduced to 2x after the vendor fixes the driver issue
4798 // increase threshold again due to low power audio mode. The way this warning
4799 // threshold is calculated and its usefulness should be reconsidered anyway.
4800 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4801}
4802
4803// ----------------------------------------------------------------------------
4804
4805AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004806 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4807 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004808 // mLeftVolFloat, mRightVolFloat
4809{
4810}
4811
Eric Laurentbfb1b832013-01-07 09:53:42 -08004812AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4813 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004814 ThreadBase::type_t type, bool systemReady)
4815 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004816 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004817 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004818{
4819}
4820
Eric Laurent81784c32012-11-19 14:55:58 -08004821AudioFlinger::DirectOutputThread::~DirectOutputThread()
4822{
4823}
4824
Eric Laurent5850c4c2016-11-10 13:04:31 -08004825void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004826{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004827 float left, right;
4828
4829 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4830 left = right = 0;
4831 } else {
4832 float typeVolume = mStreamTypes[track->streamType()].volume;
4833 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004834 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004835
Andy Hung10cbff12017-02-21 17:30:14 -08004836 // Get volumeshaper scaling
4837 std::pair<float /* volume */, bool /* active */>
4838 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004839 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004840 v *= vh.first;
4841 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004842
Glenn Kastenc56f3422014-03-21 17:53:17 -07004843 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4844 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4845 if (left > GAIN_FLOAT_UNITY) {
4846 left = GAIN_FLOAT_UNITY;
4847 }
4848 left *= v;
4849 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4850 if (right > GAIN_FLOAT_UNITY) {
4851 right = GAIN_FLOAT_UNITY;
4852 }
4853 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004854 }
4855
4856 if (lastTrack) {
4857 if (left != mLeftVolFloat || right != mRightVolFloat) {
4858 mLeftVolFloat = left;
4859 mRightVolFloat = right;
4860
4861 // Convert volumes from float to 8.24
4862 uint32_t vl = (uint32_t)(left * (1 << 24));
4863 uint32_t vr = (uint32_t)(right * (1 << 24));
4864
4865 // Delegate volume control to effect in track effect chain if needed
4866 // only one effect chain can be present on DirectOutputThread, so if
4867 // there is one, the track is connected to it
4868 if (!mEffectChains.isEmpty()) {
4869 mEffectChains[0]->setVolume_l(&vl, &vr);
4870 left = (float)vl / (1 << 24);
4871 right = (float)vr / (1 << 24);
4872 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004873 status_t result = mOutput->stream->setVolume(left, right);
4874 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004875 }
4876 }
4877}
4878
Phil Burk43b4dcc2015-06-09 16:53:44 -07004879void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4880{
4881 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004882 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004883
Eric Laurent0f0631e2015-07-06 18:01:25 -07004884 if (previousTrack != 0 && latestTrack != 0) {
4885 if (mType == DIRECT) {
4886 if (previousTrack.get() != latestTrack.get()) {
4887 mFlushPending = true;
4888 }
4889 } else /* mType == OFFLOAD */ {
4890 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4891 mFlushPending = true;
4892 }
4893 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004894 }
4895 PlaybackThread::onAddNewTrack_l();
4896}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004897
Eric Laurent81784c32012-11-19 14:55:58 -08004898AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4899 Vector< sp<Track> > *tracksToRemove
4900)
4901{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004902 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004903 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004904 bool doHwPause = false;
4905 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004906
4907 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004908 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004909 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004910 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004911 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004912 continue;
4913 }
4914
Eric Laurent5850c4c2016-11-10 13:04:31 -08004915 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004916#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004917 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004918#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004919 // Only consider last track started for volume and mixer state control.
4920 // In theory an older track could underrun and restart after the new one starts
4921 // but as we only care about the transition phase between two tracks on a
4922 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004923 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004924 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004925
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004926 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004927 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004928 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004929 doHwPause = true;
4930 mHwPaused = true;
4931 }
4932 tracksToRemove->add(track);
4933 } else if (track->isFlushPending()) {
4934 track->flushAck();
4935 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004936 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004937 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004938 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004939 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004940 if (last) {
4941 mLeftVolFloat = mRightVolFloat = -1.0;
4942 if (mHwPaused) {
4943 doHwResume = true;
4944 mHwPaused = false;
4945 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 }
4947 }
4948
Eric Laurent81784c32012-11-19 14:55:58 -08004949 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004950 // for all its buffers to be filled before processing it.
4951 // Allow draining the buffer in case the client
4952 // app does not call stop() and relies on underrun to stop:
4953 // hence the test on (track->mRetryCount > 1).
4954 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004955 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004956 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004957 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004958 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004959 minFrames = mNormalFrameCount;
4960 } else {
4961 minFrames = 1;
4962 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004963
Eric Laurentab5cdba2014-06-09 17:22:27 -07004964 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4965 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004966 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004967 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004968
4969 if (track->mFillingUpStatus == Track::FS_FILLED) {
4970 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004971 if (last) {
4972 // make sure processVolume_l() will apply new volume even if 0
4973 mLeftVolFloat = mRightVolFloat = -1.0;
4974 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004975 if (!mHwSupportsPause) {
4976 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004977 }
4978 }
4979
4980 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004981 processVolume_l(track, last);
4982 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004983 sp<Track> previousTrack = mPreviousTrack.promote();
4984 if (previousTrack != 0) {
4985 if (track != previousTrack.get()) {
4986 // Flush any data still being written from last track
4987 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004988 // Invalidate previous track to force a seek when resuming.
4989 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004990 }
4991 }
4992 mPreviousTrack = track;
4993
Eric Laurentd595b7c2013-04-03 17:27:56 -07004994 // reset retry count
4995 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004996 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004997 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004998 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08004999 doHwResume = true;
5000 mHwPaused = false;
5001 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005002 }
Eric Laurent81784c32012-11-19 14:55:58 -08005003 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005004 // clear effect chain input buffer if the last active track started underruns
5005 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005006 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005007 mEffectChains[0]->clearInputBuffer();
5008 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005009 if (track->isStopping_1()) {
5010 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005011 if (last && mHwPaused) {
5012 doHwResume = true;
5013 mHwPaused = false;
5014 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005015 }
5016 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5017 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005018 // We have consumed all the buffers of this track.
5019 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005020 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005021 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005022 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5023 } else {
5024 audioHALFrames = 0;
5025 }
5026
Andy Hung818e7a32016-02-16 18:08:07 -08005027 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005028 if (mStandby || !last ||
5029 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005030 if (track->isStopping_2()) {
5031 track->mState = TrackBase::STOPPED;
5032 }
Eric Laurent81784c32012-11-19 14:55:58 -08005033 if (track->isStopped()) {
5034 track->reset();
5035 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005036 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005037 }
5038 } else {
5039 // No buffers for this track. Give it a few chances to
5040 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005041 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005042 if (--(track->mRetryCount) <= 0) {
5043 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005044 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005045 // indicate to client process that the track was disabled because of underrun;
5046 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005047 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005048 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005049 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5050 "minFrames = %u, mFormat = %#x",
5051 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005052 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005053 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005054 doHwPause = true;
5055 mHwPaused = true;
5056 }
Eric Laurent81784c32012-11-19 14:55:58 -08005057 }
5058 }
5059 }
5060 }
5061
Eric Laurentd1f69b02014-12-15 14:33:13 -08005062 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005063 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005064 for (size_t i = 0; i < mTracks.size(); i++) {
5065 if (mTracks[i]->isFlushPending()) {
5066 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005067 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005068 }
5069 }
5070 }
5071
5072 // make sure the pause/flush/resume sequence is executed in the right order.
5073 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5074 // before flush and then resume HW. This can happen in case of pause/flush/resume
5075 // if resume is received before pause is executed.
5076 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005077 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005078 status_t result = mOutput->stream->pause();
5079 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005080 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005081 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005082 flushHw_l();
5083 }
5084 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005085 status_t result = mOutput->stream->resume();
5086 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005087 }
Eric Laurent81784c32012-11-19 14:55:58 -08005088 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005089 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005090
5091 return mixerStatus;
5092}
5093
5094void AudioFlinger::DirectOutputThread::threadLoop_mix()
5095{
Eric Laurent81784c32012-11-19 14:55:58 -08005096 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005097 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005098 // output audio to hardware
5099 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005100 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005101 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005102 status_t status = mActiveTrack->getNextBuffer(&buffer);
5103 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005104 // no need to pad with 0 for compressed audio
5105 if (audio_has_proportional_frames(mFormat)) {
5106 memset(curBuf, 0, frameCount * mFrameSize);
5107 }
Eric Laurent81784c32012-11-19 14:55:58 -08005108 break;
5109 }
5110 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5111 frameCount -= buffer.frameCount;
5112 curBuf += buffer.frameCount * mFrameSize;
5113 mActiveTrack->releaseBuffer(&buffer);
5114 }
Andy Hung2098f272014-02-27 14:00:06 -08005115 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005116 mSleepTimeUs = 0;
5117 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005118 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005119}
5120
5121void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5122{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005123 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005124 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005125 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005126 return;
5127 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005128 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005129 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005130 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005131 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005132 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005133 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005134 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005135 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005136 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005137 }
5138}
5139
Eric Laurentd1f69b02014-12-15 14:33:13 -08005140void AudioFlinger::DirectOutputThread::threadLoop_exit()
5141{
5142 {
5143 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005144 for (size_t i = 0; i < mTracks.size(); i++) {
5145 if (mTracks[i]->isFlushPending()) {
5146 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005147 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005148 }
5149 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005150 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005151 flushHw_l();
5152 }
5153 }
5154 PlaybackThread::threadLoop_exit();
5155}
5156
5157// must be called with thread mutex locked
5158bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5159{
5160 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005161 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005162
vivek mehta9cd7ad12016-03-17 00:18:29 -07005163 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5164 return !mStandby;
5165 }
5166
Eric Laurentd1f69b02014-12-15 14:33:13 -08005167 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5168 // after a timeout and we will enter standby then.
5169 if (mTracks.size() > 0) {
5170 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005171 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5172 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005173 }
5174
Eric Laurent5cff4032015-05-26 13:49:58 -07005175 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005176}
5177
Eric Laurent81784c32012-11-19 14:55:58 -08005178// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005179int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005180 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005181{
Eric Laurentad7dd962016-09-22 12:38:37 -07005182 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5183 return -1;
5184 }
Eric Laurent81784c32012-11-19 14:55:58 -08005185 return 0;
5186}
5187
5188// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005189void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005190{
5191}
5192
Eric Laurent10351942014-05-08 18:49:52 -07005193// checkForNewParameter_l() must be called with ThreadBase::mLock held
5194bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5195 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005196{
5197 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005198 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005199
Eric Laurent10351942014-05-08 18:49:52 -07005200 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005201
Eric Laurent10351942014-05-08 18:49:52 -07005202 AudioParameter param = AudioParameter(keyValuePair);
5203 int value;
5204 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5205 // forward device change to effects that have requested to be
5206 // aware of attached audio device.
5207 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005208 a2dpDeviceChanged =
5209 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005210 mOutDevice = value;
5211 for (size_t i = 0; i < mEffectChains.size(); i++) {
5212 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005213 }
5214 }
Eric Laurent81784c32012-11-19 14:55:58 -08005215 }
Eric Laurent10351942014-05-08 18:49:52 -07005216 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5217 // do not accept frame count changes if tracks are open as the track buffer
5218 // size depends on frame count and correct behavior would not be garantied
5219 // if frame count is changed after track creation
5220 if (!mTracks.isEmpty()) {
5221 status = INVALID_OPERATION;
5222 } else {
5223 reconfig = true;
5224 }
5225 }
5226 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005227 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005228 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005229 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005230 mStandby = true;
5231 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005232 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005233 }
5234 if (status == NO_ERROR && reconfig) {
5235 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005236 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005237 }
5238 }
5239
Eric Laurent42537be2016-01-08 17:16:42 -08005240 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005241}
5242
5243uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5244{
5245 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005246 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005247 time = PlaybackThread::activeSleepTimeUs();
5248 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005249 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005250 }
5251 return time;
5252}
5253
5254uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5255{
5256 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005257 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005258 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5259 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005260 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005261 }
5262 return time;
5263}
5264
5265uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5266{
5267 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005268 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005269 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5270 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005271 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005272 }
5273 return time;
5274}
5275
5276void AudioFlinger::DirectOutputThread::cacheParameters_l()
5277{
5278 PlaybackThread::cacheParameters_l();
5279
5280 // use shorter standby delay as on normal output to release
5281 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005282 // no delay on outputs with HW A/V sync
5283 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005284 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005285 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005286 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005287 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005288 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005289 }
Eric Laurent81784c32012-11-19 14:55:58 -08005290}
5291
Eric Laurente659ef42014-09-29 13:06:46 -07005292void AudioFlinger::DirectOutputThread::flushHw_l()
5293{
Phil Burk062e67a2015-02-11 13:40:50 -08005294 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005295 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005296 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005297}
5298
Andy Hung10cbff12017-02-21 17:30:14 -08005299int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5300 // If a VolumeShaper is active, we must wake up periodically to update volume.
5301 const int64_t NS_PER_MS = 1000000;
5302 return mVolumeShaperActive ?
5303 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5304}
5305
Eric Laurent81784c32012-11-19 14:55:58 -08005306// ----------------------------------------------------------------------------
5307
Eric Laurentbfb1b832013-01-07 09:53:42 -08005308AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005309 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005310 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005311 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005312 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005313 mDrainSequence(0),
5314 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005315{
5316}
5317
5318AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5319{
5320}
5321
5322void AudioFlinger::AsyncCallbackThread::onFirstRef()
5323{
5324 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5325}
5326
5327bool AudioFlinger::AsyncCallbackThread::threadLoop()
5328{
5329 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005330 uint32_t writeAckSequence;
5331 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005332 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005333
5334 {
5335 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005336 while (!((mWriteAckSequence & 1) ||
5337 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005338 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005339 exitPending())) {
5340 mWaitWorkCV.wait(mLock);
5341 }
5342
Eric Laurentbfb1b832013-01-07 09:53:42 -08005343 if (exitPending()) {
5344 break;
5345 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005346 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5347 mWriteAckSequence, mDrainSequence);
5348 writeAckSequence = mWriteAckSequence;
5349 mWriteAckSequence &= ~1;
5350 drainSequence = mDrainSequence;
5351 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005352 asyncError = mAsyncError;
5353 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005354 }
5355 {
Eric Laurent4de95592013-09-26 15:28:21 -07005356 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5357 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005358 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005359 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005360 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005361 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005362 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005364 if (asyncError) {
5365 playbackThread->onAsyncError();
5366 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005367 }
5368 }
5369 }
5370 return false;
5371}
5372
5373void AudioFlinger::AsyncCallbackThread::exit()
5374{
5375 ALOGV("AsyncCallbackThread::exit");
5376 Mutex::Autolock _l(mLock);
5377 requestExit();
5378 mWaitWorkCV.broadcast();
5379}
5380
Eric Laurent3b4529e2013-09-05 18:09:19 -07005381void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005382{
5383 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005384 // bit 0 is cleared
5385 mWriteAckSequence = sequence << 1;
5386}
5387
5388void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5389{
5390 Mutex::Autolock _l(mLock);
5391 // ignore unexpected callbacks
5392 if (mWriteAckSequence & 2) {
5393 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394 mWaitWorkCV.signal();
5395 }
5396}
5397
Eric Laurent3b4529e2013-09-05 18:09:19 -07005398void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005399{
5400 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005401 // bit 0 is cleared
5402 mDrainSequence = sequence << 1;
5403}
5404
5405void AudioFlinger::AsyncCallbackThread::resetDraining()
5406{
5407 Mutex::Autolock _l(mLock);
5408 // ignore unexpected callbacks
5409 if (mDrainSequence & 2) {
5410 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005411 mWaitWorkCV.signal();
5412 }
5413}
5414
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005415void AudioFlinger::AsyncCallbackThread::setAsyncError()
5416{
5417 Mutex::Autolock _l(mLock);
5418 mAsyncError = true;
5419 mWaitWorkCV.signal();
5420}
5421
Eric Laurentbfb1b832013-01-07 09:53:42 -08005422
5423// ----------------------------------------------------------------------------
5424AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005425 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5426 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005427 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5428 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429{
Eric Laurentfd477972013-10-25 18:10:40 -07005430 //FIXME: mStandby should be set to true by ThreadBase constructor
5431 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005432 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005433}
5434
Eric Laurentbfb1b832013-01-07 09:53:42 -08005435void AudioFlinger::OffloadThread::threadLoop_exit()
5436{
5437 if (mFlushPending || mHwPaused) {
5438 // If a flush is pending or track was paused, just discard buffered data
5439 flushHw_l();
5440 } else {
5441 mMixerStatus = MIXER_DRAIN_ALL;
5442 threadLoop_drain();
5443 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005444 if (mUseAsyncWrite) {
5445 ALOG_ASSERT(mCallbackThread != 0);
5446 mCallbackThread->exit();
5447 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 PlaybackThread::threadLoop_exit();
5449}
5450
5451AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5452 Vector< sp<Track> > *tracksToRemove
5453)
5454{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005455 size_t count = mActiveTracks.size();
5456
5457 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005458 bool doHwPause = false;
5459 bool doHwResume = false;
5460
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005461 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005462
Eric Laurentbfb1b832013-01-07 09:53:42 -08005463 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005464 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005465 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005466#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005468#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005469 // Only consider last track started for volume and mixer state control.
5470 // In theory an older track could underrun and restart after the new one starts
5471 // but as we only care about the transition phase between two tracks on a
5472 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005473 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005474 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005475
Haynes Mathew George7844f672014-01-15 12:32:55 -08005476 if (track->isInvalid()) {
5477 ALOGW("An invalidated track shouldn't be in active list");
5478 tracksToRemove->add(track);
5479 continue;
5480 }
5481
5482 if (track->mState == TrackBase::IDLE) {
5483 ALOGW("An idle track shouldn't be in active list");
5484 continue;
5485 }
5486
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 if (track->isPausing()) {
5488 track->setPaused();
5489 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005490 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005491 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 mHwPaused = true;
5493 }
5494 // If we were part way through writing the mixbuffer to
5495 // the HAL we must save this until we resume
5496 // BUG - this will be wrong if a different track is made active,
5497 // in that case we want to discard the pending data in the
5498 // mixbuffer and tell the client to present it again when the
5499 // track is resumed
5500 mPausedWriteLength = mCurrentWriteLength;
5501 mPausedBytesRemaining = mBytesRemaining;
5502 mBytesRemaining = 0; // stop writing
5503 }
5504 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005505 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005506 if (track->isStopping_1()) {
5507 track->mRetryCount = kMaxTrackStopRetriesOffload;
5508 } else {
5509 track->mRetryCount = kMaxTrackRetriesOffload;
5510 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005511 track->flushAck();
5512 if (last) {
5513 mFlushPending = true;
5514 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005515 } else if (track->isResumePending()){
5516 track->resumeAck();
5517 if (last) {
5518 if (mPausedBytesRemaining) {
5519 // Need to continue write that was interrupted
5520 mCurrentWriteLength = mPausedWriteLength;
5521 mBytesRemaining = mPausedBytesRemaining;
5522 mPausedBytesRemaining = 0;
5523 }
5524 if (mHwPaused) {
5525 doHwResume = true;
5526 mHwPaused = false;
5527 // threadLoop_mix() will handle the case that we need to
5528 // resume an interrupted write
5529 }
5530 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005531 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005532
Eric Laurent3df841a2016-07-15 15:15:40 -07005533 mLeftVolFloat = mRightVolFloat = -1.0;
5534
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005535 // Do not handle new data in this iteration even if track->framesReady()
5536 mixerStatus = MIXER_TRACKS_ENABLED;
5537 }
5538 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005539 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005540 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541 if (track->mFillingUpStatus == Track::FS_FILLED) {
5542 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005543 if (last) {
5544 // make sure processVolume_l() will apply new volume even if 0
5545 mLeftVolFloat = mRightVolFloat = -1.0;
5546 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005547 }
5548
5549 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005550 sp<Track> previousTrack = mPreviousTrack.promote();
5551 if (previousTrack != 0) {
5552 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005553 // Flush any data still being written from last track
5554 mBytesRemaining = 0;
5555 if (mPausedBytesRemaining) {
5556 // Last track was paused so we also need to flush saved
5557 // mixbuffer state and invalidate track so that it will
5558 // re-submit that unwritten data when it is next resumed
5559 mPausedBytesRemaining = 0;
5560 // Invalidate is a bit drastic - would be more efficient
5561 // to have a flag to tell client that some of the
5562 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005563 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005564 }
5565 // flush data already sent to the DSP if changing audio session as audio
5566 // comes from a different source. Also invalidate previous track to force a
5567 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005568 if (previousTrack->sessionId() != track->sessionId()) {
5569 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005570 }
5571 }
5572 }
5573 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005574 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005575 if (track->isStopping_1()) {
5576 track->mRetryCount = kMaxTrackStopRetriesOffload;
5577 } else {
5578 track->mRetryCount = kMaxTrackRetriesOffload;
5579 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005580 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 mixerStatus = MIXER_TRACKS_READY;
5582 }
5583 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005584 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005585 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005586 if (--(track->mRetryCount) <= 0) {
5587 // Hardware buffer can hold a large amount of audio so we must
5588 // wait for all current track's data to drain before we say
5589 // that the track is stopped.
5590 if (mBytesRemaining == 0) {
5591 // Only start draining when all data in mixbuffer
5592 // has been written
5593 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5594 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5595 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5596 if (last && !mStandby) {
5597 // do not modify drain sequence if we are already draining. This happens
5598 // when resuming from pause after drain.
5599 if ((mDrainSequence & 1) == 0) {
5600 mSleepTimeUs = 0;
5601 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5602 mixerStatus = MIXER_DRAIN_TRACK;
5603 mDrainSequence += 2;
5604 }
5605 if (mHwPaused) {
5606 // It is possible to move from PAUSED to STOPPING_1 without
5607 // a resume so we must ensure hardware is running
5608 doHwResume = true;
5609 mHwPaused = false;
5610 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005611 }
5612 }
Eric Laurente93cc032016-05-05 10:15:10 -07005613 } else if (last) {
5614 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5615 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005616 }
5617 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005618 // Drain has completed or we are in standby, signal presentation complete
5619 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005620 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005621 uint32_t latency = 0;
5622 status_t result = mOutput->stream->getLatency(&latency);
5623 ALOGE_IF(result != OK,
5624 "Error when retrieving output stream latency: %d", result);
5625 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005626 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005627 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005628 track->presentationComplete(framesWritten, audioHALFrames);
5629 track->reset();
5630 tracksToRemove->add(track);
5631 }
5632 } else {
5633 // No buffers for this track. Give it a few chances to
5634 // fill a buffer, then remove it from active list.
5635 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005636 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005637 uint64_t position = 0;
5638 struct timespec unused;
5639 // The running check restarts the retry counter at least once.
5640 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5641 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5642 running = true;
5643 mOffloadUnderrunPosition = position;
5644 }
5645 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005646 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5647 (long long)position, (long long)mOffloadUnderrunPosition);
5648 }
5649 if (running) { // still running, give us more time.
5650 track->mRetryCount = kMaxTrackRetriesOffload;
5651 } else {
5652 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5653 track->name());
5654 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005655 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005656 // it will then automatically call start() when data is available
5657 track->disable();
5658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005659 } else if (last){
5660 mixerStatus = MIXER_TRACKS_ENABLED;
5661 }
5662 }
5663 }
5664 // compute volume for this track
5665 processVolume_l(track, last);
5666 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005667
Eric Laurentea0fade2013-10-04 16:23:48 -07005668 // make sure the pause/flush/resume sequence is executed in the right order.
5669 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5670 // before flush and then resume HW. This can happen in case of pause/flush/resume
5671 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005672 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005673 status_t result = mOutput->stream->pause();
5674 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005675 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005676 if (mFlushPending) {
5677 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005678 }
Eric Laurentfd477972013-10-25 18:10:40 -07005679 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005680 status_t result = mOutput->stream->resume();
5681 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005682 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005683
Eric Laurentbfb1b832013-01-07 09:53:42 -08005684 // remove all the tracks that need to be...
5685 removeTracks_l(*tracksToRemove);
5686
5687 return mixerStatus;
5688}
5689
Eric Laurentbfb1b832013-01-07 09:53:42 -08005690// must be called with thread mutex locked
5691bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5692{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005693 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5694 mWriteAckSequence, mDrainSequence);
5695 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005696 return true;
5697 }
5698 return false;
5699}
5700
Eric Laurentbfb1b832013-01-07 09:53:42 -08005701bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5702{
5703 Mutex::Autolock _l(mLock);
5704 return waitingAsyncCallback_l();
5705}
5706
5707void AudioFlinger::OffloadThread::flushHw_l()
5708{
Eric Laurente659ef42014-09-29 13:06:46 -07005709 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005710 // Flush anything still waiting in the mixbuffer
5711 mCurrentWriteLength = 0;
5712 mBytesRemaining = 0;
5713 mPausedWriteLength = 0;
5714 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005715 // reset bytes written count to reflect that DSP buffers are empty after flush.
5716 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005717 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005718
Eric Laurentbfb1b832013-01-07 09:53:42 -08005719 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005720 // discard any pending drain or write ack by incrementing sequence
5721 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5722 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005723 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005724 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5725 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005726 }
5727}
5728
Haynes Mathew George05317d22016-05-03 16:34:26 -07005729void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5730{
5731 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005732 if (PlaybackThread::invalidateTracks_l(streamType)) {
5733 mFlushPending = true;
5734 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005735}
5736
Eric Laurentbfb1b832013-01-07 09:53:42 -08005737// ----------------------------------------------------------------------------
5738
Eric Laurent81784c32012-11-19 14:55:58 -08005739AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005740 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005741 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005742 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005743 mWaitTimeMs(UINT_MAX)
5744{
5745 addOutputTrack(mainThread);
5746}
5747
5748AudioFlinger::DuplicatingThread::~DuplicatingThread()
5749{
5750 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5751 mOutputTracks[i]->destroy();
5752 }
5753}
5754
5755void AudioFlinger::DuplicatingThread::threadLoop_mix()
5756{
5757 // mix buffers...
5758 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005759 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005760 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005761 if (mMixerBufferValid) {
5762 memset(mMixerBuffer, 0, mMixerBufferSize);
5763 } else {
5764 memset(mSinkBuffer, 0, mSinkBufferSize);
5765 }
Eric Laurent81784c32012-11-19 14:55:58 -08005766 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005767 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005768 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005769 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005770 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005771}
5772
5773void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5774{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005775 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005776 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005777 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005778 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005779 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005780 }
5781 } else if (mBytesWritten != 0) {
5782 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5783 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005784 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005785 } else {
5786 // flush remaining overflow buffers in output tracks
5787 writeFrames = 0;
5788 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005789 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005790 }
5791}
5792
Eric Laurentbfb1b832013-01-07 09:53:42 -08005793ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005794{
5795 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005796 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005798 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005799 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005800}
5801
5802void AudioFlinger::DuplicatingThread::threadLoop_standby()
5803{
5804 // DuplicatingThread implements standby by stopping all tracks
5805 for (size_t i = 0; i < outputTracks.size(); i++) {
5806 outputTracks[i]->stop();
5807 }
5808}
5809
5810void AudioFlinger::DuplicatingThread::saveOutputTracks()
5811{
5812 outputTracks = mOutputTracks;
5813}
5814
5815void AudioFlinger::DuplicatingThread::clearOutputTracks()
5816{
5817 outputTracks.clear();
5818}
5819
5820void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5821{
5822 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005823 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5824 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5825 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5826 const size_t frameCount =
5827 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5828 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5829 // from different OutputTracks and their associated MixerThreads (e.g. one may
5830 // nearly empty and the other may be dropping data).
5831
5832 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005833 this,
5834 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005835 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005836 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005837 frameCount,
5838 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005839 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5840 if (status != NO_ERROR) {
5841 ALOGE("addOutputTrack() initCheck failed %d", status);
5842 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005843 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005844 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5845 mOutputTracks.add(outputTrack);
5846 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5847 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005848}
5849
5850void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5851{
5852 Mutex::Autolock _l(mLock);
5853 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5854 if (mOutputTracks[i]->thread() == thread) {
5855 mOutputTracks[i]->destroy();
5856 mOutputTracks.removeAt(i);
5857 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005858 if (thread->getOutput() == mOutput) {
5859 mOutput = NULL;
5860 }
Eric Laurent81784c32012-11-19 14:55:58 -08005861 return;
5862 }
5863 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005864 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005865}
5866
5867// caller must hold mLock
5868void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5869{
5870 mWaitTimeMs = UINT_MAX;
5871 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5872 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5873 if (strong != 0) {
5874 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5875 if (waitTimeMs < mWaitTimeMs) {
5876 mWaitTimeMs = waitTimeMs;
5877 }
5878 }
5879 }
5880}
5881
5882
5883bool AudioFlinger::DuplicatingThread::outputsReady(
5884 const SortedVector< sp<OutputTrack> > &outputTracks)
5885{
5886 for (size_t i = 0; i < outputTracks.size(); i++) {
5887 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5888 if (thread == 0) {
5889 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5890 outputTracks[i].get());
5891 return false;
5892 }
5893 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5894 // see note at standby() declaration
5895 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5896 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5897 thread.get());
5898 return false;
5899 }
5900 }
5901 return true;
5902}
5903
5904uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5905{
5906 return (mWaitTimeMs * 1000) / 2;
5907}
5908
5909void AudioFlinger::DuplicatingThread::cacheParameters_l()
5910{
5911 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5912 updateWaitTime_l();
5913
5914 MixerThread::cacheParameters_l();
5915}
5916
Eric Laurent6acd1d42017-01-04 14:23:29 -08005917
Eric Laurent81784c32012-11-19 14:55:58 -08005918// ----------------------------------------------------------------------------
5919// Record
5920// ----------------------------------------------------------------------------
5921
5922AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5923 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005924 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005925 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005926 audio_devices_t inDevice,
5927 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005928#ifdef TEE_SINK
5929 , const sp<NBAIO_Sink>& teeSink
5930#endif
5931 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005932 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hungdae27702016-10-31 14:01:16 -07005933 mInput(input), mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005934 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005935 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005936#ifdef TEE_SINK
5937 , mTeeSink(teeSink)
5938#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005939 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5940 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005941 // mFastCapture below
5942 , mFastCaptureFutex(0)
5943 // mInputSource
5944 // mPipeSink
5945 // mPipeSource
5946 , mPipeFramesP2(0)
5947 // mPipeMemory
5948 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005949 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005950{
Glenn Kastend7dca052015-03-05 16:05:54 -08005951 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5952 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005953
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005954 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005955
5956 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005957 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005958 size_t numCounterOffers = 0;
5959 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005960#if !LOG_NDEBUG
5961 ssize_t index =
5962#else
5963 (void)
5964#endif
5965 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005966 ALOG_ASSERT(index == 0);
5967
5968 // initialize fast capture depending on configuration
5969 bool initFastCapture;
5970 switch (kUseFastCapture) {
5971 case FastCapture_Never:
5972 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005973 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005974 break;
5975 case FastCapture_Always:
5976 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005977 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005978 break;
5979 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005980 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005981 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
5982 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
5983 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005984 break;
5985 // case FastCapture_Dynamic:
5986 }
5987
5988 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005989 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005990 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005991 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5992 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005993 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005994 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005995 const sp<MemoryDealer> roHeap(readOnlyHeap());
5996 sp<IMemory> pipeMemory;
5997 if ((roHeap == 0) ||
5998 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005999 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6000 ALOGE("not enough memory for pipe buffer size=%zu; "
6001 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6002 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6003 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006004 goto failed;
6005 }
6006 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6007 memset(pipeBuffer, 0, pipeSize);
6008 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6009 const NBAIO_Format offers[1] = {format};
6010 size_t numCounterOffers = 0;
6011 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6012 ALOG_ASSERT(index == 0);
6013 mPipeSink = pipe;
6014 PipeReader *pipeReader = new PipeReader(*pipe);
6015 numCounterOffers = 0;
6016 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6017 ALOG_ASSERT(index == 0);
6018 mPipeSource = pipeReader;
6019 mPipeFramesP2 = pipeFramesP2;
6020 mPipeMemory = pipeMemory;
6021
6022 // create fast capture
6023 mFastCapture = new FastCapture();
6024 FastCaptureStateQueue *sq = mFastCapture->sq();
6025#ifdef STATE_QUEUE_DUMP
6026 // FIXME
6027#endif
6028 FastCaptureState *state = sq->begin();
6029 state->mCblk = NULL;
6030 state->mInputSource = mInputSource.get();
6031 state->mInputSourceGen++;
6032 state->mPipeSink = pipe;
6033 state->mPipeSinkGen++;
6034 state->mFrameCount = mFrameCount;
6035 state->mCommand = FastCaptureState::COLD_IDLE;
6036 // already done in constructor initialization list
6037 //mFastCaptureFutex = 0;
6038 state->mColdFutexAddr = &mFastCaptureFutex;
6039 state->mColdGen++;
6040 state->mDumpState = &mFastCaptureDumpState;
6041#ifdef TEE_SINK
6042 // FIXME
6043#endif
6044 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6045 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6046 sq->end();
6047 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6048
6049 // start the fast capture
6050 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6051 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006052 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006053 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006054#ifdef AUDIO_WATCHDOG
6055 // FIXME
6056#endif
6057
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006058 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006059 }
6060failed: ;
6061
6062 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006063}
6064
Eric Laurent81784c32012-11-19 14:55:58 -08006065AudioFlinger::RecordThread::~RecordThread()
6066{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006067 if (mFastCapture != 0) {
6068 FastCaptureStateQueue *sq = mFastCapture->sq();
6069 FastCaptureState *state = sq->begin();
6070 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6071 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6072 if (old == -1) {
6073 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6074 }
6075 }
6076 state->mCommand = FastCaptureState::EXIT;
6077 sq->end();
6078 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6079 mFastCapture->join();
6080 mFastCapture.clear();
6081 }
6082 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006083 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006084 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006085}
6086
6087void AudioFlinger::RecordThread::onFirstRef()
6088{
Glenn Kastend7dca052015-03-05 16:05:54 -08006089 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006090}
6091
Eric Laurent555530a2017-02-07 18:17:24 -08006092void AudioFlinger::RecordThread::preExit()
6093{
6094 ALOGV(" preExit()");
6095 Mutex::Autolock _l(mLock);
6096 for (size_t i = 0; i < mTracks.size(); i++) {
6097 sp<RecordTrack> track = mTracks[i];
6098 track->invalidate();
6099 }
6100 mActiveTracks.clear();
6101 mStartStopCond.broadcast();
6102}
6103
Eric Laurent81784c32012-11-19 14:55:58 -08006104bool AudioFlinger::RecordThread::threadLoop()
6105{
Eric Laurent81784c32012-11-19 14:55:58 -08006106 nsecs_t lastWarning = 0;
6107
6108 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006109
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006110reacquire_wakelock:
6111 sp<RecordTrack> activeTrack;
6112 {
6113 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006114 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006115 }
6116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006117 // used to request a deferred sleep, to be executed later while mutex is unlocked
6118 uint32_t sleepUs = 0;
6119
6120 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006121 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006122 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006123
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006124 // activeTracks accumulates a copy of a subset of mActiveTracks
6125 Vector< sp<RecordTrack> > activeTracks;
6126
Glenn Kasten735f45f2014-08-18 15:51:59 -07006127 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006128 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006129
Glenn Kasten735f45f2014-08-18 15:51:59 -07006130 // reference to a fast track which is about to be removed
6131 sp<RecordTrack> fastTrackToRemove;
6132
Eric Laurent81784c32012-11-19 14:55:58 -08006133 { // scope for mLock
6134 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006135
Eric Laurent021cf962014-05-13 10:18:14 -07006136 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006137
Eric Laurent000a4192014-01-29 15:17:32 -08006138 // check exitPending here because checkForNewParameters_l() and
6139 // checkForNewParameters_l() can temporarily release mLock
6140 if (exitPending()) {
6141 break;
6142 }
6143
Eric Laurent5c25d562016-07-13 17:17:45 -07006144 // sleep with mutex unlocked
6145 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006146 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006147 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6148 ATRACE_END();
6149 sleepUs = 0;
6150 continue;
6151 }
6152
Glenn Kasten2b806402013-11-20 16:37:38 -08006153 // if no active track(s), then standby and release wakelock
6154 size_t size = mActiveTracks.size();
6155 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006156 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006157 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006158 releaseWakeLock_l();
6159 ALOGV("RecordThread: loop stopping");
6160 // go to sleep
6161 mWaitWorkCV.wait(mLock);
6162 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006163 goto reacquire_wakelock;
6164 }
6165
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006166 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006167 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006168 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006169
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006170 activeTrack = mActiveTracks[i];
6171 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006172 if (activeTrack->isFastTrack()) {
6173 ALOG_ASSERT(fastTrackToRemove == 0);
6174 fastTrackToRemove = activeTrack;
6175 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006177 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006178 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006179 continue;
6180 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006181
6182 TrackBase::track_state activeTrackState = activeTrack->mState;
6183 switch (activeTrackState) {
6184
6185 case TrackBase::PAUSING:
6186 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006187 doBroadcast = true;
6188 size--;
6189 continue;
6190
6191 case TrackBase::STARTING_1:
6192 sleepUs = 10000;
6193 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006194 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006195 continue;
6196
6197 case TrackBase::STARTING_2:
6198 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006199 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006200 activeTrack->mState = 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::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006205 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 break;
6207
6208 case TrackBase::IDLE:
6209 i++;
6210 continue;
6211
6212 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006213 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006214 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006215
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006216 activeTracks.add(activeTrack);
6217 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006218
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006219 if (activeTrack->isFastTrack()) {
6220 ALOG_ASSERT(!mFastTrackAvail);
6221 ALOG_ASSERT(fastTrack == 0);
6222 fastTrack = activeTrack;
6223 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006224 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006225
Andy Hungdae27702016-10-31 14:01:16 -07006226 mActiveTracks.updatePowerState(this);
6227
Eric Laurent5c25d562016-07-13 17:17:45 -07006228 if (allStopped) {
6229 standbyIfNotAlreadyInStandby();
6230 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006231 if (doBroadcast) {
6232 mStartStopCond.broadcast();
6233 }
6234
6235 // sleep if there are no active tracks to process
6236 if (activeTracks.size() == 0) {
6237 if (sleepUs == 0) {
6238 sleepUs = kRecordThreadSleepUs;
6239 }
6240 continue;
6241 }
6242 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006243
Eric Laurent81784c32012-11-19 14:55:58 -08006244 lockEffectChains_l(effectChains);
6245 }
6246
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006247 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006248
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006249 size_t size = effectChains.size();
6250 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006251 // thread mutex is not locked, but effect chain is locked
6252 effectChains[i]->process_l();
6253 }
6254
Glenn Kasten735f45f2014-08-18 15:51:59 -07006255 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006256 if (mFastCapture != 0) {
6257 FastCaptureStateQueue *sq = mFastCapture->sq();
6258 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006259 bool didModify = false;
6260 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006261 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6262 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6263 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6264 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6265 if (old == -1) {
6266 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6267 }
6268 }
6269 state->mCommand = FastCaptureState::READ_WRITE;
6270#if 0 // FIXME
6271 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006272 FastThreadDumpState::kSamplingNforLowRamDevice :
6273 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006274#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006275 didModify = true;
6276 }
6277 audio_track_cblk_t *cblkOld = state->mCblk;
6278 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6279 if (cblkNew != cblkOld) {
6280 state->mCblk = cblkNew;
6281 // block until acked if removing a fast track
6282 if (cblkOld != NULL) {
6283 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6284 }
6285 didModify = true;
6286 }
6287 sq->end(didModify);
6288 if (didModify) {
6289 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006290#if 0
6291 if (kUseFastCapture == FastCapture_Dynamic) {
6292 mNormalSource = mPipeSource;
6293 }
6294#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006295 }
6296 }
6297
Glenn Kasten735f45f2014-08-18 15:51:59 -07006298 // now run the fast track destructor with thread mutex unlocked
6299 fastTrackToRemove.clear();
6300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6302 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6303 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6304 // If destination is non-contiguous, first read past the nominal end of buffer, then
6305 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006306
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006308 ssize_t framesRead;
6309
6310 // If an NBAIO source is present, use it to read the normal capture's data
6311 if (mPipeSource != 0) {
6312 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006313 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006314 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006315 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006316 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6317 // buffer size or at least for 20ms.
6318 size_t sleepFrames = max(
6319 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6320 if (framesRead <= (ssize_t) sleepFrames) {
6321 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6322 }
6323 if (framesRead < 0) {
6324 status_t status = (status_t) framesRead;
6325 switch (status) {
6326 case OVERRUN:
6327 ALOGW("overrun on read from pipe");
6328 framesRead = 0;
6329 break;
6330 case NEGOTIATE:
6331 ALOGE("re-negotiation is needed");
6332 framesRead = -1; // Will cause an attempt to recover.
6333 break;
6334 default:
6335 ALOGE("unknown error %d on read from pipe", status);
6336 break;
6337 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006338 }
6339 // otherwise use the HAL / AudioStreamIn directly
6340 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006341 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006342 size_t bytesRead;
6343 status_t result = mInput->stream->read(
6344 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006345 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006346 if (result < 0) {
6347 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006348 } else {
6349 framesRead = bytesRead / mFrameSize;
6350 }
6351 }
6352
Andy Hung3f0c9022016-01-15 17:49:46 -08006353 // Update server timestamp with server stats
6354 // systemTime() is optional if the hardware supports timestamps.
6355 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6356 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6357
6358 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006359 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006360 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006361 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006362 if (ret == NO_ERROR) {
6363 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6364 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6365 // Note: In general record buffers should tend to be empty in
6366 // a properly running pipeline.
6367 //
6368 // Also, it is not advantageous to call get_presentation_position during the read
6369 // as the read obtains a lock, preventing the timestamp call from executing.
6370 }
6371 }
6372 // Use this to track timestamp information
6373 // ALOGD("%s", mTimestamp.toString().c_str());
6374
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006375 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006376 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006377 // Force input into standby so that it tries to recover at next read attempt
6378 inputStandBy();
6379 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006380 }
6381 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006382 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006383 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006384 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006385
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006387 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006388 }
6389 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006390 {
6391 size_t part1 = mRsmpInFramesP2 - rear;
6392 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006393 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006394 (framesRead - part1) * mFrameSize);
6395 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006396 }
6397 rear = mRsmpInRear += framesRead;
6398
6399 size = activeTracks.size();
6400 // loop over each active track
6401 for (size_t i = 0; i < size; i++) {
6402 activeTrack = activeTracks[i];
6403
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006404 // skip fast tracks, as those are handled directly by FastCapture
6405 if (activeTrack->isFastTrack()) {
6406 continue;
6407 }
6408
Andy Hung73c02e42015-03-29 01:13:58 -07006409 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006410 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6411
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006412 enum {
6413 OVERRUN_UNKNOWN,
6414 OVERRUN_TRUE,
6415 OVERRUN_FALSE
6416 } overrun = OVERRUN_UNKNOWN;
6417
6418 // loop over getNextBuffer to handle circular sink
6419 for (;;) {
6420
6421 activeTrack->mSink.frameCount = ~0;
6422 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6423 size_t framesOut = activeTrack->mSink.frameCount;
6424 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6425
Andy Hung73c02e42015-03-29 01:13:58 -07006426 // check available frames and handle overrun conditions
6427 // if the record track isn't draining fast enough.
6428 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006429 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006430 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6431 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 overrun = OVERRUN_TRUE;
6433 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006434 if (framesOut == 0 || framesIn == 0) {
6435 break;
6436 }
6437
Andy Hung6770c6f2015-04-07 13:43:36 -07006438 // Don't allow framesOut to be larger than what is possible with resampling
6439 // from framesIn.
6440 // This isn't strictly necessary but helps limit buffer resizing in
6441 // RecordBufferConverter. TODO: remove when no longer needed.
6442 framesOut = min(framesOut,
6443 destinationFramesPossible(
6444 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006445 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6446 framesOut = activeTrack->mRecordBufferConverter->convert(
6447 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006448
6449 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6450 overrun = OVERRUN_FALSE;
6451 }
6452
6453 if (activeTrack->mFramesToDrop == 0) {
6454 if (framesOut > 0) {
6455 activeTrack->mSink.frameCount = framesOut;
6456 activeTrack->releaseBuffer(&activeTrack->mSink);
6457 }
6458 } else {
6459 // FIXME could do a partial drop of framesOut
6460 if (activeTrack->mFramesToDrop > 0) {
6461 activeTrack->mFramesToDrop -= framesOut;
6462 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006463 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006464 }
6465 } else {
6466 activeTrack->mFramesToDrop += framesOut;
6467 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6468 activeTrack->mSyncStartEvent->isCancelled()) {
6469 ALOGW("Synced record %s, session %d, trigger session %d",
6470 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6471 activeTrack->sessionId(),
6472 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006473 activeTrack->mSyncStartEvent->triggerSession() :
6474 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006475 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476 }
6477 }
6478 }
6479
6480 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006481 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006482 }
6483 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006484
6485 switch (overrun) {
6486 case OVERRUN_TRUE:
6487 // client isn't retrieving buffers fast enough
6488 if (!activeTrack->setOverflow()) {
6489 nsecs_t now = systemTime();
6490 // FIXME should lastWarning per track?
6491 if ((now - lastWarning) > kWarningThrottleNs) {
6492 ALOGW("RecordThread: buffer overflow");
6493 lastWarning = now;
6494 }
6495 }
6496 break;
6497 case OVERRUN_FALSE:
6498 activeTrack->clearOverflow();
6499 break;
6500 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006501 break;
6502 }
6503
Andy Hung3f0c9022016-01-15 17:49:46 -08006504 // update frame information and push timestamp out
6505 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006506 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006507 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6508 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006509 }
6510
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006511unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006512 // enable changes in effect chain
6513 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006514 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006515 }
6516
Glenn Kasten93e471f2013-08-19 08:40:07 -07006517 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006518
6519 {
6520 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006521 for (size_t i = 0; i < mTracks.size(); i++) {
6522 sp<RecordTrack> track = mTracks[i];
6523 track->invalidate();
6524 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006525 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006526 mStartStopCond.broadcast();
6527 }
6528
6529 releaseWakeLock();
6530
6531 ALOGV("RecordThread %p exiting", this);
6532 return false;
6533}
6534
Glenn Kasten93e471f2013-08-19 08:40:07 -07006535void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006536{
6537 if (!mStandby) {
6538 inputStandBy();
6539 mStandby = true;
6540 }
6541}
6542
6543void AudioFlinger::RecordThread::inputStandBy()
6544{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006545 // Idle the fast capture if it's currently running
6546 if (mFastCapture != 0) {
6547 FastCaptureStateQueue *sq = mFastCapture->sq();
6548 FastCaptureState *state = sq->begin();
6549 if (!(state->mCommand & FastCaptureState::IDLE)) {
6550 state->mCommand = FastCaptureState::COLD_IDLE;
6551 state->mColdFutexAddr = &mFastCaptureFutex;
6552 state->mColdGen++;
6553 mFastCaptureFutex = 0;
6554 sq->end();
6555 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6556 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6557#if 0
6558 if (kUseFastCapture == FastCapture_Dynamic) {
6559 // FIXME
6560 }
6561#endif
6562#ifdef AUDIO_WATCHDOG
6563 // FIXME
6564#endif
6565 } else {
6566 sq->end(false /*didModify*/);
6567 }
6568 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006569 status_t result = mInput->stream->standby();
6570 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006571
6572 // If going into standby, flush the pipe source.
6573 if (mPipeSource.get() != nullptr) {
6574 const ssize_t flushed = mPipeSource->flush();
6575 if (flushed > 0) {
6576 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6577 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6578 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6579 }
6580 }
Eric Laurent81784c32012-11-19 14:55:58 -08006581}
6582
Glenn Kasten05997e22014-03-13 15:08:33 -07006583// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006584sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006585 const sp<AudioFlinger::Client>& client,
6586 uint32_t sampleRate,
6587 audio_format_t format,
6588 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006589 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006590 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006591 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006592 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006593 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006594 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006595 status_t *status,
6596 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006597{
Glenn Kasten74935e42013-12-19 08:56:45 -08006598 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006599 sp<RecordTrack> track;
6600 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006601 audio_input_flags_t inputFlags = mInput->flags;
6602
6603 // special case for FAST flag considered OK if fast capture is present
6604 if (hasFastCapture()) {
6605 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6606 }
6607
6608 // Check if requested flags are compatible with output stream flags
6609 if ((*flags & inputFlags) != *flags) {
6610 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6611 " input flags (%08x)",
6612 *flags, inputFlags);
6613 *flags = (audio_input_flags_t)(*flags & inputFlags);
6614 }
Eric Laurent81784c32012-11-19 14:55:58 -08006615
Glenn Kasten90e58b12013-07-31 16:16:02 -07006616 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006617 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006618 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006619 // we formerly checked for a callback handler (non-0 tid),
6620 // but that is no longer required for TRANSFER_OBTAIN mode
6621 //
Glenn Kasten74105912014-07-03 12:28:53 -07006622 // frame count is not specified, or is exactly the pipe depth
6623 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006624 // PCM data
6625 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006626 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006627 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006628 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006629 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006630 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006631 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006632 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006633 hasFastCapture() &&
6634 // there are sufficient fast track slots available
6635 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006636 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006637 // check compatibility with audio effects.
6638 Mutex::Autolock _l(mLock);
6639 // Do not accept FAST flag if the session has software effects
6640 sp<EffectChain> chain = getEffectChain_l(sessionId);
6641 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006642 audio_input_flags_t old = *flags;
6643 chain->checkInputFlagCompatibility(flags);
6644 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006645 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6646 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006647 }
6648 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006649 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006650 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6651 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006652 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006653 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6654 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006655 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006656 this, frameCount, mFrameCount, mPipeFramesP2,
6657 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006658 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006659 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006660 }
6661 }
6662
6663 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006664 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006665 // fast track: frame count is exactly the pipe depth
6666 frameCount = mPipeFramesP2;
6667 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6668 *notificationFrames = mFrameCount;
6669 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006670 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6671 // or 20 ms if there is a fast capture
6672 // TODO This could be a roundupRatio inline, and const
6673 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6674 * sampleRate + mSampleRate - 1) / mSampleRate;
6675 // minimum number of notification periods is at least kMinNotifications,
6676 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6677 static const size_t kMinNotifications = 3;
6678 static const uint32_t kMinMs = 30;
6679 // TODO This could be a roundupRatio inline
6680 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6681 // TODO This could be a roundupRatio inline
6682 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6683 maxNotificationFrames;
6684 const size_t minFrameCount = maxNotificationFrames *
6685 max(kMinNotifications, minNotificationsByMs);
6686 frameCount = max(frameCount, minFrameCount);
6687 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6688 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006689 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006690 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006691 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006692
Glenn Kasten15e57982013-09-24 11:52:37 -07006693 lStatus = initCheck();
6694 if (lStatus != NO_ERROR) {
6695 ALOGE("createRecordTrack_l() audio driver not initialized");
6696 goto Exit;
6697 }
Eric Laurent81784c32012-11-19 14:55:58 -08006698
6699 { // scope for mLock
6700 Mutex::Autolock _l(mLock);
6701
6702 track = new RecordTrack(this, client, sampleRate,
Eric Laurent83b88082014-06-20 18:31:16 -07006703 format, channelMask, frameCount, NULL, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006704 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006705
Glenn Kasten03003332013-08-06 15:40:54 -07006706 lStatus = track->initCheck();
6707 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006708 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006709 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006710 goto Exit;
6711 }
6712 mTracks.add(track);
6713
6714 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6715 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6716 mAudioFlinger->btNrecIsOff();
6717 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6718 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006719
Eric Laurent05067782016-06-01 18:27:28 -07006720 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006721 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6722 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6723 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006724 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006725 }
Eric Laurent81784c32012-11-19 14:55:58 -08006726 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006727
Eric Laurent81784c32012-11-19 14:55:58 -08006728 lStatus = NO_ERROR;
6729
6730Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006731 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006732 return track;
6733}
6734
6735status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6736 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006737 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006738{
6739 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6740 sp<ThreadBase> strongMe = this;
6741 status_t status = NO_ERROR;
6742
6743 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006744 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006745 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006746 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006747 triggerSession,
6748 recordTrack->sessionId(),
6749 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006750 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006751 // Sync event can be cancelled by the trigger session if the track is not in a
6752 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006753 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006754 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006755 } else {
6756 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006757 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006758 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006759 }
6760 }
6761
6762 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006763 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006764 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006765 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6766 if (recordTrack->mState == TrackBase::PAUSING) {
6767 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006768 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006769 } else {
6770 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006771 }
6772 return status;
6773 }
6774
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006775 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6776 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6777 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006778 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006779 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006780 status_t status = NO_ERROR;
6781 if (recordTrack->isExternalTrack()) {
6782 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006783 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006784 mLock.lock();
6785 // FIXME should verify that recordTrack is still in mActiveTracks
6786 if (status != NO_ERROR) {
6787 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006788 recordTrack->clearSyncStartEvent();
6789 ALOGV("RecordThread::start error %d", status);
6790 return status;
6791 }
Eric Laurent81784c32012-11-19 14:55:58 -08006792 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006793 // Catch up with current buffer indices if thread is already running.
6794 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6795 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6796 // see previously buffered data before it called start(), but with greater risk of overrun.
6797
Andy Hung73c02e42015-03-29 01:13:58 -07006798 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006799 // clear any converter state as new data will be discontinuous
6800 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006801 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006802 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006803 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006804 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006805 ALOGV("Record failed to start");
6806 status = BAD_VALUE;
6807 goto startError;
6808 }
Eric Laurent81784c32012-11-19 14:55:58 -08006809 return status;
6810 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006811
Eric Laurent81784c32012-11-19 14:55:58 -08006812startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006813 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006814 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006815 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006816 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006817 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006818 return status;
6819}
6820
Eric Laurent81784c32012-11-19 14:55:58 -08006821void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6822{
6823 sp<SyncEvent> strongEvent = event.promote();
6824
6825 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006826 sp<RefBase> ptr = strongEvent->cookie().promote();
6827 if (ptr != 0) {
6828 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6829 recordTrack->handleSyncStartEvent(strongEvent);
6830 }
Eric Laurent81784c32012-11-19 14:55:58 -08006831 }
6832}
6833
Glenn Kastena8356f62013-07-25 14:37:52 -07006834bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006835 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006836 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006837 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006838 return false;
6839 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006840 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006841 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006842 // signal thread to stop
6843 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006844 // do not wait for mStartStopCond if exiting
6845 if (exitPending()) {
6846 return true;
6847 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006848 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006849 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006850 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006851 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006852 ALOGV("Record stopped OK");
6853 return true;
6854 }
6855 return false;
6856}
6857
Glenn Kasten0f11b512014-01-31 16:18:54 -08006858bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006859{
6860 return false;
6861}
6862
Glenn Kasten0f11b512014-01-31 16:18:54 -08006863status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006864{
6865#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6866 if (!isValidSyncEvent(event)) {
6867 return BAD_VALUE;
6868 }
6869
Glenn Kastend848eb42016-03-08 13:42:11 -08006870 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006871 status_t ret = NAME_NOT_FOUND;
6872
6873 Mutex::Autolock _l(mLock);
6874
6875 for (size_t i = 0; i < mTracks.size(); i++) {
6876 sp<RecordTrack> track = mTracks[i];
6877 if (eventSession == track->sessionId()) {
6878 (void) track->setSyncEvent(event);
6879 ret = NO_ERROR;
6880 }
6881 }
6882 return ret;
6883#else
6884 return BAD_VALUE;
6885#endif
6886}
6887
6888// destroyTrack_l() must be called with ThreadBase::mLock held
6889void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6890{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006891 track->terminate();
6892 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006893 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006894 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006895 removeTrack_l(track);
6896 }
6897}
6898
6899void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6900{
6901 mTracks.remove(track);
6902 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006903 if (track->isFastTrack()) {
6904 ALOG_ASSERT(!mFastTrackAvail);
6905 mFastTrackAvail = true;
6906 }
Eric Laurent81784c32012-11-19 14:55:58 -08006907}
6908
6909void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6910{
6911 dumpInternals(fd, args);
6912 dumpTracks(fd, args);
6913 dumpEffectChains(fd, args);
6914}
6915
6916void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6917{
Glenn Kasten44182c22015-03-05 17:12:23 -08006918 dumpBase(fd, args);
6919
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006920 AudioStreamIn *input = mInput;
6921 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6922 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6923 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006924 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006925 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006926 }
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006927 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006928 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006929
Glenn Kasten2f90c512015-12-02 11:40:09 -08006930 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6931 // while we are dumping it. It may be inconsistent, but it won't mutate!
6932 // This is a large object so we place it on the heap.
6933 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6934 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6935 copy->dump(fd);
6936 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006937}
6938
Glenn Kasten0f11b512014-01-31 16:18:54 -08006939void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006940{
6941 const size_t SIZE = 256;
6942 char buffer[SIZE];
6943 String8 result;
6944
Marco Nelissenb2208842014-02-07 14:00:50 -08006945 size_t numtracks = mTracks.size();
6946 size_t numactive = mActiveTracks.size();
6947 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006948 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08006949 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006950 dprintf(fd, " of which %zu are active\n", numactive);
Marco Nelissenb2208842014-02-07 14:00:50 -08006951 RecordTrack::appendDumpHeader(result);
6952 for (size_t i = 0; i < numtracks ; ++i) {
6953 sp<RecordTrack> track = mTracks[i];
6954 if (track != 0) {
6955 bool active = mActiveTracks.indexOf(track) >= 0;
6956 if (active) {
6957 numactiveseen++;
6958 }
6959 track->dump(buffer, SIZE, active);
6960 result.append(buffer);
6961 }
Eric Laurent81784c32012-11-19 14:55:58 -08006962 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006963 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006964 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006965 }
6966
Marco Nelissenb2208842014-02-07 14:00:50 -08006967 if (numactiveseen != numactive) {
6968 snprintf(buffer, SIZE, " The following tracks are in the active list but"
6969 " not in the track list\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006970 result.append(buffer);
6971 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006972 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006973 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006974 if (mTracks.indexOf(track) < 0) {
6975 track->dump(buffer, SIZE, true);
6976 result.append(buffer);
6977 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006978 }
Eric Laurent81784c32012-11-19 14:55:58 -08006979
6980 }
6981 write(fd, result.string(), result.size());
6982}
6983
Andy Hung73c02e42015-03-29 01:13:58 -07006984
6985void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6986{
6987 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6988 RecordThread *recordThread = (RecordThread *) threadBase.get();
6989 mRsmpInFront = recordThread->mRsmpInRear;
6990 mRsmpInUnrel = 0;
6991}
6992
6993void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
6994 size_t *framesAvailable, bool *hasOverrun)
6995{
6996 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6997 RecordThread *recordThread = (RecordThread *) threadBase.get();
6998 const int32_t rear = recordThread->mRsmpInRear;
6999 const int32_t front = mRsmpInFront;
7000 const ssize_t filled = rear - front;
7001
7002 size_t framesIn;
7003 bool overrun = false;
7004 if (filled < 0) {
7005 // should not happen, but treat like a massive overrun and re-sync
7006 framesIn = 0;
7007 mRsmpInFront = rear;
7008 overrun = true;
7009 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7010 framesIn = (size_t) filled;
7011 } else {
7012 // client is not keeping up with server, but give it latest data
7013 framesIn = recordThread->mRsmpInFrames;
7014 mRsmpInFront = /* front = */ rear - framesIn;
7015 overrun = true;
7016 }
7017 if (framesAvailable != NULL) {
7018 *framesAvailable = framesIn;
7019 }
7020 if (hasOverrun != NULL) {
7021 *hasOverrun = overrun;
7022 }
7023}
7024
Eric Laurent81784c32012-11-19 14:55:58 -08007025// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007026status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007027 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
Andy Hung73c02e42015-03-29 01:13:58 -07007029 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007030 if (threadBase == 0) {
7031 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007032 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007033 return NOT_ENOUGH_DATA;
7034 }
7035 RecordThread *recordThread = (RecordThread *) threadBase.get();
7036 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007037 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007038 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007039 // FIXME should not be P2 (don't want to increase latency)
7040 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007041 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007042 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007043 front &= recordThread->mRsmpInFramesP2 - 1;
7044 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007045 if (part1 > (size_t) filled) {
7046 part1 = filled;
7047 }
7048 size_t ask = buffer->frameCount;
7049 ALOG_ASSERT(ask > 0);
7050 if (part1 > ask) {
7051 part1 = ask;
7052 }
7053 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007054 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007055 buffer->raw = NULL;
7056 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007057 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007058 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007059 }
7060
Andy Hung57446612015-04-19 23:56:46 -07007061 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007062 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007063 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007064 return NO_ERROR;
7065}
7066
7067// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007068void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7069 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007070{
Glenn Kasten85948432013-08-19 12:09:05 -07007071 size_t stepCount = buffer->frameCount;
7072 if (stepCount == 0) {
7073 return;
7074 }
Andy Hung73c02e42015-03-29 01:13:58 -07007075 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7076 mRsmpInUnrel -= stepCount;
7077 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007078 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007079 buffer->frameCount = 0;
7080}
7081
Andy Hung97a893e2015-03-29 01:03:07 -07007082
Eric Laurent10351942014-05-08 18:49:52 -07007083bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7084 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007085{
7086 bool reconfig = false;
7087
Eric Laurent10351942014-05-08 18:49:52 -07007088 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007089
Eric Laurent10351942014-05-08 18:49:52 -07007090 audio_format_t reqFormat = mFormat;
7091 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007092 // 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 -07007093 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7094
7095 AudioParameter param = AudioParameter(keyValuePair);
7096 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007097
7098 // scope for AutoPark extends to end of method
7099 AutoPark<FastCapture> park(mFastCapture);
7100
Eric Laurent10351942014-05-08 18:49:52 -07007101 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7102 // channel count change can be requested. Do we mandate the first client defines the
7103 // HAL sampling rate and channel count or do we allow changes on the fly?
7104 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7105 samplingRate = value;
7106 reconfig = true;
7107 }
7108 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007109 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007110 status = BAD_VALUE;
7111 } else {
7112 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007113 reconfig = true;
7114 }
Eric Laurent10351942014-05-08 18:49:52 -07007115 }
7116 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7117 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007118 if (!audio_is_input_channel(mask) ||
7119 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007120 status = BAD_VALUE;
7121 } else {
7122 channelMask = mask;
7123 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007124 }
Eric Laurent10351942014-05-08 18:49:52 -07007125 }
7126 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7127 // do not accept frame count changes if tracks are open as the track buffer
7128 // size depends on frame count and correct behavior would not be guaranteed
7129 // if frame count is changed after track creation
7130 if (mActiveTracks.size() > 0) {
7131 status = INVALID_OPERATION;
7132 } else {
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::keyRouting), value) == NO_ERROR) {
7137 // forward device change to effects that have requested to be
7138 // aware of attached audio device.
7139 for (size_t i = 0; i < mEffectChains.size(); i++) {
7140 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007141 }
Eric Laurent81784c32012-11-19 14:55:58 -08007142
Eric Laurent10351942014-05-08 18:49:52 -07007143 // store input device and output device but do not forward output device to audio HAL.
7144 // Note that status is ignored by the caller for output device
7145 // (see AudioFlinger::setParameters()
7146 if (audio_is_output_devices(value)) {
7147 mOutDevice = value;
7148 status = BAD_VALUE;
7149 } else {
7150 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007151 if (value != AUDIO_DEVICE_NONE) {
7152 mPrevInDevice = value;
7153 }
Eric Laurent10351942014-05-08 18:49:52 -07007154 // disable AEC and NS if the device is a BT SCO headset supporting those
7155 // pre processings
7156 if (mTracks.size() > 0) {
7157 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7158 mAudioFlinger->btNrecIsOff();
7159 for (size_t i = 0; i < mTracks.size(); i++) {
7160 sp<RecordTrack> track = mTracks[i];
7161 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7162 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007163 }
7164 }
7165 }
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
7397 // disable AEC and NS if the device is a BT SCO headset supporting those
7398 // pre processings
7399 if (mTracks.size() > 0) {
7400 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7401 mAudioFlinger->btNrecIsOff();
7402 for (size_t i = 0; i < mTracks.size(); i++) {
7403 sp<RecordTrack> track = mTracks[i];
7404 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7405 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7406 }
7407 }
7408
7409 // store new source and send to effects
7410 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7411 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007412 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007413 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007414 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007415 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007416
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007417 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007418 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7419 status = hwDevice->createAudioPatch(patch->num_sources,
7420 patch->sources,
7421 patch->num_sinks,
7422 patch->sinks,
7423 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007424 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007425 char *address;
7426 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7427 address = audio_device_address_to_parameter(
7428 patch->sources[0].ext.device.type,
7429 patch->sources[0].ext.device.address);
7430 } else {
7431 address = (char *)calloc(1, 1);
7432 }
7433 AudioParameter param = AudioParameter(String8(address));
7434 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007435 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007436 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007437 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007438 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007439 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007440 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007441 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007442
Eric Laurente8726fe2015-06-26 09:39:24 -07007443 if (mInDevice != mPrevInDevice) {
7444 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7445 mPrevInDevice = mInDevice;
7446 }
Eric Laurent296fb132015-05-01 11:38:42 -07007447
Eric Laurent1c333e22014-05-20 10:48:17 -07007448 return status;
7449}
7450
7451status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7452{
7453 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007454
7455 mInDevice = AUDIO_DEVICE_NONE;
7456
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007457 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007458 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7459 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007460 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007461 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007462 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007463 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007464 }
7465 return status;
7466}
7467
Eric Laurent83b88082014-06-20 18:31:16 -07007468void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7469{
7470 Mutex::Autolock _l(mLock);
7471 mTracks.add(record);
7472}
7473
7474void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7475{
7476 Mutex::Autolock _l(mLock);
7477 destroyTrack_l(record);
7478}
7479
7480void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7481{
7482 ThreadBase::getAudioPortConfig(config);
7483 config->role = AUDIO_PORT_ROLE_SINK;
7484 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7485 config->ext.mix.usecase.source = mAudioSource;
7486}
Eric Laurent1c333e22014-05-20 10:48:17 -07007487
Eric Laurent6acd1d42017-01-04 14:23:29 -08007488// ----------------------------------------------------------------------------
7489// Mmap
7490// ----------------------------------------------------------------------------
7491
7492AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7493 : mThread(thread)
7494{
7495}
7496
7497AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7498{
7499 MmapThread *thread = mThread.get();
7500 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007501 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007502 // and the thread removed from mMMapThreads list causing the thread destruction.
7503 mThread.clear();
7504 if (thread != nullptr) {
7505 thread->disconnect();
7506 }
7507}
7508
7509status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7510 struct audio_mmap_buffer_info *info)
7511{
7512 if (mThread == 0) {
7513 return NO_INIT;
7514 }
7515 return mThread->createMmapBuffer(minSizeFrames, info);
7516}
7517
7518status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7519{
7520 if (mThread == 0) {
7521 return NO_INIT;
7522 }
7523 return mThread->getMmapPosition(position);
7524}
7525
Eric Laurentcb4dae22017-07-01 19:39:32 -07007526status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007527 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007528
7529{
7530 if (mThread == 0) {
7531 return NO_INIT;
7532 }
7533 return mThread->start(client, handle);
7534}
7535
7536status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7537{
7538 if (mThread == 0) {
7539 return NO_INIT;
7540 }
7541 return mThread->stop(handle);
7542}
7543
Eric Laurent18b57012017-02-13 16:23:52 -08007544status_t AudioFlinger::MmapThreadHandle::standby()
7545{
7546 if (mThread == 0) {
7547 return NO_INIT;
7548 }
7549 return mThread->standby();
7550}
7551
Eric Laurent6acd1d42017-01-04 14:23:29 -08007552
7553AudioFlinger::MmapThread::MmapThread(
7554 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7555 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7556 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7557 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
7558 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev)
7559{
Eric Laurent18b57012017-02-13 16:23:52 -08007560 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007561 readHalParameters_l();
7562}
7563
7564AudioFlinger::MmapThread::~MmapThread()
7565{
Eric Laurent18b57012017-02-13 16:23:52 -08007566 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007567}
7568
7569void AudioFlinger::MmapThread::onFirstRef()
7570{
7571 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7572}
7573
7574void AudioFlinger::MmapThread::disconnect()
7575{
7576 for (const sp<MmapTrack> &t : mActiveTracks) {
7577 stop(t->portId());
7578 }
7579 // this will cause the destruction of this thread.
7580 if (isOutput()) {
7581 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7582 } else {
7583 AudioSystem::releaseInput(mId, mSessionId);
7584 }
7585}
7586
7587
7588void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7589 audio_stream_type_t streamType __unused,
7590 audio_session_t sessionId,
7591 const sp<MmapStreamCallback>& callback,
7592 audio_port_handle_t portId)
7593{
7594 mAttr = *attr;
7595 mSessionId = sessionId;
7596 mCallback = callback;
7597 mPortId = portId;
7598}
7599
7600status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7601 struct audio_mmap_buffer_info *info)
7602{
7603 if (mHalStream == 0) {
7604 return NO_INIT;
7605 }
Eric Laurent18b57012017-02-13 16:23:52 -08007606 mStandby = true;
7607 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007608 return mHalStream->createMmapBuffer(minSizeFrames, info);
7609}
7610
7611status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7612{
7613 if (mHalStream == 0) {
7614 return NO_INIT;
7615 }
7616 return mHalStream->getMmapPosition(position);
7617}
7618
Eric Laurentcb4dae22017-07-01 19:39:32 -07007619status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007620 audio_port_handle_t *handle)
7621{
Eric Laurentcb4dae22017-07-01 19:39:32 -07007622 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7623 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007624 if (mHalStream == 0) {
7625 return NO_INIT;
7626 }
7627
7628 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007629
Eric Laurentcb4dae22017-07-01 19:39:32 -07007630 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007631 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007632 ret = mHalStream->start();
7633 if (ret != NO_ERROR) {
7634 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7635 return ret;
7636 }
Eric Laurent18b57012017-02-13 16:23:52 -08007637 mStandby = false;
Eric Laurentcb4dae22017-07-01 19:39:32 -07007638 return NO_ERROR;
7639 }
7640
7641 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7642
7643 audio_io_handle_t io = mId;
7644 if (isOutput()) {
7645 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7646 config.sample_rate = mSampleRate;
7647 config.channel_mask = mChannelMask;
7648 config.format = mFormat;
7649 audio_stream_type_t stream = streamType();
7650 audio_output_flags_t flags =
7651 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7652 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7653 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7654 mSessionId,
7655 &stream,
7656 client.clientUid,
7657 &config,
7658 flags,
7659 &deviceId,
7660 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007661 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007662 audio_config_base_t config;
7663 config.sample_rate = mSampleRate;
7664 config.channel_mask = mChannelMask;
7665 config.format = mFormat;
7666 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7667 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7668 mSessionId,
7669 client.clientPid,
7670 client.clientUid,
7671 &config,
7672 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7673 &deviceId,
7674 &portId);
7675 }
7676 // APM should not chose a different input or output stream for the same set of attributes
7677 // and audo configuration
7678 if (ret != NO_ERROR || io != mId) {
7679 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7680 __FUNCTION__, ret, io, mId);
7681 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007682 }
7683
7684 if (isOutput()) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007685 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007686 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007687 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007688 }
7689
7690 // abort if start is rejected by audio policy manager
7691 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007692 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007693 if (mActiveTracks.size() != 0) {
7694 if (isOutput()) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007695 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007696 } else {
Eric Laurentcb4dae22017-07-01 19:39:32 -07007697 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007698 }
Eric Laurent18b57012017-02-13 16:23:52 -08007699 } else {
7700 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007701 }
7702 return PERMISSION_DENIED;
7703 }
7704
Eric Laurentcb4dae22017-07-01 19:39:32 -07007705 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007706 client.clientUid, portId);
7707
7708 mActiveTracks.add(track);
Eric Laurentcb4dae22017-07-01 19:39:32 -07007709 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007710 if (chain != 0) {
7711 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7712 chain->incTrackCnt();
7713 chain->incActiveTrackCnt();
7714 }
7715
7716 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007717 broadcast_l();
7718
Eric Laurentcb4dae22017-07-01 19:39:32 -07007719 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007720
7721 return NO_ERROR;
7722}
7723
7724status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7725{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007726 ALOGV("%s handle %d", __FUNCTION__, handle);
7727
7728 if (mHalStream == 0) {
7729 return NO_INIT;
7730 }
7731
Eric Laurentcb4dae22017-07-01 19:39:32 -07007732 if (handle == mPortId) {
7733 mHalStream->stop();
7734 return NO_ERROR;
7735 }
7736
Eric Laurent6acd1d42017-01-04 14:23:29 -08007737 sp<MmapTrack> track;
7738 for (const sp<MmapTrack> &t : mActiveTracks) {
7739 if (handle == t->portId()) {
7740 track = t;
7741 break;
7742 }
7743 }
7744 if (track == 0) {
7745 return BAD_VALUE;
7746 }
7747
7748 mActiveTracks.remove(track);
7749
7750 if (isOutput()) {
7751 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurentcb4dae22017-07-01 19:39:32 -07007752 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007753 } else {
7754 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurentcb4dae22017-07-01 19:39:32 -07007755 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007756 }
7757
7758 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7759 if (chain != 0) {
7760 chain->decActiveTrackCnt();
7761 chain->decTrackCnt();
7762 }
7763
7764 broadcast_l();
7765
Eric Laurent6acd1d42017-01-04 14:23:29 -08007766 return NO_ERROR;
7767}
7768
Eric Laurent18b57012017-02-13 16:23:52 -08007769status_t AudioFlinger::MmapThread::standby()
7770{
7771 ALOGV("%s", __FUNCTION__);
7772
7773 if (mHalStream == 0) {
7774 return NO_INIT;
7775 }
7776 if (mActiveTracks.size() != 0) {
7777 return INVALID_OPERATION;
7778 }
7779 mHalStream->standby();
7780 mStandby = true;
7781 releaseWakeLock();
7782 return NO_ERROR;
7783}
7784
Eric Laurent6acd1d42017-01-04 14:23:29 -08007785
7786void AudioFlinger::MmapThread::readHalParameters_l()
7787{
7788 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7789 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7790 mFormat = mHALFormat;
7791 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7792 result = mHalStream->getFrameSize(&mFrameSize);
7793 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7794 result = mHalStream->getBufferSize(&mBufferSize);
7795 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7796 mFrameCount = mBufferSize / mFrameSize;
7797}
7798
7799bool AudioFlinger::MmapThread::threadLoop()
7800{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007801 checkSilentMode_l();
7802
7803 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7804
7805 while (!exitPending())
7806 {
7807 Mutex::Autolock _l(mLock);
7808 Vector< sp<EffectChain> > effectChains;
7809
7810 if (mSignalPending) {
7811 // A signal was raised while we were unlocked
7812 mSignalPending = false;
7813 } else {
7814 if (mConfigEvents.isEmpty()) {
7815 // we're about to wait, flush the binder command buffer
7816 IPCThreadState::self()->flushCommands();
7817
7818 if (exitPending()) {
7819 break;
7820 }
7821
Eric Laurent6acd1d42017-01-04 14:23:29 -08007822 // wait until we have something to do...
7823 ALOGV("%s going to sleep", myName.string());
7824 mWaitWorkCV.wait(mLock);
7825 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007826
7827 checkSilentMode_l();
7828
7829 continue;
7830 }
7831 }
7832
7833 processConfigEvents_l();
7834
7835 processVolume_l();
7836
7837 checkInvalidTracks_l();
7838
7839 mActiveTracks.updatePowerState(this);
7840
7841 lockEffectChains_l(effectChains);
7842 for (size_t i = 0; i < effectChains.size(); i ++) {
7843 effectChains[i]->process_l();
7844 }
7845 // enable changes in effect chain
7846 unlockEffectChains(effectChains);
7847 // Effect chains will be actually deleted here if they were removed from
7848 // mEffectChains list during mixing or effects processing
7849 }
7850
7851 threadLoop_exit();
7852
7853 if (!mStandby) {
7854 threadLoop_standby();
7855 mStandby = true;
7856 }
7857
Eric Laurent6acd1d42017-01-04 14:23:29 -08007858 ALOGV("Thread %p type %d exiting", this, mType);
7859 return false;
7860}
7861
7862// checkForNewParameter_l() must be called with ThreadBase::mLock held
7863bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7864 status_t& status)
7865{
7866 AudioParameter param = AudioParameter(keyValuePair);
7867 int value;
7868 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7869 // forward device change to effects that have requested to be
7870 // aware of attached audio device.
7871 if (value != AUDIO_DEVICE_NONE) {
7872 mOutDevice = value;
7873 for (size_t i = 0; i < mEffectChains.size(); i++) {
7874 mEffectChains[i]->setDevice_l(mOutDevice);
7875 }
7876 }
7877 }
7878 status = mHalStream->setParameters(keyValuePair);
7879
7880 return false;
7881}
7882
7883String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7884{
7885 Mutex::Autolock _l(mLock);
7886 String8 out_s8;
7887 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7888 return out_s8;
7889 }
7890 return String8();
7891}
7892
7893void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7894 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7895
7896 desc->mIoHandle = mId;
7897
7898 switch (event) {
7899 case AUDIO_INPUT_OPENED:
7900 case AUDIO_INPUT_CONFIG_CHANGED:
7901 case AUDIO_OUTPUT_OPENED:
7902 case AUDIO_OUTPUT_CONFIG_CHANGED:
7903 desc->mPatch = mPatch;
7904 desc->mChannelMask = mChannelMask;
7905 desc->mSamplingRate = mSampleRate;
7906 desc->mFormat = mFormat;
7907 desc->mFrameCount = mFrameCount;
7908 desc->mFrameCountHAL = mFrameCount;
7909 desc->mLatency = 0;
7910 break;
7911
7912 case AUDIO_INPUT_CLOSED:
7913 case AUDIO_OUTPUT_CLOSED:
7914 default:
7915 break;
7916 }
7917 mAudioFlinger->ioConfigChanged(event, desc, pid);
7918}
7919
7920status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7921 audio_patch_handle_t *handle)
7922{
7923 status_t status = NO_ERROR;
7924
7925 // store new device and send to effects
7926 audio_devices_t type = AUDIO_DEVICE_NONE;
7927 audio_port_handle_t deviceId;
7928 if (isOutput()) {
7929 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7930 type |= patch->sinks[i].ext.device.type;
7931 }
7932 deviceId = patch->sinks[0].id;
7933 } else {
7934 type = patch->sources[0].ext.device.type;
7935 deviceId = patch->sources[0].id;
7936 }
7937
7938 for (size_t i = 0; i < mEffectChains.size(); i++) {
7939 mEffectChains[i]->setDevice_l(type);
7940 }
7941
7942 if (isOutput()) {
7943 mOutDevice = type;
7944 } else {
7945 mInDevice = type;
7946 // store new source and send to effects
7947 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7948 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7949 for (size_t i = 0; i < mEffectChains.size(); i++) {
7950 mEffectChains[i]->setAudioSource_l(mAudioSource);
7951 }
7952 }
7953 }
7954
7955 if (mAudioHwDev->supportsAudioPatches()) {
7956 status = mHalDevice->createAudioPatch(patch->num_sources,
7957 patch->sources,
7958 patch->num_sinks,
7959 patch->sinks,
7960 handle);
7961 } else {
7962 char *address;
7963 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7964 //FIXME: we only support address on first sink with HAL version < 3.0
7965 address = audio_device_address_to_parameter(
7966 patch->sinks[0].ext.device.type,
7967 patch->sinks[0].ext.device.address);
7968 } else {
7969 address = (char *)calloc(1, 1);
7970 }
7971 AudioParameter param = AudioParameter(String8(address));
7972 free(address);
7973 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7974 if (!isOutput()) {
7975 param.addInt(String8(AudioParameter::keyInputSource),
7976 (int)patch->sinks[0].ext.mix.usecase.source);
7977 }
7978 status = mHalStream->setParameters(param.toString());
7979 *handle = AUDIO_PATCH_HANDLE_NONE;
7980 }
7981
7982 if (isOutput() && mPrevOutDevice != mOutDevice) {
7983 mPrevOutDevice = type;
7984 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007985 sp<MmapStreamCallback> callback = mCallback.promote();
7986 if (callback != 0) {
7987 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007988 }
7989 }
7990 if (!isOutput() && mPrevInDevice != mInDevice) {
7991 mPrevInDevice = type;
7992 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007993 sp<MmapStreamCallback> callback = mCallback.promote();
7994 if (callback != 0) {
7995 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007996 }
7997 }
7998 return status;
7999}
8000
8001status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8002{
8003 status_t status = NO_ERROR;
8004
8005 mInDevice = AUDIO_DEVICE_NONE;
8006
8007 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8008 supportsAudioPatches : false;
8009
8010 if (supportsAudioPatches) {
8011 status = mHalDevice->releaseAudioPatch(handle);
8012 } else {
8013 AudioParameter param;
8014 param.addInt(String8(AudioParameter::keyRouting), 0);
8015 status = mHalStream->setParameters(param.toString());
8016 }
8017 return status;
8018}
8019
8020void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8021{
8022 ThreadBase::getAudioPortConfig(config);
8023 if (isOutput()) {
8024 config->role = AUDIO_PORT_ROLE_SOURCE;
8025 config->ext.mix.hw_module = mAudioHwDev->handle();
8026 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8027 } else {
8028 config->role = AUDIO_PORT_ROLE_SINK;
8029 config->ext.mix.hw_module = mAudioHwDev->handle();
8030 config->ext.mix.usecase.source = mAudioSource;
8031 }
8032}
8033
8034status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8035{
8036 audio_session_t session = chain->sessionId();
8037
8038 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8039 // Attach all tracks with same session ID to this chain.
8040 // indicate all active tracks in the chain
8041 for (const sp<MmapTrack> &track : mActiveTracks) {
8042 if (session == track->sessionId()) {
8043 chain->incTrackCnt();
8044 chain->incActiveTrackCnt();
8045 }
8046 }
8047
8048 chain->setThread(this);
8049 chain->setInBuffer(nullptr);
8050 chain->setOutBuffer(nullptr);
8051 chain->syncHalEffectsState();
8052
8053 mEffectChains.add(chain);
8054 checkSuspendOnAddEffectChain_l(chain);
8055 return NO_ERROR;
8056}
8057
8058size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8059{
8060 audio_session_t session = chain->sessionId();
8061
8062 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8063
8064 for (size_t i = 0; i < mEffectChains.size(); i++) {
8065 if (chain == mEffectChains[i]) {
8066 mEffectChains.removeAt(i);
8067 // detach all active tracks from the chain
8068 // detach all tracks with same session ID from this chain
8069 for (const sp<MmapTrack> &track : mActiveTracks) {
8070 if (session == track->sessionId()) {
8071 chain->decActiveTrackCnt();
8072 chain->decTrackCnt();
8073 }
8074 }
8075 break;
8076 }
8077 }
8078 return mEffectChains.size();
8079}
8080
8081// hasAudioSession_l() must be called with ThreadBase::mLock held
8082uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8083{
8084 uint32_t result = 0;
8085 if (getEffectChain_l(sessionId) != 0) {
8086 result = EFFECT_SESSION;
8087 }
8088
8089 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8090 sp<MmapTrack> track = mActiveTracks[i];
8091 if (sessionId == track->sessionId()) {
8092 result |= TRACK_SESSION;
8093 if (track->isFastTrack()) {
8094 result |= FAST_SESSION;
8095 }
8096 break;
8097 }
8098 }
8099
8100 return result;
8101}
8102
8103void AudioFlinger::MmapThread::threadLoop_standby()
8104{
8105 mHalStream->standby();
8106}
8107
8108void AudioFlinger::MmapThread::threadLoop_exit()
8109{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008110 sp<MmapStreamCallback> callback = mCallback.promote();
8111 if (callback != 0) {
8112 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008113 }
8114}
8115
8116status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8117{
8118 return BAD_VALUE;
8119}
8120
8121bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8122{
8123 return false;
8124}
8125
8126status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8127 const effect_descriptor_t *desc, audio_session_t sessionId)
8128{
8129 // No global effect sessions on mmap threads
8130 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8131 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8132 desc->name, mThreadName);
8133 return BAD_VALUE;
8134 }
8135
8136 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8137 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8138 desc->name);
8139 return BAD_VALUE;
8140 }
8141 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008142 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8143 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008144 return BAD_VALUE;
8145 }
8146
8147 // Only allow effects without processing load or latency
8148 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8149 return BAD_VALUE;
8150 }
8151
8152 return NO_ERROR;
8153
8154}
8155
8156void AudioFlinger::MmapThread::checkInvalidTracks_l()
8157{
8158 for (const sp<MmapTrack> &track : mActiveTracks) {
8159 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008160 sp<MmapStreamCallback> callback = mCallback.promote();
8161 if (callback != 0) {
8162 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008163 }
8164 break;
8165 }
8166 }
8167}
8168
8169void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8170{
8171 dumpInternals(fd, args);
8172 dumpTracks(fd, args);
8173 dumpEffectChains(fd, args);
8174}
8175
8176void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8177{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008178 dumpBase(fd, args);
8179
8180 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8181 mAttr.content_type, mAttr.usage, mAttr.source);
8182 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8183 if (mActiveTracks.size() == 0) {
8184 dprintf(fd, " No active clients\n");
8185 }
8186}
8187
8188void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8189{
8190 const size_t SIZE = 256;
8191 char buffer[SIZE];
8192 String8 result;
8193
8194 size_t numtracks = mActiveTracks.size();
8195 dprintf(fd, " %zu Tracks", numtracks);
8196 if (numtracks) {
8197 MmapTrack::appendDumpHeader(result);
8198 for (size_t i = 0; i < numtracks ; ++i) {
8199 sp<MmapTrack> track = mActiveTracks[i];
8200 track->dump(buffer, SIZE);
8201 result.append(buffer);
8202 }
8203 } else {
8204 dprintf(fd, "\n");
8205 }
8206 write(fd, result.string(), result.size());
8207}
8208
8209AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8210 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8211 AudioHwDevice *hwDev, AudioStreamOut *output,
8212 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8213 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8214 mStreamType(AUDIO_STREAM_MUSIC),
8215 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8216{
8217 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8218 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8219 mMasterVolume = audioFlinger->masterVolume_l();
8220 mMasterMute = audioFlinger->masterMute_l();
8221 if (mAudioHwDev) {
8222 if (mAudioHwDev->canSetMasterVolume()) {
8223 mMasterVolume = 1.0;
8224 }
8225
8226 if (mAudioHwDev->canSetMasterMute()) {
8227 mMasterMute = false;
8228 }
8229 }
8230}
8231
8232void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8233 audio_stream_type_t streamType,
8234 audio_session_t sessionId,
8235 const sp<MmapStreamCallback>& callback,
8236 audio_port_handle_t portId)
8237{
8238 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8239 mStreamType = streamType;
8240}
8241
8242AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8243{
8244 Mutex::Autolock _l(mLock);
8245 AudioStreamOut *output = mOutput;
8246 mOutput = NULL;
8247 return output;
8248}
8249
8250void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8251{
8252 Mutex::Autolock _l(mLock);
8253 // Don't apply master volume in SW if our HAL can do it for us.
8254 if (mAudioHwDev &&
8255 mAudioHwDev->canSetMasterVolume()) {
8256 mMasterVolume = 1.0;
8257 } else {
8258 mMasterVolume = value;
8259 }
8260}
8261
8262void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8263{
8264 Mutex::Autolock _l(mLock);
8265 // Don't apply master mute in SW if our HAL can do it for us.
8266 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8267 mMasterMute = false;
8268 } else {
8269 mMasterMute = muted;
8270 }
8271}
8272
8273void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8274{
8275 Mutex::Autolock _l(mLock);
8276 if (stream == mStreamType) {
8277 mStreamVolume = value;
8278 broadcast_l();
8279 }
8280}
8281
8282float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8283{
8284 Mutex::Autolock _l(mLock);
8285 if (stream == mStreamType) {
8286 return mStreamVolume;
8287 }
8288 return 0.0f;
8289}
8290
8291void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8292{
8293 Mutex::Autolock _l(mLock);
8294 if (stream == mStreamType) {
8295 mStreamMute= muted;
8296 broadcast_l();
8297 }
8298}
8299
8300void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8301{
8302 Mutex::Autolock _l(mLock);
8303 if (streamType == mStreamType) {
8304 for (const sp<MmapTrack> &track : mActiveTracks) {
8305 track->invalidate();
8306 }
8307 broadcast_l();
8308 }
8309}
8310
8311void AudioFlinger::MmapPlaybackThread::processVolume_l()
8312{
8313 float volume;
8314
8315 if (mMasterMute || mStreamMute) {
8316 volume = 0;
8317 } else {
8318 volume = mMasterVolume * mStreamVolume;
8319 }
8320
8321 if (volume != mHalVolFloat) {
8322 mHalVolFloat = volume;
8323
8324 // Convert volumes from float to 8.24
8325 uint32_t vol = (uint32_t)(volume * (1 << 24));
8326
8327 // Delegate volume control to effect in track effect chain if needed
8328 // only one effect chain can be present on DirectOutputThread, so if
8329 // there is one, the track is connected to it
8330 if (!mEffectChains.isEmpty()) {
8331 mEffectChains[0]->setVolume_l(&vol, &vol);
8332 volume = (float)vol / (1 << 24);
8333 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008334 // Try to use HW volume control and fall back to SW control if not implemented
8335 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8336 sp<MmapStreamCallback> callback = mCallback.promote();
8337 if (callback != 0) {
8338 int channelCount;
8339 if (isOutput()) {
8340 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8341 } else {
8342 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8343 }
8344 Vector<float> values;
8345 for (int i = 0; i < channelCount; i++) {
8346 values.add(volume);
8347 }
8348 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008349 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008350 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008351 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008352 }
8353 }
8354}
8355
8356void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8357{
8358 if (!mMasterMute) {
8359 char value[PROPERTY_VALUE_MAX];
8360 if (property_get("ro.audio.silent", value, "0") > 0) {
8361 char *endptr;
8362 unsigned long ul = strtoul(value, &endptr, 0);
8363 if (*endptr == '\0' && ul != 0) {
8364 ALOGD("Silence is golden");
8365 // The setprop command will not allow a property to be changed after
8366 // the first time it is set, so we don't have to worry about un-muting.
8367 setMasterMute_l(true);
8368 }
8369 }
8370 }
8371}
8372
8373void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8374{
8375 MmapThread::dumpInternals(fd, args);
8376
Glenn Kastend3bb6452016-12-05 18:14:37 -08008377 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8378 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008379 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8380}
8381
8382AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8383 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8384 AudioHwDevice *hwDev, AudioStreamIn *input,
8385 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8386 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8387 mInput(input)
8388{
8389 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8390 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8391}
8392
8393AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8394{
8395 Mutex::Autolock _l(mLock);
8396 AudioStreamIn *input = mInput;
8397 mInput = NULL;
8398 return input;
8399}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008400} // namespace android