blob: f62a9bee522539a8a5a74846f4dd7f478600dc41 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten691b02a2017-10-03 10:12:20 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x4000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800446 case MMAP:
447 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800534 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Mikhail Naganov83f04272017-02-07 10:45:09 -0800615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700616{
617 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
623 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700700 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
701 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700705 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 CreateAudioPatchConfigEventData *data =
707 (CreateAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t newDevice = getDevice();
710 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
711 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
712 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 } break;
714 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 ReleaseAudioPatchConfigEventData *data =
717 (ReleaseAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t newDevice = getDevice();
720 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
721 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
722 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 default:
Eric Laurent10351942014-05-08 18:49:52 -0700725 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
729 Mutex::Autolock _l(event->mLock);
730 if (event->mWaitStatus) {
731 event->mWaitStatus = false;
732 event->mCond.signal();
733 }
734 }
735 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
736 }
737
738 if (configChanged) {
739 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Marco Nelissenb2208842014-02-07 14:00:50 -0800743String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
744 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700745 const audio_channel_representation_t representation =
746 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700789 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800810 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
811 this, mThreadName, getTid(), type(), threadTypeToString(type()));
812
Eric Laurent81784c32012-11-19 14:55:58 -0800813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800815 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700823 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700828 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Andy Hung293558a2017-03-21 12:19:20 -0700840 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
842 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 if (locked) {
846 mLock.unlock();
847 }
848}
849
850void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000857 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800858 write(fd, buffer, strlen(buffer));
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800861 sp<EffectChain> chain = mEffectChains[i];
862 if (chain != 0) {
863 chain->dump(fd, args);
864 }
865 }
866}
867
Andy Hungdae27702016-10-31 14:01:16 -0700868void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800869{
870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700871 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872}
873
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874String16 AudioFlinger::ThreadBase::getWakeLockTag()
875{
876 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 case MIXER:
878 return String16("AudioMix");
879 case DIRECT:
880 return String16("AudioDirectOut");
881 case DUPLICATING:
882 return String16("AudioDup");
883 case RECORD:
884 return String16("AudioIn");
885 case OFFLOAD:
886 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800887 case MMAP:
888 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Andy Hungdae27702016-10-31 14:01:16 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700900 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
901 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700904 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (status == NO_ERROR) {
907 mWakeLockToken = binder;
908 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Wei Jia3f273d12015-11-24 09:06:49 -0800911
Andy Hung3f0c9022016-01-15 17:49:46 -0800912 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800913 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
914 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800915}
916
917void AudioFlinger::ThreadBase::releaseWakeLock()
918{
919 Mutex::Autolock _l(mLock);
920 releaseWakeLock_l();
921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock_l()
924{
Andy Hung3f0c9022016-01-15 17:49:46 -0800925 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800934}
935
936void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700937 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938 // use checkService() to avoid blocking if power service is not up yet
939 sp<IBinder> binder =
940 defaultServiceManager()->checkService(String16("power"));
941 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800942 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 } else {
944 mPowerManager = interface_cast<IPowerManager>(binder);
945 binder->linkToDeath(mDeathRecipient);
946 }
947 }
948}
949
Andy Hungd01b0f12016-11-07 16:10:30 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700952
953#if !LOG_NDEBUG
954 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800955 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700956 s << uid << " ";
957 }
958 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
959#endif
960
Andy Hung438e7572015-12-14 15:51:17 -0800961 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
962 if (mSystemReady) {
963 ALOGE("no wake lock to update, but system ready!");
964 } else {
965 ALOGW("no wake lock to update, system not ready yet");
966 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 return;
968 }
969 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800970 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
971 status_t status = mPowerManager->updateWakeLockUids(
972 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
973 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800974 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 }
976}
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978void AudioFlinger::ThreadBase::clearPowerManager()
979{
980 Mutex::Autolock _l(mLock);
981 releaseWakeLock_l();
982 mPowerManager.clear();
983}
984
Glenn Kasten0f11b512014-01-31 16:18:54 -0800985void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 sp<ThreadBase> thread = mThread.promote();
988 if (thread != 0) {
989 thread->clearPowerManager();
990 }
991 ALOGW("power manager service died !!!");
992}
993
Eric Laurent81784c32012-11-19 14:55:58 -0800994void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800995 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001020 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001035 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001104 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
Eric Laurent4c415062016-06-17 16:14:16 -07001123// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1124status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1125 const effect_descriptor_t *desc, audio_session_t sessionId)
1126{
1127 // No global effect sessions on record threads
1128 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1129 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1130 desc->name, mThreadName);
1131 return BAD_VALUE;
1132 }
1133 // only pre processing effects on record thread
1134 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1135 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001139
1140 // always allow effects without processing load or latency
1141 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1142 return NO_ERROR;
1143 }
1144
Eric Laurent4c415062016-06-17 16:14:16 -07001145 audio_input_flags_t flags = mInput->flags;
1146 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1147 if (flags & AUDIO_INPUT_FLAG_RAW) {
1148 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1153 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
1161// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1162status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1163 const effect_descriptor_t *desc, audio_session_t sessionId)
1164{
1165 // no preprocessing on playback threads
1166 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1167 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1168 " thread %s", desc->name, mThreadName);
1169 return BAD_VALUE;
1170 }
1171
Eric Laurent3e4de772017-07-16 16:55:08 -07001172 // always allow effects without processing load or latency
1173 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1174 return NO_ERROR;
1175 }
1176
Eric Laurent4c415062016-06-17 16:14:16 -07001177 switch (mType) {
1178 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001179#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001180 // Reject any effect on mixer multichannel sinks.
1181 // TODO: fix both format and multichannel issues with effects.
1182 if (mChannelCount != FCC_2) {
1183 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1184 " thread %s", desc->name, mChannelCount, mThreadName);
1185 return BAD_VALUE;
1186 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001187#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001188 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
Eric Laurent4c415062016-06-17 16:14:16 -07001209 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1210 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1211 desc->name);
1212 return BAD_VALUE;
1213 }
1214 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1215 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1216 " in fast mode", desc->name);
1217 return BAD_VALUE;
1218 }
1219 }
1220 } break;
1221 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001222 // nothing actionable on offload threads, if the effect:
1223 // - is offloadable: the effect can be created
1224 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1225 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001226 break;
1227 case DIRECT:
1228 // Reject any effect on Direct output threads for now, since the format of
1229 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1230 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1231 desc->name, mThreadName);
1232 return BAD_VALUE;
1233 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001234#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001235 // Reject any effect on mixer multichannel sinks.
1236 // TODO: fix both format and multichannel issues with effects.
1237 if (mChannelCount != FCC_2) {
1238 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1239 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1240 return BAD_VALUE;
1241 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001242#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001243 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1244 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1245 " thread %s", desc->name, mThreadName);
1246 return BAD_VALUE;
1247 }
1248 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1249 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1250 " DUPLICATING thread %s", desc->name, mThreadName);
1251 return BAD_VALUE;
1252 }
1253 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1254 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1255 " DUPLICATING thread %s", desc->name, mThreadName);
1256 return BAD_VALUE;
1257 }
1258 break;
1259 default:
1260 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1261 }
1262
1263 return NO_ERROR;
1264}
1265
Eric Laurent81784c32012-11-19 14:55:58 -08001266// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1267sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1268 const sp<AudioFlinger::Client>& client,
1269 const sp<IEffectClient>& effectClient,
1270 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001271 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001272 effect_descriptor_t *desc,
1273 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001274 status_t *status,
1275 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001276{
1277 sp<EffectModule> effect;
1278 sp<EffectHandle> handle;
1279 status_t lStatus;
1280 sp<EffectChain> chain;
1281 bool chainCreated = false;
1282 bool effectCreated = false;
1283 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001284 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001285
1286 lStatus = initCheck();
1287 if (lStatus != NO_ERROR) {
1288 ALOGW("createEffect_l() Audio driver not initialized.");
1289 goto Exit;
1290 }
1291
Eric Laurent81784c32012-11-19 14:55:58 -08001292 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1293
1294 { // scope for mLock
1295 Mutex::Autolock _l(mLock);
1296
Eric Laurent4c415062016-06-17 16:14:16 -07001297 lStatus = checkEffectCompatibility_l(desc, sessionId);
1298 if (lStatus != NO_ERROR) {
1299 goto Exit;
1300 }
1301
Eric Laurent81784c32012-11-19 14:55:58 -08001302 // check for existing effect chain with the requested audio session
1303 chain = getEffectChain_l(sessionId);
1304 if (chain == 0) {
1305 // create a new chain for this session
1306 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1307 chain = new EffectChain(this, sessionId);
1308 addEffectChain_l(chain);
1309 chain->setStrategy(getStrategyForSession_l(sessionId));
1310 chainCreated = true;
1311 } else {
1312 effect = chain->getEffectFromDesc_l(desc);
1313 }
1314
1315 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1316
1317 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001318 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001319 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001320 lStatus = AudioSystem::registerEffect(
1321 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 if (lStatus != NO_ERROR) {
1323 goto Exit;
1324 }
1325 effectRegistered = true;
1326 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001327 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 if (lStatus != NO_ERROR) {
1329 goto Exit;
1330 }
1331 effectCreated = true;
1332
1333 effect->setDevice(mOutDevice);
1334 effect->setDevice(mInDevice);
1335 effect->setMode(mAudioFlinger->getMode());
1336 effect->setAudioSource(mAudioSource);
1337 }
1338 // create effect handle and connect it to effect module
1339 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001340 lStatus = handle->initCheck();
1341 if (lStatus == OK) {
1342 lStatus = effect->addHandle(handle.get());
1343 }
Eric Laurent81784c32012-11-19 14:55:58 -08001344 if (enabled != NULL) {
1345 *enabled = (int)effect->isEnabled();
1346 }
1347 }
1348
1349Exit:
1350 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1351 Mutex::Autolock _l(mLock);
1352 if (effectCreated) {
1353 chain->removeEffect_l(effect);
1354 }
1355 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001356 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001357 }
1358 if (chainCreated) {
1359 removeEffectChain_l(chain);
1360 }
1361 handle.clear();
1362 }
1363
Glenn Kasten9156ef32013-08-06 15:39:08 -07001364 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001365 return handle;
1366}
1367
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001368void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1369 bool unpinIfLast)
1370{
1371 bool remove = false;
1372 sp<EffectModule> effect;
1373 {
1374 Mutex::Autolock _l(mLock);
1375
1376 effect = handle->effect().promote();
1377 if (effect == 0) {
1378 return;
1379 }
1380 // restore suspended effects if the disconnected handle was enabled and the last one.
1381 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1382 if (remove) {
1383 removeEffect_l(effect, true);
1384 }
1385 }
1386 if (remove) {
1387 mAudioFlinger->updateOrphanEffectChains(effect);
1388 AudioSystem::unregisterEffect(effect->id());
1389 if (handle->enabled()) {
1390 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1391 }
1392 }
1393}
1394
Glenn Kastend848eb42016-03-08 13:42:11 -08001395sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1396 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001397{
1398 Mutex::Autolock _l(mLock);
1399 return getEffect_l(sessionId, effectId);
1400}
1401
Glenn Kastend848eb42016-03-08 13:42:11 -08001402sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1403 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001404{
1405 sp<EffectChain> chain = getEffectChain_l(sessionId);
1406 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1407}
1408
1409// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1410// PlaybackThread::mLock held
1411status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1412{
1413 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001414 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001415 sp<EffectChain> chain = getEffectChain_l(sessionId);
1416 bool chainCreated = false;
1417
Eric Laurent5baf2af2013-09-12 17:37:00 -07001418 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001419 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001420 this, effect->desc().name, effect->desc().flags);
1421
Eric Laurent81784c32012-11-19 14:55:58 -08001422 if (chain == 0) {
1423 // create a new chain for this session
1424 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1425 chain = new EffectChain(this, sessionId);
1426 addEffectChain_l(chain);
1427 chain->setStrategy(getStrategyForSession_l(sessionId));
1428 chainCreated = true;
1429 }
1430 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1431
1432 if (chain->getEffectFromId_l(effect->id()) != 0) {
1433 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1434 this, effect->desc().name, chain.get());
1435 return BAD_VALUE;
1436 }
1437
Eric Laurent5baf2af2013-09-12 17:37:00 -07001438 effect->setOffloaded(mType == OFFLOAD, mId);
1439
Eric Laurent81784c32012-11-19 14:55:58 -08001440 status_t status = chain->addEffect_l(effect);
1441 if (status != NO_ERROR) {
1442 if (chainCreated) {
1443 removeEffectChain_l(chain);
1444 }
1445 return status;
1446 }
1447
1448 effect->setDevice(mOutDevice);
1449 effect->setDevice(mInDevice);
1450 effect->setMode(mAudioFlinger->getMode());
1451 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001452
Eric Laurent81784c32012-11-19 14:55:58 -08001453 return NO_ERROR;
1454}
1455
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001456void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001457
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001458 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001459 effect_descriptor_t desc = effect->desc();
1460 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1461 detachAuxEffect_l(effect->id());
1462 }
1463
1464 sp<EffectChain> chain = effect->chain().promote();
1465 if (chain != 0) {
1466 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001467 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001468 removeEffectChain_l(chain);
1469 }
1470 } else {
1471 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1472 }
1473}
1474
1475void AudioFlinger::ThreadBase::lockEffectChains_l(
1476 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1477{
1478 effectChains = mEffectChains;
1479 for (size_t i = 0; i < mEffectChains.size(); i++) {
1480 mEffectChains[i]->lock();
1481 }
1482}
1483
1484void AudioFlinger::ThreadBase::unlockEffectChains(
1485 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1486{
1487 for (size_t i = 0; i < effectChains.size(); i++) {
1488 effectChains[i]->unlock();
1489 }
1490}
1491
Glenn Kastend848eb42016-03-08 13:42:11 -08001492sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001493{
1494 Mutex::Autolock _l(mLock);
1495 return getEffectChain_l(sessionId);
1496}
1497
Glenn Kastend848eb42016-03-08 13:42:11 -08001498sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1499 const
Eric Laurent81784c32012-11-19 14:55:58 -08001500{
1501 size_t size = mEffectChains.size();
1502 for (size_t i = 0; i < size; i++) {
1503 if (mEffectChains[i]->sessionId() == sessionId) {
1504 return mEffectChains[i];
1505 }
1506 }
1507 return 0;
1508}
1509
1510void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1511{
1512 Mutex::Autolock _l(mLock);
1513 size_t size = mEffectChains.size();
1514 for (size_t i = 0; i < size; i++) {
1515 mEffectChains[i]->setMode_l(mode);
1516 }
1517}
1518
Eric Laurent83b88082014-06-20 18:31:16 -07001519void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1520{
1521 config->type = AUDIO_PORT_TYPE_MIX;
1522 config->ext.mix.handle = mId;
1523 config->sample_rate = mSampleRate;
1524 config->format = mFormat;
1525 config->channel_mask = mChannelMask;
1526 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1527 AUDIO_PORT_CONFIG_FORMAT;
1528}
1529
Eric Laurent72e3f392015-05-20 14:43:50 -07001530void AudioFlinger::ThreadBase::systemReady()
1531{
1532 Mutex::Autolock _l(mLock);
1533 if (mSystemReady) {
1534 return;
1535 }
1536 mSystemReady = true;
1537
1538 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1539 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1540 }
1541 mPendingConfigEvents.clear();
1542}
1543
Andy Hungdae27702016-10-31 14:01:16 -07001544template <typename T>
1545ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1546 ssize_t index = mActiveTracks.indexOf(track);
1547 if (index >= 0) {
1548 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1549 return index;
1550 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001551 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001552 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 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001565 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001566 mActiveTracksGeneration++;
1567 --mBatteryCounter[track->uid()].second;
1568 // mLatestActiveTrack is not cleared even if is the same as track.
1569 return index;
1570}
1571
1572template <typename T>
1573void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1574 for (const sp<T> &track : mActiveTracks) {
1575 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001576 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001577 }
1578 mLastActiveTracksGeneration = mActiveTracksGeneration;
1579 mActiveTracks.clear();
1580 mLatestActiveTrack.clear();
1581 mBatteryCounter.clear();
1582}
1583
1584template <typename T>
1585void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1586 sp<ThreadBase> thread, bool force) {
1587 // Updates ActiveTracks client uids to the thread wakelock.
1588 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1589 thread->updateWakeLockUids_l(getWakeLockUids());
1590 mLastActiveTracksGeneration = mActiveTracksGeneration;
1591 }
1592
1593 // Updates BatteryNotifier uids
1594 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1595 const uid_t uid = it->first;
1596 ssize_t &previous = it->second.first;
1597 ssize_t &current = it->second.second;
1598 if (current > 0) {
1599 if (previous == 0) {
1600 BatteryNotifier::getInstance().noteStartAudio(uid);
1601 }
1602 previous = current;
1603 ++it;
1604 } else if (current == 0) {
1605 if (previous > 0) {
1606 BatteryNotifier::getInstance().noteStopAudio(uid);
1607 }
1608 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1609 } else /* (current < 0) */ {
1610 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1611 }
1612 }
1613}
Eric Laurent83b88082014-06-20 18:31:16 -07001614
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001615template <typename T>
1616void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1617 const char *funcName, const sp<T> &track) const {
1618 if (mLocalLog != nullptr) {
1619 String8 result;
1620 track->appendDump(result, false /* active */);
1621 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1622 }
1623}
1624
Eric Laurent6acd1d42017-01-04 14:23:29 -08001625void AudioFlinger::ThreadBase::broadcast_l()
1626{
1627 // Thread could be blocked waiting for async
1628 // so signal it to handle state changes immediately
1629 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1630 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1631 mSignalPending = true;
1632 mWaitWorkCV.broadcast();
1633}
1634
Eric Laurent81784c32012-11-19 14:55:58 -08001635// ----------------------------------------------------------------------------
1636// Playback
1637// ----------------------------------------------------------------------------
1638
1639AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1640 AudioStreamOut* output,
1641 audio_io_handle_t id,
1642 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001643 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001644 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001645 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001646 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001647 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001648 mMixerBuffer(NULL),
1649 mMixerBufferSize(0),
1650 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1651 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001652 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001653 mEffectBuffer(NULL),
1654 mEffectBufferSize(0),
1655 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1656 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001657 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001658 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001659 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001660 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001661 // mStreamTypes[] initialized in constructor body
1662 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001663 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001664 mMixerStatus(MIXER_IDLE),
1665 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001666 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001667 mBytesRemaining(0),
1668 mCurrentWriteLength(0),
1669 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001670 mWriteAckSequence(0),
1671 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001672 mScreenState(AudioFlinger::mScreenState),
1673 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001674 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001675 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1676 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
Glenn Kastend7dca052015-03-05 16:05:54 -08001678 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1679 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001680
1681 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1682 // it would be safer to explicitly pass initial masterVolume/masterMute as
1683 // parameter.
1684 //
1685 // If the HAL we are using has support for master volume or master mute,
1686 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1687 // and the mute set to false).
1688 mMasterVolume = audioFlinger->masterVolume_l();
1689 mMasterMute = audioFlinger->masterMute_l();
1690 if (mOutput && mOutput->audioHwDev) {
1691 if (mOutput->audioHwDev->canSetMasterVolume()) {
1692 mMasterVolume = 1.0;
1693 }
1694
1695 if (mOutput->audioHwDev->canSetMasterMute()) {
1696 mMasterMute = false;
1697 }
1698 }
1699
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001700 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001701
Eric Laurent223fd5c2014-11-11 13:43:36 -08001702 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001703 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001704 stream = (audio_stream_type_t) (stream + 1)) {
1705 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1706 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1707 }
Eric Laurent81784c32012-11-19 14:55:58 -08001708}
1709
1710AudioFlinger::PlaybackThread::~PlaybackThread()
1711{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001712 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001713 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001714 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001715 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001716}
1717
1718void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1719{
1720 dumpInternals(fd, args);
1721 dumpTracks(fd, args);
1722 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001723 dprintf(fd, " Local log:\n");
1724 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
Glenn Kasten0f11b512014-01-31 16:18:54 -08001727void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001728{
Eric Laurent81784c32012-11-19 14:55:58 -08001729 String8 result;
1730
Marco Nelissenb2208842014-02-07 14:00:50 -08001731 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001732 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1733 const stream_type_t *st = &mStreamTypes[i];
1734 if (i > 0) {
1735 result.appendFormat(", ");
1736 }
1737 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1738 if (st->mute) {
1739 result.append("M");
1740 }
1741 }
1742 result.append("\n");
1743 write(fd, result.string(), result.length());
1744 result.clear();
1745
Eric Laurent81784c32012-11-19 14:55:58 -08001746 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1747 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001748 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001749 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001750
1751 size_t numtracks = mTracks.size();
1752 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001753 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001754 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001755 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001756 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001757 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001758 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001759 Track::appendDumpHeader(result);
1760 for (size_t i = 0; i < numtracks; ++i) {
1761 sp<Track> track = mTracks[i];
1762 if (track != 0) {
1763 bool active = mActiveTracks.indexOf(track) >= 0;
1764 if (active) {
1765 numactiveseen++;
1766 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001767 result.append(prefix);
1768 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001769 }
1770 }
1771 } else {
1772 result.append("\n");
1773 }
1774 if (numactiveseen != numactive) {
1775 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001776 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001777 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001778 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001779 Track::appendDumpHeader(result);
1780 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001781 sp<Track> track = mActiveTracks[i];
1782 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001783 result.append(prefix);
1784 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001785 }
1786 }
1787 }
1788
1789 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001790}
1791
1792void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1793{
Glenn Kasten44182c22015-03-05 17:12:23 -08001794 dumpBase(fd, args);
1795
Elliott Hughes87cebad2014-05-22 10:14:43 -07001796 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001797 dprintf(fd, " Last write occurred (msecs): %llu\n",
1798 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001799 dprintf(fd, " Total writes: %d\n", mNumWrites);
1800 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1801 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1802 dprintf(fd, " Suspend count: %d\n", mSuspended);
1803 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1804 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1805 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1806 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001807 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001808 AudioStreamOut *output = mOutput;
1809 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001810 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1811 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001812 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1813 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1814 if (mPipeSink.get() != nullptr) {
1815 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1816 }
1817 if (output != nullptr) {
1818 dprintf(fd, " Hal stream dump:\n");
1819 (void)output->stream->dump(fd);
1820 }
Eric Laurent81784c32012-11-19 14:55:58 -08001821}
1822
1823// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001824
1825void AudioFlinger::PlaybackThread::onFirstRef()
1826{
Glenn Kastend7dca052015-03-05 16:05:54 -08001827 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001828}
1829
1830// ThreadBase virtuals
1831void AudioFlinger::PlaybackThread::preExit()
1832{
1833 ALOGV(" preExit()");
1834 // FIXME this is using hard-coded strings but in the future, this functionality will be
1835 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001836 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1837 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001838}
1839
1840// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1841sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1842 const sp<AudioFlinger::Client>& client,
1843 audio_stream_type_t streamType,
Eric Laurent21da6472017-11-09 16:29:26 -08001844 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001845 audio_format_t format,
1846 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001847 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001848 size_t *pNotificationFrameCount,
1849 uint32_t notificationsPerBuffer,
1850 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001851 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001852 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001853 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001854 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001855 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001856 status_t *status,
1857 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001858{
Glenn Kasten74935e42013-12-19 08:56:45 -08001859 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001860 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001861 sp<Track> track;
1862 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001863 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001864 audio_output_flags_t requestedFlags = *flags;
1865
1866 if (*pSampleRate == 0) {
1867 *pSampleRate = mSampleRate;
1868 }
1869 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001870
1871 // special case for FAST flag considered OK if fast mixer is present
1872 if (hasFastMixer()) {
1873 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1874 }
1875
1876 // Check if requested flags are compatible with output stream flags
1877 if ((*flags & outputFlags) != *flags) {
1878 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1879 *flags, outputFlags);
1880 *flags = (audio_output_flags_t)(*flags & outputFlags);
1881 }
Eric Laurent81784c32012-11-19 14:55:58 -08001882
Eric Laurent81784c32012-11-19 14:55:58 -08001883 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001884 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001885 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001886 // PCM data
1887 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001888 // TODO: extract as a data library function that checks that a computationally
1889 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001890 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001891 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1892 (channelMask == AUDIO_CHANNEL_OUT_MONO
1893 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001894 // hardware sample rate
1895 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001896 // normal mixer has an associated fast mixer
1897 hasFastMixer() &&
1898 // there are sufficient fast track slots available
1899 (mFastTrackAvailMask != 0)
1900 // FIXME test that MixerThread for this fast track has a capable output HAL
1901 // FIXME add a permission test also?
1902 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001903 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1904 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001905 // read the fast track multiplier property the first time it is needed
1906 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1907 if (ok != 0) {
1908 ALOGE("%s pthread_once failed: %d", __func__, ok);
1909 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001910 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001911 }
Eric Laurent4c415062016-06-17 16:14:16 -07001912
1913 // check compatibility with audio effects.
1914 { // scope for mLock
1915 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001916 for (audio_session_t session : {
1917 AUDIO_SESSION_OUTPUT_STAGE,
1918 AUDIO_SESSION_OUTPUT_MIX,
1919 sessionId,
1920 }) {
1921 sp<EffectChain> chain = getEffectChain_l(session);
1922 if (chain.get() != nullptr) {
1923 audio_output_flags_t old = *flags;
1924 chain->checkOutputFlagCompatibility(flags);
1925 if (old != *flags) {
1926 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1927 (int)session, (int)old, (int)*flags);
1928 }
Eric Laurent4c415062016-06-17 16:14:16 -07001929 }
1930 }
1931 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001932 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001933 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1934 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001935 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001936 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1937 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001938 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001939 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001940 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001941 audio_is_linear_pcm(format),
1942 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001943 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001944 }
1945 }
Eric Laurent21da6472017-11-09 16:29:26 -08001946
1947 if (!audio_has_proportional_frames(format)) {
1948 if (sharedBuffer != 0) {
1949 // Same comment as below about ignoring frameCount parameter for set()
1950 frameCount = sharedBuffer->size();
1951 } else if (frameCount == 0) {
1952 frameCount = mNormalFrameCount;
1953 }
1954 if (notificationFrameCount != frameCount) {
1955 notificationFrameCount = frameCount;
1956 }
1957 } else if (sharedBuffer != 0) {
1958 // FIXME: Ensure client side memory buffers need
1959 // not have additional alignment beyond sample
1960 // (e.g. 16 bit stereo accessed as 32 bit frame).
1961 size_t alignment = audio_bytes_per_sample(format);
1962 if (alignment & 1) {
1963 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1964 alignment = 1;
1965 }
1966 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1967 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1968 if (channelCount > 1) {
1969 // More than 2 channels does not require stronger alignment than stereo
1970 alignment <<= 1;
1971 }
1972 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
1973 ALOGE("Invalid buffer alignment: address %p, channel count %u",
1974 sharedBuffer->pointer(), channelCount);
1975 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001976 goto Exit;
1977 }
Eric Laurent21da6472017-11-09 16:29:26 -08001978
1979 // When initializing a shared buffer AudioTrack via constructors,
1980 // there's no frameCount parameter.
1981 // But when initializing a shared buffer AudioTrack via set(),
1982 // there _is_ a frameCount parameter. We silently ignore it.
1983 frameCount = sharedBuffer->size() / frameSize;
1984 } else {
1985 size_t minFrameCount = 0;
1986 // For fast tracks we try to respect the application's request for notifications per buffer.
1987 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
1988 if (notificationsPerBuffer > 0) {
1989 // Avoid possible arithmetic overflow during multiplication.
1990 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
1991 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
1992 notificationsPerBuffer, mFrameCount);
1993 } else {
1994 minFrameCount = mFrameCount * notificationsPerBuffer;
1995 }
1996 }
1997 } else {
1998 // For normal PCM streaming tracks, update minimum frame count.
1999 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2000 // cover audio hardware latency.
2001 // This is probably too conservative, but legacy application code may depend on it.
2002 // If you change this calculation, also review the start threshold which is related.
2003 uint32_t latencyMs = latency_l();
2004 if (latencyMs == 0) {
2005 ALOGE("Error when retrieving output stream latency");
2006 lStatus = UNKNOWN_ERROR;
2007 goto Exit;
2008 }
2009
2010 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2011 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2012
Eric Laurent81784c32012-11-19 14:55:58 -08002013 }
Eric Laurent21da6472017-11-09 16:29:26 -08002014 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002015 frameCount = minFrameCount;
2016 }
Eric Laurent81784c32012-11-19 14:55:58 -08002017 }
Eric Laurent21da6472017-11-09 16:29:26 -08002018
2019 // Make sure that application is notified with sufficient margin before underrun.
2020 // The client can divide the AudioTrack buffer into sub-buffers,
2021 // and expresses its desire to server as the notification frame count.
2022 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2023 size_t maxNotificationFrames;
2024 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2025 // notify every HAL buffer, regardless of the size of the track buffer
2026 maxNotificationFrames = mFrameCount;
2027 } else {
2028 // For normal tracks, use at least double-buffering if no sample rate conversion,
2029 // or at least triple-buffering if there is sample rate conversion
2030 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2031 maxNotificationFrames = frameCount / nBuffering;
2032 // If client requested a fast track but this was denied, then use the smaller maximum.
2033 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2034 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2035 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2036 maxNotificationFrames = maxNotificationFramesFastDenied;
2037 }
2038 }
2039 }
2040 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2041 if (notificationFrameCount == 0) {
2042 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2043 maxNotificationFrames, frameCount);
2044 } else {
2045 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2046 notificationFrameCount, maxNotificationFrames, frameCount);
2047 }
2048 notificationFrameCount = maxNotificationFrames;
2049 }
2050 }
2051
Glenn Kasten74935e42013-12-19 08:56:45 -08002052 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002053 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002054
Glenn Kastenc3df8382014-03-13 15:05:25 -07002055 switch (mType) {
2056
2057 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002058 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002059 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002060 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2061 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002062 sampleRate, format, channelMask, mOutput, mFormat);
2063 lStatus = BAD_VALUE;
2064 goto Exit;
2065 }
2066 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002067 break;
2068
2069 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002070 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002071 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2072 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002073 sampleRate, format, channelMask, mOutput, mFormat);
2074 lStatus = BAD_VALUE;
2075 goto Exit;
2076 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002077 break;
2078
2079 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002080 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002081 ALOGE("createTrack_l() Bad parameter: format %#x \""
2082 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002083 format, mOutput, mFormat);
2084 lStatus = BAD_VALUE;
2085 goto Exit;
2086 }
Andy Hungcd044842014-08-07 11:04:34 -07002087 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002088 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2089 lStatus = BAD_VALUE;
2090 goto Exit;
2091 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002092 break;
2093
Eric Laurent81784c32012-11-19 14:55:58 -08002094 }
2095
2096 lStatus = initCheck();
2097 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002098 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002099 goto Exit;
2100 }
2101
2102 { // scope for mLock
2103 Mutex::Autolock _l(mLock);
2104
2105 // all tracks in same audio session must share the same routing strategy otherwise
2106 // conflicts will happen when tracks are moved from one output to another by audio policy
2107 // manager
2108 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2109 for (size_t i = 0; i < mTracks.size(); ++i) {
2110 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002111 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002112 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2113 if (sessionId == t->sessionId() && strategy != actual) {
2114 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2115 strategy, actual);
2116 lStatus = BAD_VALUE;
2117 goto Exit;
2118 }
2119 }
2120 }
2121
Glenn Kastend79072e2016-01-06 08:41:20 -08002122 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002123 channelMask, frameCount,
2124 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002125 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002126
Glenn Kasten03003332013-08-06 15:40:54 -07002127 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2128 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002129 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002130 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002131 goto Exit;
2132 }
2133 mTracks.add(track);
2134
2135 sp<EffectChain> chain = getEffectChain_l(sessionId);
2136 if (chain != 0) {
2137 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2138 track->setMainBuffer(chain->inBuffer());
2139 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2140 chain->incTrackCnt();
2141 }
2142
Eric Laurent05067782016-06-01 18:27:28 -07002143 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002144 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2145 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2146 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002147 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002148 }
2149 }
2150
2151 lStatus = NO_ERROR;
2152
2153Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002154 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002155 return track;
2156}
2157
2158uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2159{
2160 return latency;
2161}
2162
2163uint32_t AudioFlinger::PlaybackThread::latency() const
2164{
2165 Mutex::Autolock _l(mLock);
2166 return latency_l();
2167}
2168uint32_t AudioFlinger::PlaybackThread::latency_l() const
2169{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002170 uint32_t latency;
2171 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2172 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002173 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002174 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002175}
2176
2177void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2178{
2179 Mutex::Autolock _l(mLock);
2180 // Don't apply master volume in SW if our HAL can do it for us.
2181 if (mOutput && mOutput->audioHwDev &&
2182 mOutput->audioHwDev->canSetMasterVolume()) {
2183 mMasterVolume = 1.0;
2184 } else {
2185 mMasterVolume = value;
2186 }
2187}
2188
2189void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2190{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002191 if (isDuplicating()) {
2192 return;
2193 }
Eric Laurent81784c32012-11-19 14:55:58 -08002194 Mutex::Autolock _l(mLock);
2195 // Don't apply master mute in SW if our HAL can do it for us.
2196 if (mOutput && mOutput->audioHwDev &&
2197 mOutput->audioHwDev->canSetMasterMute()) {
2198 mMasterMute = false;
2199 } else {
2200 mMasterMute = muted;
2201 }
2202}
2203
2204void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2205{
2206 Mutex::Autolock _l(mLock);
2207 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002208 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002209}
2210
2211void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2212{
2213 Mutex::Autolock _l(mLock);
2214 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002215 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002216}
2217
2218float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2219{
2220 Mutex::Autolock _l(mLock);
2221 return mStreamTypes[stream].volume;
2222}
2223
2224// addTrack_l() must be called with ThreadBase::mLock held
2225status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2226{
2227 status_t status = ALREADY_EXISTS;
2228
Eric Laurent81784c32012-11-19 14:55:58 -08002229 if (mActiveTracks.indexOf(track) < 0) {
2230 // the track is newly added, make sure it fills up all its
2231 // buffers before playing. This is to ensure the client will
2232 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002233 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 TrackBase::track_state state = track->mState;
2235 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002236 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002237 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002238 mLock.lock();
2239 // abort track was stopped/paused while we released the lock
2240 if (state != track->mState) {
2241 if (status == NO_ERROR) {
2242 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002243 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002244 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002245 mLock.lock();
2246 }
2247 return INVALID_OPERATION;
2248 }
2249 // abort if start is rejected by audio policy manager
2250 if (status != NO_ERROR) {
2251 return PERMISSION_DENIED;
2252 }
2253#ifdef ADD_BATTERY_DATA
2254 // to track the speaker usage
2255 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2256#endif
2257 }
2258
Eric Laurent51716182016-02-29 18:00:56 -08002259 // set retry count for buffer fill
2260 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002261 if (track->isStopping_1()) {
2262 track->mRetryCount = kMaxTrackStopRetriesOffload;
2263 } else {
2264 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2265 }
2266 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002267 } else {
2268 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002269 track->mFillingUpStatus =
2270 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002271 }
2272
Eric Laurent81784c32012-11-19 14:55:58 -08002273 track->mResetDone = false;
2274 track->mPresentationCompleteFrames = 0;
2275 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002276 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2277 if (chain != 0) {
2278 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2279 track->sessionId());
2280 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002281 }
2282
2283 status = NO_ERROR;
2284 }
2285
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002286 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002287 return status;
2288}
2289
Eric Laurentbfb1b832013-01-07 09:53:42 -08002290bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002291{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002292 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002293 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002294 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2295 track->mState = TrackBase::STOPPED;
2296 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002297 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002298 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002300 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002301
2302 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002303}
2304
2305void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2306{
2307 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002308
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002309 String8 result;
2310 track->appendDump(result, false /* active */);
2311 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002312
Eric Laurent81784c32012-11-19 14:55:58 -08002313 mTracks.remove(track);
2314 deleteTrackName_l(track->name());
2315 // redundant as track is about to be destroyed, for dumpsys only
2316 track->mName = -1;
2317 if (track->isFastTrack()) {
2318 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002319 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002320 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2321 mFastTrackAvailMask |= 1 << index;
2322 // redundant as track is about to be destroyed, for dumpsys only
2323 track->mFastIndex = -1;
2324 }
2325 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2326 if (chain != 0) {
2327 chain->decTrackCnt();
2328 }
2329}
2330
2331String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2332{
Eric Laurent81784c32012-11-19 14:55:58 -08002333 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 String8 out_s8;
2335 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2336 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002337 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002339}
2340
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002341void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002342 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2343 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002344
Eric Laurent73e26b62015-04-27 16:55:58 -07002345 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002346
2347 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002348 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002349 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002350 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002351 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002352 desc->mChannelMask = mChannelMask;
2353 desc->mSamplingRate = mSampleRate;
2354 desc->mFormat = mFormat;
2355 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002356 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002357 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002358 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002359 break;
2360
Eric Laurent73e26b62015-04-27 16:55:58 -07002361 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002362 default:
2363 break;
2364 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002365 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002366}
2367
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002368void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002369{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002370 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371}
2372
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002373void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002375 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002376}
2377
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002378void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002379{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002380 mCallbackThread->setAsyncError();
2381}
2382
Eric Laurent3b4529e2013-09-05 18:09:19 -07002383void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002384{
2385 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002386 // reject out of sequence requests
2387 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2388 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 mWaitWorkCV.signal();
2390 }
2391}
2392
Eric Laurent3b4529e2013-09-05 18:09:19 -07002393void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002394{
2395 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002396 // reject out of sequence requests
2397 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2398 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002399 mWaitWorkCV.signal();
2400 }
2401}
2402
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002403void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002404{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002405 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002406 mSampleRate = mOutput->getSampleRate();
2407 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002408 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002409 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002410 }
Andy Hung9a592762014-07-21 21:56:01 -07002411 if ((mType == MIXER || mType == DUPLICATING)
2412 && !isValidPcmSinkChannelMask(mChannelMask)) {
2413 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2414 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002415 }
Andy Hunge5412692014-05-16 11:25:07 -07002416 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002417
2418 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002419 status_t result = mOutput->stream->getFormat(&mHALFormat);
2420 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002421 // Get format from the shim, which will be different than the HAL format
2422 // if playing compressed audio over HDMI passthrough.
2423 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002424 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002425 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002426 }
Andy Hung6146c082014-03-18 11:56:15 -07002427 if ((mType == MIXER || mType == DUPLICATING)
2428 && !isValidPcmSinkFormat(mFormat)) {
2429 LOG_FATAL("HAL format %#x not supported for mixed output",
2430 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002431 }
Phil Burk062e67a2015-02-11 13:40:50 -08002432 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002433 result = mOutput->stream->getBufferSize(&mBufferSize);
2434 LOG_ALWAYS_FATAL_IF(result != OK,
2435 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002436 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002437 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002438 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002439 mFrameCount);
2440 }
2441
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002442 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2443 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002444 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002445 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446 }
2447 }
2448
Eric Laurentd1f69b02014-12-15 14:33:13 -08002449 mHwSupportsPause = false;
2450 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002451 bool supportsPause = false, supportsResume = false;
2452 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2453 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002454 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002455 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002456 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002457 } else if (supportsResume) {
2458 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002459 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002460 }
2461 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002462 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2463 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2464 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002465
Andy Hungfbfc3952015-01-15 13:33:51 -08002466 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2467 // For best precision, we use float instead of the associated output
2468 // device format (typically PCM 16 bit).
2469
2470 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2471 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2472 mBufferSize = mFrameSize * mFrameCount;
2473
2474 // TODO: We currently use the associated output device channel mask and sample rate.
2475 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2476 // (if a valid mask) to avoid premature downmix.
2477 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2478 // instead of the output device sample rate to avoid loss of high frequency information.
2479 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2480 }
2481
Andy Hung09a50072014-02-27 14:30:47 -08002482 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002483 double multiplier = 1.0;
2484 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2485 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002486 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2487 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002488
Eric Laurent81784c32012-11-19 14:55:58 -08002489 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2490 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2491 maxNormalFrameCount = maxNormalFrameCount & ~15;
2492 if (maxNormalFrameCount < minNormalFrameCount) {
2493 maxNormalFrameCount = minNormalFrameCount;
2494 }
2495 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2496 if (multiplier <= 1.0) {
2497 multiplier = 1.0;
2498 } else if (multiplier <= 2.0) {
2499 if (2 * mFrameCount <= maxNormalFrameCount) {
2500 multiplier = 2.0;
2501 } else {
2502 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2503 }
2504 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002505 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002506 }
2507 }
2508 mNormalFrameCount = multiplier * mFrameCount;
2509 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002510 if (mType == MIXER || mType == DUPLICATING) {
2511 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2512 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002513 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002514 mNormalFrameCount);
2515
Andy Hung08fb1742015-05-31 23:22:10 -07002516 // Check if we want to throttle the processing to no more than 2x normal rate
2517 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002518 mThreadThrottleTimeMs = 0;
2519 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002520 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2521
Andy Hung010a1a12014-03-13 13:57:33 -07002522 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2523 // Originally this was int16_t[] array, need to remove legacy implications.
2524 free(mSinkBuffer);
2525 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002526 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2527 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2528 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002529 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002530
Andy Hung69aed5f2014-02-25 17:24:40 -08002531 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2532 // drives the output.
2533 free(mMixerBuffer);
2534 mMixerBuffer = NULL;
2535 if (mMixerBufferEnabled) {
2536 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2537 mMixerBufferSize = mNormalFrameCount * mChannelCount
2538 * audio_bytes_per_sample(mMixerBufferFormat);
2539 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2540 }
Andy Hung98ef9782014-03-04 14:46:50 -08002541 free(mEffectBuffer);
2542 mEffectBuffer = NULL;
2543 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002544 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002545 mEffectBufferSize = mNormalFrameCount * mChannelCount
2546 * audio_bytes_per_sample(mEffectBufferFormat);
2547 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2548 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002549
Eric Laurent81784c32012-11-19 14:55:58 -08002550 // force reconfiguration of effect chains and engines to take new buffer size and audio
2551 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002552 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002553 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2554 // matter.
2555 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2556 Vector< sp<EffectChain> > effectChains = mEffectChains;
2557 for (size_t i = 0; i < effectChains.size(); i ++) {
2558 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2559 }
2560}
2561
2562
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002563status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002564{
2565 if (halFrames == NULL || dspFrames == NULL) {
2566 return BAD_VALUE;
2567 }
2568 Mutex::Autolock _l(mLock);
2569 if (initCheck() != NO_ERROR) {
2570 return INVALID_OPERATION;
2571 }
Andy Hung818e7a32016-02-16 18:08:07 -08002572 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002573 *halFrames = framesWritten;
2574
2575 if (isSuspended()) {
2576 // return an estimation of rendered frames when the output is suspended
2577 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002578 *dspFrames = (uint32_t)
2579 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002580 return NO_ERROR;
2581 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002582 status_t status;
2583 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002584 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002585 *dspFrames = (size_t)frames;
2586 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002587 }
2588}
2589
Eric Laurent4c415062016-06-17 16:14:16 -07002590// hasAudioSession_l() must be called with ThreadBase::mLock held
2591uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002592{
Eric Laurent81784c32012-11-19 14:55:58 -08002593 uint32_t result = 0;
2594 if (getEffectChain_l(sessionId) != 0) {
2595 result = EFFECT_SESSION;
2596 }
2597
2598 for (size_t i = 0; i < mTracks.size(); ++i) {
2599 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002600 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002601 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002602 if (track->isFastTrack()) {
2603 result |= FAST_SESSION;
2604 }
Eric Laurent81784c32012-11-19 14:55:58 -08002605 break;
2606 }
2607 }
2608
2609 return result;
2610}
2611
Glenn Kastend848eb42016-03-08 13:42:11 -08002612uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002613{
2614 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2615 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2616 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2617 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2618 }
2619 for (size_t i = 0; i < mTracks.size(); i++) {
2620 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002621 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002622 return AudioSystem::getStrategyForStream(track->streamType());
2623 }
2624 }
2625 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2626}
2627
2628
Phil Burk062e67a2015-02-11 13:40:50 -08002629AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002630{
2631 Mutex::Autolock _l(mLock);
2632 return mOutput;
2633}
2634
Phil Burk062e67a2015-02-11 13:40:50 -08002635AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002636{
2637 Mutex::Autolock _l(mLock);
2638 AudioStreamOut *output = mOutput;
2639 mOutput = NULL;
2640 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2641 // must push a NULL and wait for ack
2642 mOutputSink.clear();
2643 mPipeSink.clear();
2644 mNormalSink.clear();
2645 return output;
2646}
2647
2648// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002649sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002650{
2651 if (mOutput == NULL) {
2652 return NULL;
2653 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002654 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002655}
2656
2657uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2658{
2659 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2660}
2661
2662status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2663{
2664 if (!isValidSyncEvent(event)) {
2665 return BAD_VALUE;
2666 }
2667
2668 Mutex::Autolock _l(mLock);
2669
2670 for (size_t i = 0; i < mTracks.size(); ++i) {
2671 sp<Track> track = mTracks[i];
2672 if (event->triggerSession() == track->sessionId()) {
2673 (void) track->setSyncEvent(event);
2674 return NO_ERROR;
2675 }
2676 }
2677
2678 return NAME_NOT_FOUND;
2679}
2680
2681bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2682{
2683 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2684}
2685
2686void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2687 const Vector< sp<Track> >& tracksToRemove)
2688{
2689 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002690 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002691 for (size_t i = 0 ; i < count ; i++) {
2692 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002693 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002694 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002695 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002696#ifdef ADD_BATTERY_DATA
2697 // to track the speaker usage
2698 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2699#endif
2700 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002701 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002702 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 }
Eric Laurent81784c32012-11-19 14:55:58 -08002704 }
2705 }
2706 }
Eric Laurent81784c32012-11-19 14:55:58 -08002707}
2708
2709void AudioFlinger::PlaybackThread::checkSilentMode_l()
2710{
2711 if (!mMasterMute) {
2712 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002713 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2714 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2715 return;
2716 }
Eric Laurent81784c32012-11-19 14:55:58 -08002717 if (property_get("ro.audio.silent", value, "0") > 0) {
2718 char *endptr;
2719 unsigned long ul = strtoul(value, &endptr, 0);
2720 if (*endptr == '\0' && ul != 0) {
2721 ALOGD("Silence is golden");
2722 // The setprop command will not allow a property to be changed after
2723 // the first time it is set, so we don't have to worry about un-muting.
2724 setMasterMute_l(true);
2725 }
2726 }
2727 }
2728}
2729
2730// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002732{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002733 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002734 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002735 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002736 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002737
2738 // If an NBAIO sink is present, use it to write the normal mixer's submix
2739 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002740
Andy Hung010a1a12014-03-13 13:57:33 -07002741 const size_t count = mBytesRemaining / mFrameSize;
2742
Simon Wilson2d590962012-11-29 15:18:50 -08002743 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002744 // update the setpoint when AudioFlinger::mScreenState changes
2745 uint32_t screenState = AudioFlinger::mScreenState;
2746 if (screenState != mScreenState) {
2747 mScreenState = screenState;
2748 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2749 if (pipe != NULL) {
2750 pipe->setAvgFrames((mScreenState & 1) ?
2751 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2752 }
2753 }
Andy Hung010a1a12014-03-13 13:57:33 -07002754 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002755 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002756 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002757 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 } else {
2759 bytesWritten = framesWritten;
2760 }
2761 // otherwise use the HAL / AudioStreamOut directly
2762 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002763 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002764
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002766 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2767 mWriteAckSequence += 2;
2768 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002769 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002770 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002771 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002772 // FIXME We should have an implementation of timestamps for direct output threads.
2773 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002774 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002775
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 if (mUseAsyncWrite &&
2777 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2778 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002779 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002781 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002782 }
Eric Laurent81784c32012-11-19 14:55:58 -08002783 }
2784
Eric Laurent81784c32012-11-19 14:55:58 -08002785 mNumWrites++;
2786 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002787 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002788 return bytesWritten;
2789}
2790
2791void AudioFlinger::PlaybackThread::threadLoop_drain()
2792{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002793 bool supportsDrain = false;
2794 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2796 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002797 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2798 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002799 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002800 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002802 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002803 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002804 }
2805}
2806
2807void AudioFlinger::PlaybackThread::threadLoop_exit()
2808{
Eric Laurent275e8e92014-11-30 15:14:47 -08002809 {
2810 Mutex::Autolock _l(mLock);
2811 for (size_t i = 0; i < mTracks.size(); i++) {
2812 sp<Track> track = mTracks[i];
2813 track->invalidate();
2814 }
Andy Hungdae27702016-10-31 14:01:16 -07002815 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2816 // After we exit there are no more track changes sent to BatteryNotifier
2817 // because that requires an active threadLoop.
2818 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2819 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002820 }
Eric Laurent81784c32012-11-19 14:55:58 -08002821}
2822
2823/*
2824The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002825 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002826 - mActiveSleepTimeUs from activeSleepTimeUs()
2827 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002828 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2829 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002830 - maxPeriod from frame count and sample rate (MIXER only)
2831
2832The parameters that affect these derived values are:
2833 - frame count
2834 - frame size
2835 - sample rate
2836 - device type: A2DP or not
2837 - device latency
2838 - format: PCM or not
2839 - active sleep time
2840 - idle sleep time
2841*/
2842
2843void AudioFlinger::PlaybackThread::cacheParameters_l()
2844{
Andy Hung25c2dac2014-02-27 14:56:00 -08002845 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002846 mActiveSleepTimeUs = activeSleepTimeUs();
2847 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002848
2849 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2850 // truncating audio when going to standby.
2851 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2852 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2853 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2854 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2855 }
2856 }
Eric Laurent81784c32012-11-19 14:55:58 -08002857}
2858
Eric Laurent13084622016-05-17 10:51:49 -07002859bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002860{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002861 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002862 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002863 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002864 size_t size = mTracks.size();
2865 for (size_t i = 0; i < size; i++) {
2866 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002867 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002868 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002869 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002870 }
2871 }
Eric Laurent13084622016-05-17 10:51:49 -07002872 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002873}
2874
Haynes Mathew George05317d22016-05-03 16:34:26 -07002875void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2876{
2877 Mutex::Autolock _l(mLock);
2878 invalidateTracks_l(streamType);
2879}
2880
Eric Laurent81784c32012-11-19 14:55:58 -08002881status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2882{
Glenn Kastend848eb42016-03-08 13:42:11 -08002883 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002884 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2885 status_t result = EffectBufferHalInterface::mirror(
2886 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2887 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2888 &halInBuffer);
2889 if (result != OK) return result;
2890 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002891 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002892 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002893 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002894 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002895 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002896 if (mType != DIRECT) {
2897 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002898 status_t result = EffectBufferHalInterface::allocate(
rago94a1ee82017-07-21 15:11:02 -07002899 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002900 &halInBuffer);
2901 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002902#ifdef FLOAT_EFFECT_CHAIN
2903 buffer = halInBuffer->audioBuffer()->f32;
2904#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08002905 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07002906#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08002907 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2908 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002909 }
2910
2911 // Attach all tracks with same session ID to this chain.
2912 for (size_t i = 0; i < mTracks.size(); ++i) {
2913 sp<Track> track = mTracks[i];
2914 if (session == track->sessionId()) {
2915 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2916 buffer);
2917 track->setMainBuffer(buffer);
2918 chain->incTrackCnt();
2919 }
2920 }
2921
2922 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002923 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002924 if (session == track->sessionId()) {
2925 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2926 chain->incActiveTrackCnt();
2927 }
2928 }
2929 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002930 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002931 chain->setInBuffer(halInBuffer);
2932 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002933 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002934 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002935 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2936 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002937 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002938 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002939 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002940 // Effect chain for other sessions are inserted at beginning of effect
2941 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002942 // sessions is not important.
2943 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2944 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2945 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002946 size_t size = mEffectChains.size();
2947 size_t i = 0;
2948 for (i = 0; i < size; i++) {
2949 if (mEffectChains[i]->sessionId() < session) {
2950 break;
2951 }
2952 }
2953 mEffectChains.insertAt(chain, i);
2954 checkSuspendOnAddEffectChain_l(chain);
2955
2956 return NO_ERROR;
2957}
2958
2959size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2960{
Glenn Kastend848eb42016-03-08 13:42:11 -08002961 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002962
2963 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2964
2965 for (size_t i = 0; i < mEffectChains.size(); i++) {
2966 if (chain == mEffectChains[i]) {
2967 mEffectChains.removeAt(i);
2968 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002969 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002970 if (session == track->sessionId()) {
2971 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2972 chain.get(), session);
2973 chain->decActiveTrackCnt();
2974 }
2975 }
2976
2977 // detach all tracks with same session ID from this chain
2978 for (size_t i = 0; i < mTracks.size(); ++i) {
2979 sp<Track> track = mTracks[i];
2980 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07002981 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002982 chain->decTrackCnt();
2983 }
2984 }
2985 break;
2986 }
2987 }
2988 return mEffectChains.size();
2989}
2990
2991status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002992 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002993{
2994 Mutex::Autolock _l(mLock);
2995 return attachAuxEffect_l(track, EffectId);
2996}
2997
2998status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002999 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003000{
3001 status_t status = NO_ERROR;
3002
3003 if (EffectId == 0) {
3004 track->setAuxBuffer(0, NULL);
3005 } else {
3006 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3007 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3008 if (effect != 0) {
3009 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3010 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3011 } else {
3012 status = INVALID_OPERATION;
3013 }
3014 } else {
3015 status = BAD_VALUE;
3016 }
3017 }
3018 return status;
3019}
3020
3021void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3022{
3023 for (size_t i = 0; i < mTracks.size(); ++i) {
3024 sp<Track> track = mTracks[i];
3025 if (track->auxEffectId() == effectId) {
3026 attachAuxEffect_l(track, 0);
3027 }
3028 }
3029}
3030
3031bool AudioFlinger::PlaybackThread::threadLoop()
3032{
Glenn Kasten388d5712017-04-07 14:38:41 -07003033 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003034
Eric Laurent81784c32012-11-19 14:55:58 -08003035 Vector< sp<Track> > tracksToRemove;
3036
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003037 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003038 nsecs_t lastWriteFinished = -1; // time last server write completed
3039 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003040
3041 // MIXER
3042 nsecs_t lastWarning = 0;
3043
3044 // DUPLICATING
3045 // FIXME could this be made local to while loop?
3046 writeFrames = 0;
3047
3048 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003049 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003050
3051 if (mType == MIXER) {
3052 sleepTimeShift = 0;
3053 }
3054
3055 CpuStats cpuStats;
3056 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3057
3058 acquireWakeLock();
3059
Glenn Kasteneef598c2017-04-03 14:41:13 -07003060 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3061 // thread associated with this PlaybackThread.
3062 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3063 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003064 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3065 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003066 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003067 const char *logString = NULL;
3068
rago1bb90822017-05-02 18:31:48 -07003069 // Estimated time for next buffer to be written to hal. This is used only on
3070 // suspended mode (for now) to help schedule the wait time until next iteration.
3071 nsecs_t timeLoopNextNs = 0;
3072
Eric Laurent664539d2013-09-23 18:24:31 -07003073 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003074
Eric Laurent81784c32012-11-19 14:55:58 -08003075 while (!exitPending())
3076 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003077 // Log merge requests are performed during AudioFlinger binder transactions, but
3078 // that does not cover audio playback. It's requested here for that reason.
3079 mAudioFlinger->requestLogMerge();
3080
Eric Laurent81784c32012-11-19 14:55:58 -08003081 cpuStats.sample(myName);
3082
3083 Vector< sp<EffectChain> > effectChains;
3084
Eric Laurent81784c32012-11-19 14:55:58 -08003085 { // scope for mLock
3086
3087 Mutex::Autolock _l(mLock);
3088
Eric Laurent021cf962014-05-13 10:18:14 -07003089 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003090
Glenn Kasteneef598c2017-04-03 14:41:13 -07003091 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003092 if (logString != NULL) {
3093 mNBLogWriter->logTimestamp();
3094 mNBLogWriter->log(logString);
3095 logString = NULL;
3096 }
3097
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003098 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003099 // and associate with the sink frames written out. We need
3100 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003101 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003102 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003103 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003104 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003105 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003106 ExtendedTimestamp timestamp; // use private copy to fetch
3107 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003108
3109 // We keep track of the last valid kernel position in case we are in underrun
3110 // and the normal mixer period is the same as the fast mixer period, or there
3111 // is some error from the HAL.
3112 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3113 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3114 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3115 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3116 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3117
3118 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3119 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3120 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3121 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003122 }
3123
3124 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3125 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003126 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003127 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003128 }
3129
Andy Hung818e7a32016-02-16 18:08:07 -08003130 // copy over kernel info
3131 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003132 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3133 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003134 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3135 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003136 }
3137 // mFramesWritten for non-offloaded tracks are contiguous
3138 // even after standby() is called. This is useful for the track frame
3139 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003140 bool serverLocationUpdate = false;
3141 if (mFramesWritten != lastFramesWritten) {
3142 serverLocationUpdate = true;
3143 lastFramesWritten = mFramesWritten;
3144 }
3145 // Only update timestamps if there is a meaningful change.
3146 // Either the kernel timestamp must be valid or we have written something.
3147 if (kernelLocationUpdate || serverLocationUpdate) {
3148 if (serverLocationUpdate) {
3149 // use the time before we called the HAL write - it is a bit more accurate
3150 // to when the server last read data than the current time here.
3151 //
3152 // If we haven't written anything, mLastWriteTime will be -1
3153 // and we use systemTime().
3154 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3155 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3156 ? systemTime() : mLastWriteTime;
3157 }
Andy Hungdae27702016-10-31 14:01:16 -07003158
3159 for (const sp<Track> &t : mActiveTracks) {
3160 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003161 t->updateTrackFrameInfo(
3162 t->mAudioTrackServerProxy->framesReleased(),
3163 mFramesWritten,
3164 mTimestamp);
3165 }
Andy Hunge10393e2015-06-12 13:59:33 -07003166 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003167 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003168#if 0
3169 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003170 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003171 timespec ts;
3172 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003173 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003174 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003175 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003176 }
3177 ++z;
3178#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003179 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003180 if (mSignalPending) {
3181 // A signal was raised while we were unlocked
3182 mSignalPending = false;
3183 } else if (waitingAsyncCallback_l()) {
3184 if (exitPending()) {
3185 break;
3186 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003187 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003188 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003189 releaseWakeLock_l();
3190 released = true;
3191 }
Andy Hung10cbff12017-02-21 17:30:14 -08003192
3193 const int64_t waitNs = computeWaitTimeNs_l();
3194 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3195 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3196 if (status == TIMED_OUT) {
3197 mSignalPending = true; // if timeout recheck everything
3198 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003199 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003200 if (released) {
3201 acquireWakeLock_l();
3202 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003203 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3204 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003205
3206 continue;
3207 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003208 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 isSuspended()) {
3210 // put audio hardware into standby after short delay
3211 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003212
3213 threadLoop_standby();
3214
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003215 // This is where we go into standby
3216 if (!mStandby) {
3217 LOG_AUDIO_STATE();
3218 }
Eric Laurent81784c32012-11-19 14:55:58 -08003219 mStandby = true;
3220 }
3221
3222 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3223 // we're about to wait, flush the binder command buffer
3224 IPCThreadState::self()->flushCommands();
3225
3226 clearOutputTracks();
3227
3228 if (exitPending()) {
3229 break;
3230 }
3231
3232 releaseWakeLock_l();
3233 // wait until we have something to do...
3234 ALOGV("%s going to sleep", myName.string());
3235 mWaitWorkCV.wait(mLock);
3236 ALOGV("%s waking up", myName.string());
3237 acquireWakeLock_l();
3238
3239 mMixerStatus = MIXER_IDLE;
3240 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3241 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003242 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003243 checkSilentMode_l();
3244
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003245 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3246 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003247 if (mType == MIXER) {
3248 sleepTimeShift = 0;
3249 }
3250
3251 continue;
3252 }
3253 }
Eric Laurent81784c32012-11-19 14:55:58 -08003254 // mMixerStatusIgnoringFastTracks is also updated internally
3255 mMixerStatus = prepareTracks_l(&tracksToRemove);
3256
Andy Hungdae27702016-10-31 14:01:16 -07003257 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003258
Eric Laurent81784c32012-11-19 14:55:58 -08003259 // prevent any changes in effect chain list and in each effect chain
3260 // during mixing and effect process as the audio buffers could be deleted
3261 // or modified if an effect is created or deleted
3262 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003263 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003264
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265 if (mBytesRemaining == 0) {
3266 mCurrentWriteLength = 0;
3267 if (mMixerStatus == MIXER_TRACKS_READY) {
3268 // threadLoop_mix() sets mCurrentWriteLength
3269 threadLoop_mix();
3270 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3271 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003272 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 // must be written to HAL
3274 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003275 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003276 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003277 }
3278 }
Andy Hung98ef9782014-03-04 14:46:50 -08003279 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003280 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003281 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3282 // or mSinkBuffer (if there are no effects).
3283 //
3284 // This is done pre-effects computation; if effects change to
3285 // support higher precision, this needs to move.
3286 //
3287 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003288 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003289 if (mMixerBufferValid) {
3290 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3291 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3292
Andy Hung2ddee192015-12-18 17:34:44 -08003293 // mono blend occurs for mixer threads only (not direct or offloaded)
3294 // and is handled here if we're going directly to the sink.
3295 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003296 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3297 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003298 }
3299
Andy Hung98ef9782014-03-04 14:46:50 -08003300 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3301 mNormalFrameCount * mChannelCount);
3302 }
3303
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 mBytesRemaining = mCurrentWriteLength;
3305 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003306 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3307 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3308 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3309 mBytesWritten += mBytesRemaining;
3310 mFramesWritten += framesRemaining;
3311 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003312 mBytesRemaining = 0;
3313 }
Eric Laurent81784c32012-11-19 14:55:58 -08003314
Eric Laurentbfb1b832013-01-07 09:53:42 -08003315 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003316 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003317 for (size_t i = 0; i < effectChains.size(); i ++) {
3318 effectChains[i]->process_l();
3319 }
Eric Laurent81784c32012-11-19 14:55:58 -08003320 }
3321 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003322 // Process effect chains for offloaded thread even if no audio
3323 // was read from audio track: process only updates effect state
3324 // and thus does have to be synchronized with audio writes but may have
3325 // to be called while waiting for async write callback
3326 if (mType == OFFLOAD) {
3327 for (size_t i = 0; i < effectChains.size(); i ++) {
3328 effectChains[i]->process_l();
3329 }
3330 }
Eric Laurent81784c32012-11-19 14:55:58 -08003331
Andy Hung98ef9782014-03-04 14:46:50 -08003332 // Only if the Effects buffer is enabled and there is data in the
3333 // Effects buffer (buffer valid), we need to
3334 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003335 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003336 if (mEffectBufferValid) {
3337 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003338
3339 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003340 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3341 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003342 }
3343
Andy Hung98ef9782014-03-04 14:46:50 -08003344 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3345 mNormalFrameCount * mChannelCount);
3346 }
3347
Eric Laurent81784c32012-11-19 14:55:58 -08003348 // enable changes in effect chain
3349 unlockEffectChains(effectChains);
3350
Eric Laurentbfb1b832013-01-07 09:53:42 -08003351 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003352 // mSleepTimeUs == 0 means we must write to audio hardware
3353 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003354 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003355 // We save lastWriteFinished here, as previousLastWriteFinished,
3356 // for throttling. On thread start, previousLastWriteFinished will be
3357 // set to -1, which properly results in no throttling after the first write.
3358 nsecs_t previousLastWriteFinished = lastWriteFinished;
3359 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003360 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003361 // FIXME rewrite to reduce number of system calls
3362 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003363 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003364 lastWriteFinished = systemTime();
3365 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003366 if (ret < 0) {
3367 mBytesRemaining = 0;
3368 } else {
3369 mBytesWritten += ret;
3370 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003371 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003372 }
3373 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3374 (mMixerStatus == MIXER_DRAIN_ALL)) {
3375 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003376 }
Andy Hung08fb1742015-05-31 23:22:10 -07003377 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003378 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003379 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003380 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003381 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003382 ATRACE_NAME("underrun");
3383 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003384 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003385 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003386 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003387 }
Andy Hung08fb1742015-05-31 23:22:10 -07003388
3389 if (mThreadThrottle
3390 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3391 && ret > 0) { // we wrote something
3392 // Limit MixerThread data processing to no more than twice the
3393 // expected processing rate.
3394 //
3395 // This helps prevent underruns with NuPlayer and other applications
3396 // which may set up buffers that are close to the minimum size, or use
3397 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3398 //
3399 // The throttle smooths out sudden large data drains from the device,
3400 // e.g. when it comes out of standby, which often causes problems with
3401 // (1) mixer threads without a fast mixer (which has its own warm-up)
3402 // (2) minimum buffer sized tracks (even if the track is full,
3403 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003404 //
3405 // Total time spent in last processing cycle equals time spent in
3406 // 1. threadLoop_write, as well as time spent in
3407 // 2. threadLoop_mix (significant for heavy mixing, especially
3408 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003409
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003410 // it's OK if deltaMs (and deltaNs) is an overestimate.
3411 nsecs_t deltaNs;
3412 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3413 __builtin_sub_overflow(
3414 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3415 const int32_t deltaMs = deltaNs / 1000000;
3416
Ivan Lozanoea04d392017-11-07 14:37:07 -08003417 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003418 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3419 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003420 // notify of throttle start on verbose log
3421 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3422 "mixer(%p) throttle begin:"
3423 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003424 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003425 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003426 // Throttle must be attributed to the previous mixer loop's write time
3427 // to allow back-to-back throttling.
3428 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003429 } else {
3430 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3431 if (diff > 0) {
3432 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003433 // but prevent spamming for bluetooth
3434 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3435 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003436 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3437 }
Andy Hung08fb1742015-05-31 23:22:10 -07003438 }
3439 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003440 }
Eric Laurent81784c32012-11-19 14:55:58 -08003441
Eric Laurentbfb1b832013-01-07 09:53:42 -08003442 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003443 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003444 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003445 // suspended requires accurate metering of sleep time.
3446 if (isSuspended()) {
3447 // advance by expected sleepTime
3448 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3449 const nsecs_t nowNs = systemTime();
3450
3451 // compute expected next time vs current time.
3452 // (negative deltas are treated as delays).
3453 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3454 if (deltaNs < -kMaxNextBufferDelayNs) {
3455 // Delays longer than the max allowed trigger a reset.
3456 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3457 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3458 timeLoopNextNs = nowNs + deltaNs;
3459 } else if (deltaNs < 0) {
3460 // Delays within the max delay allowed: zero the delta/sleepTime
3461 // to help the system catch up in the next iteration(s)
3462 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3463 deltaNs = 0;
3464 }
3465 // update sleep time (which is >= 0)
3466 mSleepTimeUs = deltaNs / 1000;
3467 }
Eric Laurente93cc032016-05-05 10:15:10 -07003468 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3469 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003470 }
Glenn Kastene7754022014-10-31 12:11:26 -07003471 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472 }
Eric Laurent81784c32012-11-19 14:55:58 -08003473 }
3474
3475 // Finally let go of removed track(s), without the lock held
3476 // since we can't guarantee the destructors won't acquire that
3477 // same lock. This will also mutate and push a new fast mixer state.
3478 threadLoop_removeTracks(tracksToRemove);
3479 tracksToRemove.clear();
3480
3481 // FIXME I don't understand the need for this here;
3482 // it was in the original code but maybe the
3483 // assignment in saveOutputTracks() makes this unnecessary?
3484 clearOutputTracks();
3485
3486 // Effect chains will be actually deleted here if they were removed from
3487 // mEffectChains list during mixing or effects processing
3488 effectChains.clear();
3489
3490 // FIXME Note that the above .clear() is no longer necessary since effectChains
3491 // is now local to this block, but will keep it for now (at least until merge done).
3492 }
3493
Eric Laurentbfb1b832013-01-07 09:53:42 -08003494 threadLoop_exit();
3495
Eric Laurentcf817a22014-08-04 20:36:31 -07003496 if (!mStandby) {
3497 threadLoop_standby();
3498 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003499 }
3500
3501 releaseWakeLock();
3502
3503 ALOGV("Thread %p type %d exiting", this, mType);
3504 return false;
3505}
3506
Eric Laurentbfb1b832013-01-07 09:53:42 -08003507// removeTracks_l() must be called with ThreadBase::mLock held
3508void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3509{
3510 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003511 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 for (size_t i=0 ; i<count ; i++) {
3513 const sp<Track>& track = tracksToRemove.itemAt(i);
3514 mActiveTracks.remove(track);
3515 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3516 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3517 if (chain != 0) {
3518 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3519 track->sessionId());
3520 chain->decActiveTrackCnt();
3521 }
3522 if (track->isTerminated()) {
3523 removeTrack_l(track);
3524 }
3525 }
3526 }
3527
3528}
Eric Laurent81784c32012-11-19 14:55:58 -08003529
Eric Laurentaccc1472013-09-20 09:36:34 -07003530status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3531{
3532 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003533 ExtendedTimestamp ets;
3534 status_t status = mNormalSink->getTimestamp(ets);
3535 if (status == NO_ERROR) {
3536 status = ets.getBestTimestamp(&timestamp);
3537 }
3538 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003539 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003540 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003541 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003542 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003543 timestamp.mPosition = (uint32_t)position64;
3544 return NO_ERROR;
3545 }
3546 }
3547 return INVALID_OPERATION;
3548}
Eric Laurent1c333e22014-05-20 10:48:17 -07003549
Eric Laurent054d9d32015-04-24 08:48:48 -07003550status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3551 audio_patch_handle_t *handle)
3552{
Andy Hungf60abce2016-08-26 11:37:54 -07003553 status_t status;
3554 if (property_get_bool("af.patch_park", false /* default_value */)) {
3555 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3556 // or if HAL does not properly lock against access.
3557 AutoPark<FastMixer> park(mFastMixer);
3558 status = PlaybackThread::createAudioPatch_l(patch, handle);
3559 } else {
3560 status = PlaybackThread::createAudioPatch_l(patch, handle);
3561 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003562 return status;
3563}
3564
Eric Laurent1c333e22014-05-20 10:48:17 -07003565status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3566 audio_patch_handle_t *handle)
3567{
3568 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003569
3570 // store new device and send to effects
3571 audio_devices_t type = AUDIO_DEVICE_NONE;
3572 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3573 type |= patch->sinks[i].ext.device.type;
3574 }
3575
3576#ifdef ADD_BATTERY_DATA
3577 // when changing the audio output device, call addBatteryData to notify
3578 // the change
3579 if (mOutDevice != type) {
3580 uint32_t params = 0;
3581 // check whether speaker is on
3582 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3583 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003584 }
3585
Eric Laurent054d9d32015-04-24 08:48:48 -07003586 audio_devices_t deviceWithoutSpeaker
3587 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3588 // check if any other device (except speaker) is on
3589 if (type & deviceWithoutSpeaker) {
3590 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3591 }
3592
3593 if (params != 0) {
3594 addBatteryData(params);
3595 }
3596 }
3597#endif
3598
3599 for (size_t i = 0; i < mEffectChains.size(); i++) {
3600 mEffectChains[i]->setDevice_l(type);
3601 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003602
3603 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3604 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3605 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003606 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003607 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003608
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003609 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003610 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3611 status = hwDevice->createAudioPatch(patch->num_sources,
3612 patch->sources,
3613 patch->num_sinks,
3614 patch->sinks,
3615 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003616 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003617 char *address;
3618 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3619 //FIXME: we only support address on first sink with HAL version < 3.0
3620 address = audio_device_address_to_parameter(
3621 patch->sinks[0].ext.device.type,
3622 patch->sinks[0].ext.device.address);
3623 } else {
3624 address = (char *)calloc(1, 1);
3625 }
3626 AudioParameter param = AudioParameter(String8(address));
3627 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003628 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003629 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003630 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003631 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003632 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003633 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003634 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3635 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003636 return status;
3637}
3638
Eric Laurent054d9d32015-04-24 08:48:48 -07003639status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3640{
Andy Hungf60abce2016-08-26 11:37:54 -07003641 status_t status;
3642 if (property_get_bool("af.patch_park", false /* default_value */)) {
3643 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3644 // or if HAL does not properly lock against access.
3645 AutoPark<FastMixer> park(mFastMixer);
3646 status = PlaybackThread::releaseAudioPatch_l(handle);
3647 } else {
3648 status = PlaybackThread::releaseAudioPatch_l(handle);
3649 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003650 return status;
3651}
3652
Eric Laurent1c333e22014-05-20 10:48:17 -07003653status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3654{
3655 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003656
3657 mOutDevice = AUDIO_DEVICE_NONE;
3658
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003659 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003660 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3661 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003662 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003663 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003664 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003665 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003666 }
3667 return status;
3668}
3669
Eric Laurent83b88082014-06-20 18:31:16 -07003670void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3671{
3672 Mutex::Autolock _l(mLock);
3673 mTracks.add(track);
3674}
3675
3676void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3677{
3678 Mutex::Autolock _l(mLock);
3679 destroyTrack_l(track);
3680}
3681
3682void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3683{
3684 ThreadBase::getAudioPortConfig(config);
3685 config->role = AUDIO_PORT_ROLE_SOURCE;
3686 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3687 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3688}
3689
Eric Laurent81784c32012-11-19 14:55:58 -08003690// ----------------------------------------------------------------------------
3691
3692AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003693 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3694 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // mAudioMixer below
3696 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003697 mFastMixerFutex(0),
3698 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003699 // mOutputSink below
3700 // mPipeSink below
3701 // mNormalSink below
3702{
3703 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003704 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003705 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003706 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3707 mNormalFrameCount);
3708 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3709
Andy Hungfbfc3952015-01-15 13:33:51 -08003710 if (type == DUPLICATING) {
3711 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3712 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3713 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3714 return;
3715 }
Eric Laurent81784c32012-11-19 14:55:58 -08003716 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003717 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003718 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003719 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003720#if !LOG_NDEBUG
3721 ssize_t index =
3722#else
3723 (void)
3724#endif
3725 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003726 ALOG_ASSERT(index == 0);
3727
3728 // initialize fast mixer depending on configuration
3729 bool initFastMixer;
3730 switch (kUseFastMixer) {
3731 case FastMixer_Never:
3732 initFastMixer = false;
3733 break;
3734 case FastMixer_Always:
3735 initFastMixer = true;
3736 break;
3737 case FastMixer_Static:
3738 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003739 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3740 // where the period is less than an experimentally determined threshold that can be
3741 // scheduled reliably with CFS. However, the BT A2DP HAL is
3742 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3743 initFastMixer = mFrameCount < mNormalFrameCount
3744 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003745 break;
3746 }
Andy Hungfda69402017-02-15 14:33:12 -08003747 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3748 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3749 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003750 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003751 audio_format_t fastMixerFormat;
3752 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3753 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3754 } else {
3755 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3756 }
3757 if (mFormat != fastMixerFormat) {
3758 // change our Sink format to accept our intermediate precision
3759 mFormat = fastMixerFormat;
3760 free(mSinkBuffer);
3761 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3762 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3763 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3764 }
Eric Laurent81784c32012-11-19 14:55:58 -08003765
3766 // create a MonoPipe to connect our submix to FastMixer
3767 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003768#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003769 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003770#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003771 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003772 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003773 format.mFormat = fastMixerFormat;
3774 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3775
Eric Laurent81784c32012-11-19 14:55:58 -08003776 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3777 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3778 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3779 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3780 const NBAIO_Format offers[1] = {format};
3781 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003782#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003783 ssize_t index =
3784#else
3785 (void)
3786#endif
3787 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003788 ALOG_ASSERT(index == 0);
3789 monoPipe->setAvgFrames((mScreenState & 1) ?
3790 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3791 mPipeSink = monoPipe;
3792
Glenn Kasten46909e72013-02-26 09:20:22 -08003793#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003794 if (mTeeSinkOutputEnabled) {
3795 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003796 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3797 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003798 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003799 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003800 ALOG_ASSERT(index == 0);
3801 mTeeSink = teeSink;
3802 PipeReader *teeSource = new PipeReader(*teeSink);
3803 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003804 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003805 ALOG_ASSERT(index == 0);
3806 mTeeSource = teeSource;
3807 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003808#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003809
3810 // create fast mixer and configure it initially with just one fast track for our submix
3811 mFastMixer = new FastMixer();
3812 FastMixerStateQueue *sq = mFastMixer->sq();
3813#ifdef STATE_QUEUE_DUMP
3814 sq->setObserverDump(&mStateQueueObserverDump);
3815 sq->setMutatorDump(&mStateQueueMutatorDump);
3816#endif
3817 FastMixerState *state = sq->begin();
3818 FastTrack *fastTrack = &state->mFastTracks[0];
3819 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3820 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3821 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003822 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3823 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003824 fastTrack->mGeneration++;
3825 state->mFastTracksGen++;
3826 state->mTrackMask = 1;
3827 // fast mixer will use the HAL output sink
3828 state->mOutputSink = mOutputSink.get();
3829 state->mOutputSinkGen++;
3830 state->mFrameCount = mFrameCount;
3831 state->mCommand = FastMixerState::COLD_IDLE;
3832 // already done in constructor initialization list
3833 //mFastMixerFutex = 0;
3834 state->mColdFutexAddr = &mFastMixerFutex;
3835 state->mColdGen++;
3836 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003837#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003838 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003839#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003840 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3841 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003842 sq->end();
3843 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3844
3845 // start the fast mixer
3846 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3847 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003848 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003849 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003850
3851#ifdef AUDIO_WATCHDOG
3852 // create and start the watchdog
3853 mAudioWatchdog = new AudioWatchdog();
3854 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3855 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3856 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003857 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003858#endif
3859
Eric Laurent81784c32012-11-19 14:55:58 -08003860 }
3861
3862 switch (kUseFastMixer) {
3863 case FastMixer_Never:
3864 case FastMixer_Dynamic:
3865 mNormalSink = mOutputSink;
3866 break;
3867 case FastMixer_Always:
3868 mNormalSink = mPipeSink;
3869 break;
3870 case FastMixer_Static:
3871 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3872 break;
3873 }
3874}
3875
3876AudioFlinger::MixerThread::~MixerThread()
3877{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003878 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003879 FastMixerStateQueue *sq = mFastMixer->sq();
3880 FastMixerState *state = sq->begin();
3881 if (state->mCommand == FastMixerState::COLD_IDLE) {
3882 int32_t old = android_atomic_inc(&mFastMixerFutex);
3883 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003884 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003885 }
3886 }
3887 state->mCommand = FastMixerState::EXIT;
3888 sq->end();
3889 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3890 mFastMixer->join();
3891 // Though the fast mixer thread has exited, it's state queue is still valid.
3892 // We'll use that extract the final state which contains one remaining fast track
3893 // corresponding to our sub-mix.
3894 state = sq->begin();
3895 ALOG_ASSERT(state->mTrackMask == 1);
3896 FastTrack *fastTrack = &state->mFastTracks[0];
3897 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3898 delete fastTrack->mBufferProvider;
3899 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003900 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003901#ifdef AUDIO_WATCHDOG
3902 if (mAudioWatchdog != 0) {
3903 mAudioWatchdog->requestExit();
3904 mAudioWatchdog->requestExitAndWait();
3905 mAudioWatchdog.clear();
3906 }
3907#endif
3908 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003909 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003910 delete mAudioMixer;
3911}
3912
3913
3914uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3915{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003916 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003917 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3918 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3919 }
3920 return latency;
3921}
3922
3923
3924void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3925{
3926 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3927}
3928
Eric Laurentbfb1b832013-01-07 09:53:42 -08003929ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003930{
3931 // FIXME we should only do one push per cycle; confirm this is true
3932 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003933 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003934 FastMixerStateQueue *sq = mFastMixer->sq();
3935 FastMixerState *state = sq->begin();
3936 if (state->mCommand != FastMixerState::MIX_WRITE &&
3937 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3938 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003939
3940 // FIXME workaround for first HAL write being CPU bound on some devices
3941 ATRACE_BEGIN("write");
3942 mOutput->write((char *)mSinkBuffer, 0);
3943 ATRACE_END();
3944
Eric Laurent81784c32012-11-19 14:55:58 -08003945 int32_t old = android_atomic_inc(&mFastMixerFutex);
3946 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003947 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003948 }
3949#ifdef AUDIO_WATCHDOG
3950 if (mAudioWatchdog != 0) {
3951 mAudioWatchdog->resume();
3952 }
3953#endif
3954 }
3955 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003956#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003957 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003958 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003959#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003960 sq->end();
3961 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3962 if (kUseFastMixer == FastMixer_Dynamic) {
3963 mNormalSink = mPipeSink;
3964 }
3965 } else {
3966 sq->end(false /*didModify*/);
3967 }
3968 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003969 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003970}
3971
3972void AudioFlinger::MixerThread::threadLoop_standby()
3973{
3974 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003975 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003976 FastMixerStateQueue *sq = mFastMixer->sq();
3977 FastMixerState *state = sq->begin();
3978 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003979 // Report any frames trapped in the Monopipe
3980 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3981 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3982 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3983 "monoPipeWritten:%lld monoPipeLeft:%lld",
3984 (long long)mFramesWritten, (long long)mSuspendedFrames,
3985 (long long)mPipeSink->framesWritten(), pipeFrames);
3986 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3987
Eric Laurent81784c32012-11-19 14:55:58 -08003988 state->mCommand = FastMixerState::COLD_IDLE;
3989 state->mColdFutexAddr = &mFastMixerFutex;
3990 state->mColdGen++;
3991 mFastMixerFutex = 0;
3992 sq->end();
3993 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3994 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3995 if (kUseFastMixer == FastMixer_Dynamic) {
3996 mNormalSink = mOutputSink;
3997 }
3998#ifdef AUDIO_WATCHDOG
3999 if (mAudioWatchdog != 0) {
4000 mAudioWatchdog->pause();
4001 }
4002#endif
4003 } else {
4004 sq->end(false /*didModify*/);
4005 }
4006 }
4007 PlaybackThread::threadLoop_standby();
4008}
4009
Eric Laurentbfb1b832013-01-07 09:53:42 -08004010bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4011{
4012 return false;
4013}
4014
4015bool AudioFlinger::PlaybackThread::shouldStandby_l()
4016{
4017 return !mStandby;
4018}
4019
4020bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4021{
4022 Mutex::Autolock _l(mLock);
4023 return waitingAsyncCallback_l();
4024}
4025
Eric Laurent81784c32012-11-19 14:55:58 -08004026// shared by MIXER and DIRECT, overridden by DUPLICATING
4027void AudioFlinger::PlaybackThread::threadLoop_standby()
4028{
4029 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004030 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004032 // discard any pending drain or write ack by incrementing sequence
4033 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4034 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004035 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004036 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4037 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004038 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004039 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004040}
4041
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004042void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4043{
4044 ALOGV("signal playback thread");
4045 broadcast_l();
4046}
4047
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004048void AudioFlinger::PlaybackThread::onAsyncError()
4049{
4050 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4051 invalidateTracks((audio_stream_type_t)i);
4052 }
4053}
4054
Eric Laurent81784c32012-11-19 14:55:58 -08004055void AudioFlinger::MixerThread::threadLoop_mix()
4056{
Eric Laurent81784c32012-11-19 14:55:58 -08004057 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004058 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004059 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004060 // increase sleep time progressively when application underrun condition clears.
4061 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4062 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4063 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004064 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004065 sleepTimeShift--;
4066 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004067 mSleepTimeUs = 0;
4068 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004069 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004070
Eric Laurent81784c32012-11-19 14:55:58 -08004071}
4072
4073void AudioFlinger::MixerThread::threadLoop_sleepTime()
4074{
4075 // If no tracks are ready, sleep once for the duration of an output
4076 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004077 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004078 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004079 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4080 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4081 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004082 }
4083 // reduce sleep time in case of consecutive application underruns to avoid
4084 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4085 // duration we would end up writing less data than needed by the audio HAL if
4086 // the condition persists.
4087 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4088 sleepTimeShift++;
4089 }
4090 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004091 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004092 }
4093 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004094 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4095 // before effects processing or output.
4096 if (mMixerBufferValid) {
4097 memset(mMixerBuffer, 0, mMixerBufferSize);
4098 } else {
4099 memset(mSinkBuffer, 0, mSinkBufferSize);
4100 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004101 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004102 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4103 "anticipated start");
4104 }
4105 // TODO add standby time extension fct of effect tail
4106}
4107
4108// prepareTracks_l() must be called with ThreadBase::mLock held
4109AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4110 Vector< sp<Track> > *tracksToRemove)
4111{
4112
4113 mixer_state mixerStatus = MIXER_IDLE;
4114 // find out which tracks need to be processed
4115 size_t count = mActiveTracks.size();
4116 size_t mixedTracks = 0;
4117 size_t tracksWithEffect = 0;
4118 // counts only _active_ fast tracks
4119 size_t fastTracks = 0;
4120 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4121
4122 float masterVolume = mMasterVolume;
4123 bool masterMute = mMasterMute;
4124
4125 if (masterMute) {
4126 masterVolume = 0;
4127 }
4128 // Delegate master volume control to effect in output mix effect chain if needed
4129 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4130 if (chain != 0) {
4131 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4132 chain->setVolume_l(&v, &v);
4133 masterVolume = (float)((v + (1 << 23)) >> 24);
4134 chain.clear();
4135 }
4136
4137 // prepare a new state to push
4138 FastMixerStateQueue *sq = NULL;
4139 FastMixerState *state = NULL;
4140 bool didModify = false;
4141 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004142 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004143 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004144 sq = mFastMixer->sq();
4145 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004146 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004147 }
4148
Andy Hung69aed5f2014-02-25 17:24:40 -08004149 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004150 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004151
Eric Laurent81784c32012-11-19 14:55:58 -08004152 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004153 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004154
4155 // this const just means the local variable doesn't change
4156 Track* const track = t.get();
4157
4158 // process fast tracks
4159 if (track->isFastTrack()) {
4160
4161 // It's theoretically possible (though unlikely) for a fast track to be created
4162 // and then removed within the same normal mix cycle. This is not a problem, as
4163 // the track never becomes active so it's fast mixer slot is never touched.
4164 // The converse, of removing an (active) track and then creating a new track
4165 // at the identical fast mixer slot within the same normal mix cycle,
4166 // is impossible because the slot isn't marked available until the end of each cycle.
4167 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004168 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004169 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4170 FastTrack *fastTrack = &state->mFastTracks[j];
4171
4172 // Determine whether the track is currently in underrun condition,
4173 // and whether it had a recent underrun.
4174 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4175 FastTrackUnderruns underruns = ftDump->mUnderruns;
4176 uint32_t recentFull = (underruns.mBitFields.mFull -
4177 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4178 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4179 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4180 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4181 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4182 uint32_t recentUnderruns = recentPartial + recentEmpty;
4183 track->mObservedUnderruns = underruns;
4184 // don't count underruns that occur while stopping or pausing
4185 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004186 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4187 recentUnderruns > 0) {
4188 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4189 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004190 } else {
4191 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004192 }
4193
4194 // This is similar to the state machine for normal tracks,
4195 // with a few modifications for fast tracks.
4196 bool isActive = true;
4197 switch (track->mState) {
4198 case TrackBase::STOPPING_1:
4199 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004200 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004201 track->mState = TrackBase::STOPPING_2;
4202 }
4203 break;
4204 case TrackBase::PAUSING:
4205 // ramp down is not yet implemented
4206 track->setPaused();
4207 break;
4208 case TrackBase::RESUMING:
4209 // ramp up is not yet implemented
4210 track->mState = TrackBase::ACTIVE;
4211 break;
4212 case TrackBase::ACTIVE:
4213 if (recentFull > 0 || recentPartial > 0) {
4214 // track has provided at least some frames recently: reset retry count
4215 track->mRetryCount = kMaxTrackRetries;
4216 }
4217 if (recentUnderruns == 0) {
4218 // no recent underruns: stay active
4219 break;
4220 }
4221 // there has recently been an underrun of some kind
4222 if (track->sharedBuffer() == 0) {
4223 // were any of the recent underruns "empty" (no frames available)?
4224 if (recentEmpty == 0) {
4225 // no, then ignore the partial underruns as they are allowed indefinitely
4226 break;
4227 }
4228 // there has recently been an "empty" underrun: decrement the retry counter
4229 if (--(track->mRetryCount) > 0) {
4230 break;
4231 }
4232 // indicate to client process that the track was disabled because of underrun;
4233 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004234 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004235 // remove from active list, but state remains ACTIVE [confusing but true]
4236 isActive = false;
4237 break;
4238 }
4239 // fall through
4240 case TrackBase::STOPPING_2:
4241 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004242 case TrackBase::STOPPED:
4243 case TrackBase::FLUSHED: // flush() while active
4244 // Check for presentation complete if track is inactive
4245 // We have consumed all the buffers of this track.
4246 // This would be incomplete if we auto-paused on underrun
4247 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004248 uint32_t latency = 0;
4249 status_t result = mOutput->stream->getLatency(&latency);
4250 ALOGE_IF(result != OK,
4251 "Error when retrieving output stream latency: %d", result);
4252 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004253 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004254 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4255 // track stays in active list until presentation is complete
4256 break;
4257 }
4258 }
4259 if (track->isStopping_2()) {
4260 track->mState = TrackBase::STOPPED;
4261 }
4262 if (track->isStopped()) {
4263 // Can't reset directly, as fast mixer is still polling this track
4264 // track->reset();
4265 // So instead mark this track as needing to be reset after push with ack
4266 resetMask |= 1 << i;
4267 }
4268 isActive = false;
4269 break;
4270 case TrackBase::IDLE:
4271 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004272 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004273 }
4274
4275 if (isActive) {
4276 // was it previously inactive?
4277 if (!(state->mTrackMask & (1 << j))) {
4278 ExtendedAudioBufferProvider *eabp = track;
4279 VolumeProvider *vp = track;
4280 fastTrack->mBufferProvider = eabp;
4281 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004282 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004283 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004284 fastTrack->mGeneration++;
4285 state->mTrackMask |= 1 << j;
4286 didModify = true;
4287 // no acknowledgement required for newly active tracks
4288 }
4289 // cache the combined master volume and stream type volume for fast mixer; this
4290 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004291 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004292 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004293 track->mCachedVolume = masterVolume
4294 * mStreamTypes[track->streamType()].volume
4295 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004296 ++fastTracks;
4297 } else {
4298 // was it previously active?
4299 if (state->mTrackMask & (1 << j)) {
4300 fastTrack->mBufferProvider = NULL;
4301 fastTrack->mGeneration++;
4302 state->mTrackMask &= ~(1 << j);
4303 didModify = true;
4304 // If any fast tracks were removed, we must wait for acknowledgement
4305 // because we're about to decrement the last sp<> on those tracks.
4306 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4307 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004308 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4309 // AudioTrack may start (which may not be with a start() but with a write()
4310 // after underrun) and immediately paused or released. In that case the
4311 // FastTrack state hasn't had time to update.
4312 // TODO Remove the ALOGW when this theory is confirmed.
4313 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004314 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4315 j, track->mState, state->mTrackMask, recentUnderruns,
4316 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004317 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004318 }
4319 tracksToRemove->add(track);
4320 // Avoids a misleading display in dumpsys
4321 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4322 }
4323 continue;
4324 }
4325
4326 { // local variable scope to avoid goto warning
4327
4328 audio_track_cblk_t* cblk = track->cblk();
4329
4330 // The first time a track is added we wait
4331 // for all its buffers to be filled before processing it
4332 int name = track->name();
4333 // make sure that we have enough frames to mix one full buffer.
4334 // enforce this condition only once to enable draining the buffer in case the client
4335 // app does not call stop() and relies on underrun to stop:
4336 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4337 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004338 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004339 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004340 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004341
4342 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004343 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004344 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4345 // add frames already consumed but not yet released by the resampler
4346 // because mAudioTrackServerProxy->framesReady() will include these frames
4347 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4348
Eric Laurent81784c32012-11-19 14:55:58 -08004349 uint32_t minFrames = 1;
4350 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4351 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004352 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004353 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004354
4355 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004356 if (ATRACE_ENABLED()) {
4357 // I wish we had formatted trace names
4358 char traceName[16];
4359 strcpy(traceName, "nRdy");
4360 int name = track->name();
4361 if (AudioMixer::TRACK0 <= name &&
4362 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4363 name -= AudioMixer::TRACK0;
4364 traceName[4] = (name / 10) + '0';
4365 traceName[5] = (name % 10) + '0';
4366 } else {
4367 traceName[4] = '?';
4368 traceName[5] = '?';
4369 }
4370 traceName[6] = '\0';
4371 ATRACE_INT(traceName, framesReady);
4372 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004373 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004374 !track->isPaused() && !track->isTerminated())
4375 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004376 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004377
4378 mixedTracks++;
4379
Andy Hung69aed5f2014-02-25 17:24:40 -08004380 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4381 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004382 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004383 if (track->mainBuffer() != mSinkBuffer &&
4384 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004385 if (mEffectBufferEnabled) {
4386 mEffectBufferValid = true; // Later can set directly.
4387 }
Eric Laurent81784c32012-11-19 14:55:58 -08004388 chain = getEffectChain_l(track->sessionId());
4389 // Delegate volume control to effect in track effect chain if needed
4390 if (chain != 0) {
4391 tracksWithEffect++;
4392 } else {
4393 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4394 "session %d",
4395 name, track->sessionId());
4396 }
4397 }
4398
4399
4400 int param = AudioMixer::VOLUME;
4401 if (track->mFillingUpStatus == Track::FS_FILLED) {
4402 // no ramp for the first volume setting
4403 track->mFillingUpStatus = Track::FS_ACTIVE;
4404 if (track->mState == TrackBase::RESUMING) {
4405 track->mState = TrackBase::ACTIVE;
4406 param = AudioMixer::RAMP_VOLUME;
4407 }
4408 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004409 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004410 // FIXME should not make a decision based on mServer
4411 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004412 // If the track is stopped before the first frame was mixed,
4413 // do not apply ramp
4414 param = AudioMixer::RAMP_VOLUME;
4415 }
4416
4417 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004418 uint32_t vl, vr; // in U8.24 integer format
4419 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004420 // read original volumes with volume control
4421 float typeVolume = mStreamTypes[track->streamType()].volume;
4422 float v = masterVolume * typeVolume;
4423
Glenn Kastene4756fe2012-11-29 13:38:14 -08004424 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004425 vl = vr = 0;
4426 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004427 if (track->isPausing()) {
4428 track->setPaused();
4429 }
4430 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004431 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004432 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004433 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4434 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004435 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004436 if (vlf > GAIN_FLOAT_UNITY) {
4437 ALOGV("Track left volume out of range: %.3g", vlf);
4438 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004439 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004440 if (vrf > GAIN_FLOAT_UNITY) {
4441 ALOGV("Track right volume out of range: %.3g", vrf);
4442 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004443 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004444 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004445 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004446 // now apply the master volume and stream type volume and shaper volume
4447 vlf *= v * vh;
4448 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004449 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004450 // then derive vl and vr as U8.24 versions for the effect chain
4451 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4452 vl = (uint32_t) (scaleto8_24 * vlf);
4453 vr = (uint32_t) (scaleto8_24 * vrf);
4454 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004455 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004456 // send level comes from shared memory and so may be corrupt
4457 if (sendLevel > MAX_GAIN_INT) {
4458 ALOGV("Track send level out of range: %04X", sendLevel);
4459 sendLevel = MAX_GAIN_INT;
4460 }
Andy Hung6be49402014-05-30 10:42:03 -07004461 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4462 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004463 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004464
Eric Laurent81784c32012-11-19 14:55:58 -08004465 // Delegate volume control to effect in track effect chain if needed
4466 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4467 // Do not ramp volume if volume is controlled by effect
4468 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004469 // Update remaining floating point volume levels
4470 vlf = (float)vl / (1 << 24);
4471 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004472 track->mHasVolumeController = true;
4473 } else {
4474 // force no volume ramp when volume controller was just disabled or removed
4475 // from effect chain to avoid volume spike
4476 if (track->mHasVolumeController) {
4477 param = AudioMixer::VOLUME;
4478 }
4479 track->mHasVolumeController = false;
4480 }
4481
Eric Laurent7c29ec92017-09-20 17:54:22 -07004482 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4483 // still applied by the mixer.
4484 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4485 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4486 if (v != mLeftVolFloat) {
4487 status_t result = mOutput->stream->setVolume(v, v);
4488 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4489 if (result == OK) {
4490 mLeftVolFloat = v;
4491 }
4492 }
4493 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4494 // remove stream volume contribution from software volume.
4495 if (v != 0.0f && mLeftVolFloat == v) {
4496 vlf = min(1.0f, vlf / v);
4497 vrf = min(1.0f, vrf / v);
4498 vaf = min(1.0f, vaf / v);
4499 }
4500 }
Eric Laurent81784c32012-11-19 14:55:58 -08004501 // XXX: these things DON'T need to be done each time
4502 mAudioMixer->setBufferProvider(name, track);
4503 mAudioMixer->enable(name);
4504
Andy Hung6be49402014-05-30 10:42:03 -07004505 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4506 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4507 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004508 mAudioMixer->setParameter(
4509 name,
4510 AudioMixer::TRACK,
4511 AudioMixer::FORMAT, (void *)track->format());
4512 mAudioMixer->setParameter(
4513 name,
4514 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004515 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004516 mAudioMixer->setParameter(
4517 name,
4518 AudioMixer::TRACK,
4519 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004520 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004521 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004522 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004523 if (reqSampleRate == 0) {
4524 reqSampleRate = mSampleRate;
4525 } else if (reqSampleRate > maxSampleRate) {
4526 reqSampleRate = maxSampleRate;
4527 }
Eric Laurent81784c32012-11-19 14:55:58 -08004528 mAudioMixer->setParameter(
4529 name,
4530 AudioMixer::RESAMPLE,
4531 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004532 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004533
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004534 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004535 mAudioMixer->setParameter(
4536 name,
4537 AudioMixer::TIMESTRETCH,
4538 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004539 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004540
Andy Hung69aed5f2014-02-25 17:24:40 -08004541 /*
4542 * Select the appropriate output buffer for the track.
4543 *
Andy Hung98ef9782014-03-04 14:46:50 -08004544 * Tracks with effects go into their own effects chain buffer
4545 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004546 *
4547 * Other tracks can use mMixerBuffer for higher precision
4548 * channel accumulation. If this buffer is enabled
4549 * (mMixerBufferEnabled true), then selected tracks will accumulate
4550 * into it.
4551 *
4552 */
4553 if (mMixerBufferEnabled
4554 && (track->mainBuffer() == mSinkBuffer
4555 || track->mainBuffer() == mMixerBuffer)) {
4556 mAudioMixer->setParameter(
4557 name,
4558 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004559 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004560 mAudioMixer->setParameter(
4561 name,
4562 AudioMixer::TRACK,
4563 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4564 // TODO: override track->mainBuffer()?
4565 mMixerBufferValid = true;
4566 } else {
4567 mAudioMixer->setParameter(
4568 name,
4569 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004570 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004571 mAudioMixer->setParameter(
4572 name,
4573 AudioMixer::TRACK,
4574 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4575 }
Eric Laurent81784c32012-11-19 14:55:58 -08004576 mAudioMixer->setParameter(
4577 name,
4578 AudioMixer::TRACK,
4579 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4580
4581 // reset retry count
4582 track->mRetryCount = kMaxTrackRetries;
4583
4584 // If one track is ready, set the mixer ready if:
4585 // - the mixer was not ready during previous round OR
4586 // - no other track is not ready
4587 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4588 mixerStatus != MIXER_TRACKS_ENABLED) {
4589 mixerStatus = MIXER_TRACKS_READY;
4590 }
4591 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004592 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004593 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4594 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004595 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004596 } else {
4597 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004598 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004599
Eric Laurent81784c32012-11-19 14:55:58 -08004600 // clear effect chain input buffer if an active track underruns to avoid sending
4601 // previous audio buffer again to effects
4602 chain = getEffectChain_l(track->sessionId());
4603 if (chain != 0) {
4604 chain->clearInputBuffer();
4605 }
4606
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004607 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004608 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4609 track->isStopped() || track->isPaused()) {
4610 // We have consumed all the buffers of this track.
4611 // Remove it from the list of active tracks.
4612 // TODO: use actual buffer filling status instead of latency when available from
4613 // audio HAL
4614 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004615 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004616 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4617 if (track->isStopped()) {
4618 track->reset();
4619 }
4620 tracksToRemove->add(track);
4621 }
4622 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004623 // No buffers for this track. Give it a few chances to
4624 // fill a buffer, then remove it from active list.
4625 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004626 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004627 tracksToRemove->add(track);
4628 // indicate to client process that the track was disabled because of underrun;
4629 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004630 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004631 // If one track is not ready, mark the mixer also not ready if:
4632 // - the mixer was ready during previous round OR
4633 // - no other track is ready
4634 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4635 mixerStatus != MIXER_TRACKS_READY) {
4636 mixerStatus = MIXER_TRACKS_ENABLED;
4637 }
4638 }
4639 mAudioMixer->disable(name);
4640 }
4641
4642 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004643
4644 }
4645
4646 // Push the new FastMixer state if necessary
4647 bool pauseAudioWatchdog = false;
4648 if (didModify) {
4649 state->mFastTracksGen++;
4650 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4651 if (kUseFastMixer == FastMixer_Dynamic &&
4652 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4653 state->mCommand = FastMixerState::COLD_IDLE;
4654 state->mColdFutexAddr = &mFastMixerFutex;
4655 state->mColdGen++;
4656 mFastMixerFutex = 0;
4657 if (kUseFastMixer == FastMixer_Dynamic) {
4658 mNormalSink = mOutputSink;
4659 }
4660 // If we go into cold idle, need to wait for acknowledgement
4661 // so that fast mixer stops doing I/O.
4662 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4663 pauseAudioWatchdog = true;
4664 }
Eric Laurent81784c32012-11-19 14:55:58 -08004665 }
4666 if (sq != NULL) {
4667 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004668 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4669 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4670 // when bringing the output sink into standby.)
4671 //
4672 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4673 //
4674 // This occurs with BT suspend when we idle the FastMixer with
4675 // active tracks, which may be added or removed.
4676 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004677 }
4678#ifdef AUDIO_WATCHDOG
4679 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4680 mAudioWatchdog->pause();
4681 }
4682#endif
4683
4684 // Now perform the deferred reset on fast tracks that have stopped
4685 while (resetMask != 0) {
4686 size_t i = __builtin_ctz(resetMask);
4687 ALOG_ASSERT(i < count);
4688 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004689 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004690 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4691 track->reset();
4692 }
4693
4694 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004695 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004696
Eric Laurent97d547d2014-09-02 14:45:53 -07004697 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4698 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004699 }
4700
4701 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004702 // as long as there are effects we should clear the effects buffer, to avoid
4703 // passing a non-clean buffer to the effect chain
4704 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004705 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004706 // sink or mix buffer must be cleared if all tracks are connected to an
4707 // effect chain as in this case the mixer will not write to the sink or mix buffer
4708 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004709 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4710 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004711 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004712 if (mMixerBufferValid) {
4713 memset(mMixerBuffer, 0, mMixerBufferSize);
4714 // TODO: In testing, mSinkBuffer below need not be cleared because
4715 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4716 // after mixing.
4717 //
4718 // To enforce this guarantee:
4719 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4720 // (mixedTracks == 0 && fastTracks > 0))
4721 // must imply MIXER_TRACKS_READY.
4722 // Later, we may clear buffers regardless, and skip much of this logic.
4723 }
Andy Hung98ef9782014-03-04 14:46:50 -08004724 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004725 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004726 }
4727
4728 // if any fast tracks, then status is ready
4729 mMixerStatusIgnoringFastTracks = mixerStatus;
4730 if (fastTracks > 0) {
4731 mixerStatus = MIXER_TRACKS_READY;
4732 }
4733 return mixerStatus;
4734}
4735
Eric Laurentad7dd962016-09-22 12:38:37 -07004736// trackCountForUid_l() must be called with ThreadBase::mLock held
4737uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4738{
4739 uint32_t trackCount = 0;
4740 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004741 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004742 trackCount++;
4743 }
4744 }
4745 return trackCount;
4746}
4747
Eric Laurent81784c32012-11-19 14:55:58 -08004748// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004749int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004750 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004751{
Eric Laurentad7dd962016-09-22 12:38:37 -07004752 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4753 return -1;
4754 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004755 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004756}
4757
4758// deleteTrackName_l() must be called with ThreadBase::mLock held
4759void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4760{
4761 ALOGV("remove track (%d) and delete from mixer", name);
4762 mAudioMixer->deleteTrackName(name);
4763}
4764
Eric Laurent10351942014-05-08 18:49:52 -07004765// checkForNewParameter_l() must be called with ThreadBase::mLock held
4766bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4767 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004768{
Eric Laurent81784c32012-11-19 14:55:58 -08004769 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004770 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004771
Eric Laurent10351942014-05-08 18:49:52 -07004772 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004773
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004774 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004775
Eric Laurent10351942014-05-08 18:49:52 -07004776 AudioParameter param = AudioParameter(keyValuePair);
4777 int value;
4778 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4779 reconfig = true;
4780 }
4781 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004782 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004783 status = BAD_VALUE;
4784 } else {
4785 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004786 reconfig = true;
4787 }
Eric Laurent10351942014-05-08 18:49:52 -07004788 }
4789 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004790 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004791 status = BAD_VALUE;
4792 } else {
4793 // no need to save value, since it's constant
4794 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004795 }
Eric Laurent10351942014-05-08 18:49:52 -07004796 }
4797 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4798 // do not accept frame count changes if tracks are open as the track buffer
4799 // size depends on frame count and correct behavior would not be guaranteed
4800 // if frame count is changed after track creation
4801 if (!mTracks.isEmpty()) {
4802 status = INVALID_OPERATION;
4803 } else {
4804 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004805 }
Eric Laurent10351942014-05-08 18:49:52 -07004806 }
4807 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004808#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004809 // when changing the audio output device, call addBatteryData to notify
4810 // the change
4811 if (mOutDevice != value) {
4812 uint32_t params = 0;
4813 // check whether speaker is on
4814 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4815 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004816 }
Eric Laurent10351942014-05-08 18:49:52 -07004817
4818 audio_devices_t deviceWithoutSpeaker
4819 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4820 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004821 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004822 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4823 }
4824
4825 if (params != 0) {
4826 addBatteryData(params);
4827 }
4828 }
Eric Laurent81784c32012-11-19 14:55:58 -08004829#endif
4830
Eric Laurent10351942014-05-08 18:49:52 -07004831 // forward device change to effects that have requested to be
4832 // aware of attached audio device.
4833 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004834 a2dpDeviceChanged =
4835 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004836 mOutDevice = value;
4837 for (size_t i = 0; i < mEffectChains.size(); i++) {
4838 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004839 }
4840 }
Eric Laurent10351942014-05-08 18:49:52 -07004841 }
Eric Laurent81784c32012-11-19 14:55:58 -08004842
Eric Laurent10351942014-05-08 18:49:52 -07004843 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004844 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004845 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004846 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004847 mStandby = true;
4848 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004849 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004850 }
Eric Laurent10351942014-05-08 18:49:52 -07004851 if (status == NO_ERROR && reconfig) {
4852 readOutputParameters_l();
4853 delete mAudioMixer;
4854 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4855 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004856 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004857 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004858 if (name < 0) {
4859 break;
4860 }
4861 mTracks[i]->mName = name;
4862 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004863 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004864 }
Eric Laurent81784c32012-11-19 14:55:58 -08004865 }
4866
Eric Laurent42537be2016-01-08 17:16:42 -08004867 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004868}
4869
4870
4871void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4872{
Eric Laurent81784c32012-11-19 14:55:58 -08004873 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004874 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004875 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004876 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004877
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004878 if (hasFastMixer()) {
4879 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4880
4881 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4882 // while we are dumping it. It may be inconsistent, but it won't mutate!
4883 // This is a large object so we place it on the heap.
4884 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4885 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4886 copy->dump(fd);
4887 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004888
4889#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004890 // Similar for state queue
4891 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4892 observerCopy.dump(fd);
4893 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4894 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004895#endif
4896
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004897#ifdef AUDIO_WATCHDOG
4898 if (mAudioWatchdog != 0) {
4899 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4900 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4901 wdCopy.dump(fd);
4902 }
4903#endif
4904
4905 } else {
4906 dprintf(fd, " No FastMixer\n");
4907 }
4908
Glenn Kasten46909e72013-02-26 09:20:22 -08004909#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004910 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004911 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004912#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004913
Eric Laurent81784c32012-11-19 14:55:58 -08004914}
4915
4916uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4917{
4918 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4919}
4920
4921uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4922{
4923 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4924}
4925
4926void AudioFlinger::MixerThread::cacheParameters_l()
4927{
4928 PlaybackThread::cacheParameters_l();
4929
4930 // FIXME: Relaxed timing because of a certain device that can't meet latency
4931 // Should be reduced to 2x after the vendor fixes the driver issue
4932 // increase threshold again due to low power audio mode. The way this warning
4933 // threshold is calculated and its usefulness should be reconsidered anyway.
4934 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4935}
4936
4937// ----------------------------------------------------------------------------
4938
4939AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004940 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4941 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004942{
4943}
4944
Eric Laurentbfb1b832013-01-07 09:53:42 -08004945AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4946 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004947 ThreadBase::type_t type, bool systemReady)
4948 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08004949 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004950{
4951}
4952
Eric Laurent81784c32012-11-19 14:55:58 -08004953AudioFlinger::DirectOutputThread::~DirectOutputThread()
4954{
4955}
4956
Eric Laurent5850c4c2016-11-10 13:04:31 -08004957void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004958{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004959 float left, right;
4960
4961 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4962 left = right = 0;
4963 } else {
4964 float typeVolume = mStreamTypes[track->streamType()].volume;
4965 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004966 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004967
Andy Hung10cbff12017-02-21 17:30:14 -08004968 // Get volumeshaper scaling
4969 std::pair<float /* volume */, bool /* active */>
4970 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004971 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004972 v *= vh.first;
4973 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004974
Glenn Kastenc56f3422014-03-21 17:53:17 -07004975 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4976 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4977 if (left > GAIN_FLOAT_UNITY) {
4978 left = GAIN_FLOAT_UNITY;
4979 }
4980 left *= v;
4981 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4982 if (right > GAIN_FLOAT_UNITY) {
4983 right = GAIN_FLOAT_UNITY;
4984 }
4985 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004986 }
4987
4988 if (lastTrack) {
4989 if (left != mLeftVolFloat || right != mRightVolFloat) {
4990 mLeftVolFloat = left;
4991 mRightVolFloat = right;
4992
4993 // Convert volumes from float to 8.24
4994 uint32_t vl = (uint32_t)(left * (1 << 24));
4995 uint32_t vr = (uint32_t)(right * (1 << 24));
4996
4997 // Delegate volume control to effect in track effect chain if needed
4998 // only one effect chain can be present on DirectOutputThread, so if
4999 // there is one, the track is connected to it
5000 if (!mEffectChains.isEmpty()) {
5001 mEffectChains[0]->setVolume_l(&vl, &vr);
5002 left = (float)vl / (1 << 24);
5003 right = (float)vr / (1 << 24);
5004 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005005 status_t result = mOutput->stream->setVolume(left, right);
5006 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005007 }
5008 }
5009}
5010
Phil Burk43b4dcc2015-06-09 16:53:44 -07005011void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5012{
5013 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005014 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005015
Eric Laurent0f0631e2015-07-06 18:01:25 -07005016 if (previousTrack != 0 && latestTrack != 0) {
5017 if (mType == DIRECT) {
5018 if (previousTrack.get() != latestTrack.get()) {
5019 mFlushPending = true;
5020 }
5021 } else /* mType == OFFLOAD */ {
5022 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5023 mFlushPending = true;
5024 }
5025 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005026 }
5027 PlaybackThread::onAddNewTrack_l();
5028}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005029
Eric Laurent81784c32012-11-19 14:55:58 -08005030AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5031 Vector< sp<Track> > *tracksToRemove
5032)
5033{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005034 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005035 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005036 bool doHwPause = false;
5037 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005038
5039 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005040 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005041 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005042 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005043 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005044 continue;
5045 }
5046
Eric Laurent5850c4c2016-11-10 13:04:31 -08005047 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005048#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005049 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005050#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005051 // Only consider last track started for volume and mixer state control.
5052 // In theory an older track could underrun and restart after the new one starts
5053 // but as we only care about the transition phase between two tracks on a
5054 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005055 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005056 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005057
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005058 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005059 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005060 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005061 doHwPause = true;
5062 mHwPaused = true;
5063 }
5064 tracksToRemove->add(track);
5065 } else if (track->isFlushPending()) {
5066 track->flushAck();
5067 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005068 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005069 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005070 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005071 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005072 if (last) {
5073 mLeftVolFloat = mRightVolFloat = -1.0;
5074 if (mHwPaused) {
5075 doHwResume = true;
5076 mHwPaused = false;
5077 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005078 }
5079 }
5080
Eric Laurent81784c32012-11-19 14:55:58 -08005081 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005082 // for all its buffers to be filled before processing it.
5083 // Allow draining the buffer in case the client
5084 // app does not call stop() and relies on underrun to stop:
5085 // hence the test on (track->mRetryCount > 1).
5086 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005087 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005088 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005089 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005090 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005091 minFrames = mNormalFrameCount;
5092 } else {
5093 minFrames = 1;
5094 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005095
Eric Laurentab5cdba2014-06-09 17:22:27 -07005096 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5097 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005098 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005099 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005100
5101 if (track->mFillingUpStatus == Track::FS_FILLED) {
5102 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005103 if (last) {
5104 // make sure processVolume_l() will apply new volume even if 0
5105 mLeftVolFloat = mRightVolFloat = -1.0;
5106 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005107 if (!mHwSupportsPause) {
5108 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005109 }
5110 }
5111
5112 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005113 processVolume_l(track, last);
5114 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005115 sp<Track> previousTrack = mPreviousTrack.promote();
5116 if (previousTrack != 0) {
5117 if (track != previousTrack.get()) {
5118 // Flush any data still being written from last track
5119 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005120 // Invalidate previous track to force a seek when resuming.
5121 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005122 }
5123 }
5124 mPreviousTrack = track;
5125
Eric Laurentd595b7c2013-04-03 17:27:56 -07005126 // reset retry count
5127 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005128 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005129 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005130 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005131 doHwResume = true;
5132 mHwPaused = false;
5133 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005134 }
Eric Laurent81784c32012-11-19 14:55:58 -08005135 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005136 // clear effect chain input buffer if the last active track started underruns
5137 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005138 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005139 mEffectChains[0]->clearInputBuffer();
5140 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005141 if (track->isStopping_1()) {
5142 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005143 if (last && mHwPaused) {
5144 doHwResume = true;
5145 mHwPaused = false;
5146 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005147 }
5148 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5149 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005150 // We have consumed all the buffers of this track.
5151 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005152 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005153 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005154 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5155 } else {
5156 audioHALFrames = 0;
5157 }
5158
Andy Hung818e7a32016-02-16 18:08:07 -08005159 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005160 if (mStandby || !last ||
5161 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005162 if (track->isStopping_2()) {
5163 track->mState = TrackBase::STOPPED;
5164 }
Eric Laurent81784c32012-11-19 14:55:58 -08005165 if (track->isStopped()) {
5166 track->reset();
5167 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005168 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005169 }
5170 } else {
5171 // No buffers for this track. Give it a few chances to
5172 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005173 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005174 if (--(track->mRetryCount) <= 0) {
5175 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005176 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005177 // indicate to client process that the track was disabled because of underrun;
5178 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005179 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005180 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005181 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5182 "minFrames = %u, mFormat = %#x",
5183 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005184 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005185 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005186 doHwPause = true;
5187 mHwPaused = true;
5188 }
Eric Laurent81784c32012-11-19 14:55:58 -08005189 }
5190 }
5191 }
5192 }
5193
Eric Laurentd1f69b02014-12-15 14:33:13 -08005194 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005195 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005196 for (size_t i = 0; i < mTracks.size(); i++) {
5197 if (mTracks[i]->isFlushPending()) {
5198 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005199 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005200 }
5201 }
5202 }
5203
5204 // make sure the pause/flush/resume sequence is executed in the right order.
5205 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5206 // before flush and then resume HW. This can happen in case of pause/flush/resume
5207 // if resume is received before pause is executed.
5208 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005209 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005210 status_t result = mOutput->stream->pause();
5211 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005212 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005213 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005214 flushHw_l();
5215 }
5216 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005217 status_t result = mOutput->stream->resume();
5218 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005219 }
Eric Laurent81784c32012-11-19 14:55:58 -08005220 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005222
5223 return mixerStatus;
5224}
5225
5226void AudioFlinger::DirectOutputThread::threadLoop_mix()
5227{
Eric Laurent81784c32012-11-19 14:55:58 -08005228 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005229 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005230 // output audio to hardware
5231 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005232 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005233 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005234 status_t status = mActiveTrack->getNextBuffer(&buffer);
5235 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005236 // no need to pad with 0 for compressed audio
5237 if (audio_has_proportional_frames(mFormat)) {
5238 memset(curBuf, 0, frameCount * mFrameSize);
5239 }
Eric Laurent81784c32012-11-19 14:55:58 -08005240 break;
5241 }
5242 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5243 frameCount -= buffer.frameCount;
5244 curBuf += buffer.frameCount * mFrameSize;
5245 mActiveTrack->releaseBuffer(&buffer);
5246 }
Andy Hung2098f272014-02-27 14:00:06 -08005247 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005248 mSleepTimeUs = 0;
5249 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005250 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005251}
5252
5253void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5254{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005255 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005256 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005257 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005258 return;
5259 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005260 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005261 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005262 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005263 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005264 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005265 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005266 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005267 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005268 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
5270}
5271
Eric Laurentd1f69b02014-12-15 14:33:13 -08005272void AudioFlinger::DirectOutputThread::threadLoop_exit()
5273{
5274 {
5275 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005276 for (size_t i = 0; i < mTracks.size(); i++) {
5277 if (mTracks[i]->isFlushPending()) {
5278 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005279 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005280 }
5281 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005282 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005283 flushHw_l();
5284 }
5285 }
5286 PlaybackThread::threadLoop_exit();
5287}
5288
5289// must be called with thread mutex locked
5290bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5291{
5292 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005293 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005294
vivek mehta9cd7ad12016-03-17 00:18:29 -07005295 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5296 return !mStandby;
5297 }
5298
Eric Laurentd1f69b02014-12-15 14:33:13 -08005299 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5300 // after a timeout and we will enter standby then.
5301 if (mTracks.size() > 0) {
5302 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005303 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5304 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005305 }
5306
Eric Laurent5cff4032015-05-26 13:49:58 -07005307 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005308}
5309
Eric Laurent81784c32012-11-19 14:55:58 -08005310// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005311int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005312 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005313{
Eric Laurentad7dd962016-09-22 12:38:37 -07005314 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5315 return -1;
5316 }
Eric Laurent81784c32012-11-19 14:55:58 -08005317 return 0;
5318}
5319
5320// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005321void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005322{
5323}
5324
Eric Laurent10351942014-05-08 18:49:52 -07005325// checkForNewParameter_l() must be called with ThreadBase::mLock held
5326bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5327 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005328{
5329 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005330 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005331
Eric Laurent10351942014-05-08 18:49:52 -07005332 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005333
Eric Laurent10351942014-05-08 18:49:52 -07005334 AudioParameter param = AudioParameter(keyValuePair);
5335 int value;
5336 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5337 // forward device change to effects that have requested to be
5338 // aware of attached audio device.
5339 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005340 a2dpDeviceChanged =
5341 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005342 mOutDevice = value;
5343 for (size_t i = 0; i < mEffectChains.size(); i++) {
5344 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005345 }
5346 }
Eric Laurent81784c32012-11-19 14:55:58 -08005347 }
Eric Laurent10351942014-05-08 18:49:52 -07005348 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5349 // do not accept frame count changes if tracks are open as the track buffer
5350 // size depends on frame count and correct behavior would not be garantied
5351 // if frame count is changed after track creation
5352 if (!mTracks.isEmpty()) {
5353 status = INVALID_OPERATION;
5354 } else {
5355 reconfig = true;
5356 }
5357 }
5358 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005359 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005360 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005361 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005362 mStandby = true;
5363 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005364 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005365 }
5366 if (status == NO_ERROR && reconfig) {
5367 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005368 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005369 }
5370 }
5371
Eric Laurent42537be2016-01-08 17:16:42 -08005372 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005373}
5374
5375uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5376{
5377 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005378 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005379 time = PlaybackThread::activeSleepTimeUs();
5380 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005381 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005382 }
5383 return time;
5384}
5385
5386uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5387{
5388 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005389 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005390 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5391 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005392 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005393 }
5394 return time;
5395}
5396
5397uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5398{
5399 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005400 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005401 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5402 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005403 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005404 }
5405 return time;
5406}
5407
5408void AudioFlinger::DirectOutputThread::cacheParameters_l()
5409{
5410 PlaybackThread::cacheParameters_l();
5411
5412 // use shorter standby delay as on normal output to release
5413 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005414 // no delay on outputs with HW A/V sync
5415 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005416 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005417 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005418 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005419 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005420 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005421 }
Eric Laurent81784c32012-11-19 14:55:58 -08005422}
5423
Eric Laurente659ef42014-09-29 13:06:46 -07005424void AudioFlinger::DirectOutputThread::flushHw_l()
5425{
Phil Burk062e67a2015-02-11 13:40:50 -08005426 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005427 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005428 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005429}
5430
Andy Hung10cbff12017-02-21 17:30:14 -08005431int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5432 // If a VolumeShaper is active, we must wake up periodically to update volume.
5433 const int64_t NS_PER_MS = 1000000;
5434 return mVolumeShaperActive ?
5435 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5436}
5437
Eric Laurent81784c32012-11-19 14:55:58 -08005438// ----------------------------------------------------------------------------
5439
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005441 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005443 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005444 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005445 mDrainSequence(0),
5446 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005447{
5448}
5449
5450AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5451{
5452}
5453
5454void AudioFlinger::AsyncCallbackThread::onFirstRef()
5455{
5456 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5457}
5458
5459bool AudioFlinger::AsyncCallbackThread::threadLoop()
5460{
5461 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005462 uint32_t writeAckSequence;
5463 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005464 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005465
5466 {
5467 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005468 while (!((mWriteAckSequence & 1) ||
5469 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005470 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005471 exitPending())) {
5472 mWaitWorkCV.wait(mLock);
5473 }
5474
Eric Laurentbfb1b832013-01-07 09:53:42 -08005475 if (exitPending()) {
5476 break;
5477 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005478 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5479 mWriteAckSequence, mDrainSequence);
5480 writeAckSequence = mWriteAckSequence;
5481 mWriteAckSequence &= ~1;
5482 drainSequence = mDrainSequence;
5483 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005484 asyncError = mAsyncError;
5485 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486 }
5487 {
Eric Laurent4de95592013-09-26 15:28:21 -07005488 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5489 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005490 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005491 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005492 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005493 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005494 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005496 if (asyncError) {
5497 playbackThread->onAsyncError();
5498 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005499 }
5500 }
5501 }
5502 return false;
5503}
5504
5505void AudioFlinger::AsyncCallbackThread::exit()
5506{
5507 ALOGV("AsyncCallbackThread::exit");
5508 Mutex::Autolock _l(mLock);
5509 requestExit();
5510 mWaitWorkCV.broadcast();
5511}
5512
Eric Laurent3b4529e2013-09-05 18:09:19 -07005513void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514{
5515 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005516 // bit 0 is cleared
5517 mWriteAckSequence = sequence << 1;
5518}
5519
5520void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5521{
5522 Mutex::Autolock _l(mLock);
5523 // ignore unexpected callbacks
5524 if (mWriteAckSequence & 2) {
5525 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005526 mWaitWorkCV.signal();
5527 }
5528}
5529
Eric Laurent3b4529e2013-09-05 18:09:19 -07005530void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005531{
5532 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005533 // bit 0 is cleared
5534 mDrainSequence = sequence << 1;
5535}
5536
5537void AudioFlinger::AsyncCallbackThread::resetDraining()
5538{
5539 Mutex::Autolock _l(mLock);
5540 // ignore unexpected callbacks
5541 if (mDrainSequence & 2) {
5542 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005543 mWaitWorkCV.signal();
5544 }
5545}
5546
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005547void AudioFlinger::AsyncCallbackThread::setAsyncError()
5548{
5549 Mutex::Autolock _l(mLock);
5550 mAsyncError = true;
5551 mWaitWorkCV.signal();
5552}
5553
Eric Laurentbfb1b832013-01-07 09:53:42 -08005554
5555// ----------------------------------------------------------------------------
5556AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005557 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5558 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005559 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5560 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005561{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005562 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005563 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005564 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005565}
5566
Eric Laurentbfb1b832013-01-07 09:53:42 -08005567void AudioFlinger::OffloadThread::threadLoop_exit()
5568{
5569 if (mFlushPending || mHwPaused) {
5570 // If a flush is pending or track was paused, just discard buffered data
5571 flushHw_l();
5572 } else {
5573 mMixerStatus = MIXER_DRAIN_ALL;
5574 threadLoop_drain();
5575 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005576 if (mUseAsyncWrite) {
5577 ALOG_ASSERT(mCallbackThread != 0);
5578 mCallbackThread->exit();
5579 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005580 PlaybackThread::threadLoop_exit();
5581}
5582
5583AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5584 Vector< sp<Track> > *tracksToRemove
5585)
5586{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005587 size_t count = mActiveTracks.size();
5588
5589 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005590 bool doHwPause = false;
5591 bool doHwResume = false;
5592
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005593 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005594
Eric Laurentbfb1b832013-01-07 09:53:42 -08005595 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005596 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005597 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005598#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005599 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005600#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005601 // Only consider last track started for volume and mixer state control.
5602 // In theory an older track could underrun and restart after the new one starts
5603 // but as we only care about the transition phase between two tracks on a
5604 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005605 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005606 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005607
Haynes Mathew George7844f672014-01-15 12:32:55 -08005608 if (track->isInvalid()) {
5609 ALOGW("An invalidated track shouldn't be in active list");
5610 tracksToRemove->add(track);
5611 continue;
5612 }
5613
5614 if (track->mState == TrackBase::IDLE) {
5615 ALOGW("An idle track shouldn't be in active list");
5616 continue;
5617 }
5618
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 if (track->isPausing()) {
5620 track->setPaused();
5621 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005622 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005623 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005624 mHwPaused = true;
5625 }
5626 // If we were part way through writing the mixbuffer to
5627 // the HAL we must save this until we resume
5628 // BUG - this will be wrong if a different track is made active,
5629 // in that case we want to discard the pending data in the
5630 // mixbuffer and tell the client to present it again when the
5631 // track is resumed
5632 mPausedWriteLength = mCurrentWriteLength;
5633 mPausedBytesRemaining = mBytesRemaining;
5634 mBytesRemaining = 0; // stop writing
5635 }
5636 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005637 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005638 if (track->isStopping_1()) {
5639 track->mRetryCount = kMaxTrackStopRetriesOffload;
5640 } else {
5641 track->mRetryCount = kMaxTrackRetriesOffload;
5642 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005643 track->flushAck();
5644 if (last) {
5645 mFlushPending = true;
5646 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005647 } else if (track->isResumePending()){
5648 track->resumeAck();
5649 if (last) {
5650 if (mPausedBytesRemaining) {
5651 // Need to continue write that was interrupted
5652 mCurrentWriteLength = mPausedWriteLength;
5653 mBytesRemaining = mPausedBytesRemaining;
5654 mPausedBytesRemaining = 0;
5655 }
5656 if (mHwPaused) {
5657 doHwResume = true;
5658 mHwPaused = false;
5659 // threadLoop_mix() will handle the case that we need to
5660 // resume an interrupted write
5661 }
5662 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005663 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005664
Eric Laurent3df841a2016-07-15 15:15:40 -07005665 mLeftVolFloat = mRightVolFloat = -1.0;
5666
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005667 // Do not handle new data in this iteration even if track->framesReady()
5668 mixerStatus = MIXER_TRACKS_ENABLED;
5669 }
5670 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005671 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005672 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005673 if (track->mFillingUpStatus == Track::FS_FILLED) {
5674 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005675 if (last) {
5676 // make sure processVolume_l() will apply new volume even if 0
5677 mLeftVolFloat = mRightVolFloat = -1.0;
5678 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005679 }
5680
5681 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005682 sp<Track> previousTrack = mPreviousTrack.promote();
5683 if (previousTrack != 0) {
5684 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005685 // Flush any data still being written from last track
5686 mBytesRemaining = 0;
5687 if (mPausedBytesRemaining) {
5688 // Last track was paused so we also need to flush saved
5689 // mixbuffer state and invalidate track so that it will
5690 // re-submit that unwritten data when it is next resumed
5691 mPausedBytesRemaining = 0;
5692 // Invalidate is a bit drastic - would be more efficient
5693 // to have a flag to tell client that some of the
5694 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005695 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005696 }
5697 // flush data already sent to the DSP if changing audio session as audio
5698 // comes from a different source. Also invalidate previous track to force a
5699 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005700 if (previousTrack->sessionId() != track->sessionId()) {
5701 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005702 }
5703 }
5704 }
5705 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005706 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005707 if (track->isStopping_1()) {
5708 track->mRetryCount = kMaxTrackStopRetriesOffload;
5709 } else {
5710 track->mRetryCount = kMaxTrackRetriesOffload;
5711 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005712 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005713 mixerStatus = MIXER_TRACKS_READY;
5714 }
5715 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005716 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005717 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005718 if (--(track->mRetryCount) <= 0) {
5719 // Hardware buffer can hold a large amount of audio so we must
5720 // wait for all current track's data to drain before we say
5721 // that the track is stopped.
5722 if (mBytesRemaining == 0) {
5723 // Only start draining when all data in mixbuffer
5724 // has been written
5725 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5726 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5727 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5728 if (last && !mStandby) {
5729 // do not modify drain sequence if we are already draining. This happens
5730 // when resuming from pause after drain.
5731 if ((mDrainSequence & 1) == 0) {
5732 mSleepTimeUs = 0;
5733 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5734 mixerStatus = MIXER_DRAIN_TRACK;
5735 mDrainSequence += 2;
5736 }
5737 if (mHwPaused) {
5738 // It is possible to move from PAUSED to STOPPING_1 without
5739 // a resume so we must ensure hardware is running
5740 doHwResume = true;
5741 mHwPaused = false;
5742 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005743 }
5744 }
Eric Laurente93cc032016-05-05 10:15:10 -07005745 } else if (last) {
5746 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5747 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005748 }
5749 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005750 // Drain has completed or we are in standby, signal presentation complete
5751 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005752 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005753 uint32_t latency = 0;
5754 status_t result = mOutput->stream->getLatency(&latency);
5755 ALOGE_IF(result != OK,
5756 "Error when retrieving output stream latency: %d", result);
5757 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005758 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005759 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005760 track->presentationComplete(framesWritten, audioHALFrames);
5761 track->reset();
5762 tracksToRemove->add(track);
5763 }
5764 } else {
5765 // No buffers for this track. Give it a few chances to
5766 // fill a buffer, then remove it from active list.
5767 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005768 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005769 uint64_t position = 0;
5770 struct timespec unused;
5771 // The running check restarts the retry counter at least once.
5772 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5773 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5774 running = true;
5775 mOffloadUnderrunPosition = position;
5776 }
5777 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005778 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5779 (long long)position, (long long)mOffloadUnderrunPosition);
5780 }
5781 if (running) { // still running, give us more time.
5782 track->mRetryCount = kMaxTrackRetriesOffload;
5783 } else {
5784 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5785 track->name());
5786 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005787 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005788 // it will then automatically call start() when data is available
5789 track->disable();
5790 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005791 } else if (last){
5792 mixerStatus = MIXER_TRACKS_ENABLED;
5793 }
5794 }
5795 }
5796 // compute volume for this track
5797 processVolume_l(track, last);
5798 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005799
Eric Laurentea0fade2013-10-04 16:23:48 -07005800 // make sure the pause/flush/resume sequence is executed in the right order.
5801 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5802 // before flush and then resume HW. This can happen in case of pause/flush/resume
5803 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005804 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005805 status_t result = mOutput->stream->pause();
5806 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005807 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005808 if (mFlushPending) {
5809 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005810 }
Eric Laurentfd477972013-10-25 18:10:40 -07005811 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005812 status_t result = mOutput->stream->resume();
5813 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005814 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005815
Eric Laurentbfb1b832013-01-07 09:53:42 -08005816 // remove all the tracks that need to be...
5817 removeTracks_l(*tracksToRemove);
5818
5819 return mixerStatus;
5820}
5821
Eric Laurentbfb1b832013-01-07 09:53:42 -08005822// must be called with thread mutex locked
5823bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5824{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005825 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5826 mWriteAckSequence, mDrainSequence);
5827 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005828 return true;
5829 }
5830 return false;
5831}
5832
Eric Laurentbfb1b832013-01-07 09:53:42 -08005833bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5834{
5835 Mutex::Autolock _l(mLock);
5836 return waitingAsyncCallback_l();
5837}
5838
5839void AudioFlinger::OffloadThread::flushHw_l()
5840{
Eric Laurente659ef42014-09-29 13:06:46 -07005841 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005842 // Flush anything still waiting in the mixbuffer
5843 mCurrentWriteLength = 0;
5844 mBytesRemaining = 0;
5845 mPausedWriteLength = 0;
5846 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005847 // reset bytes written count to reflect that DSP buffers are empty after flush.
5848 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005849 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005850
Eric Laurentbfb1b832013-01-07 09:53:42 -08005851 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005852 // discard any pending drain or write ack by incrementing sequence
5853 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5854 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005855 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005856 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5857 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005858 }
5859}
5860
Haynes Mathew George05317d22016-05-03 16:34:26 -07005861void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5862{
5863 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005864 if (PlaybackThread::invalidateTracks_l(streamType)) {
5865 mFlushPending = true;
5866 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005867}
5868
Eric Laurentbfb1b832013-01-07 09:53:42 -08005869// ----------------------------------------------------------------------------
5870
Eric Laurent81784c32012-11-19 14:55:58 -08005871AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005872 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005873 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005874 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005875 mWaitTimeMs(UINT_MAX)
5876{
5877 addOutputTrack(mainThread);
5878}
5879
5880AudioFlinger::DuplicatingThread::~DuplicatingThread()
5881{
5882 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5883 mOutputTracks[i]->destroy();
5884 }
5885}
5886
5887void AudioFlinger::DuplicatingThread::threadLoop_mix()
5888{
5889 // mix buffers...
5890 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005891 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005892 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005893 if (mMixerBufferValid) {
5894 memset(mMixerBuffer, 0, mMixerBufferSize);
5895 } else {
5896 memset(mSinkBuffer, 0, mSinkBufferSize);
5897 }
Eric Laurent81784c32012-11-19 14:55:58 -08005898 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005899 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005900 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005901 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005902 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005903}
5904
5905void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5906{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005907 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005908 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005909 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005910 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005911 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005912 }
5913 } else if (mBytesWritten != 0) {
5914 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5915 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005916 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005917 } else {
5918 // flush remaining overflow buffers in output tracks
5919 writeFrames = 0;
5920 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005921 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005922 }
5923}
5924
Eric Laurentbfb1b832013-01-07 09:53:42 -08005925ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005926{
5927 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005928 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005930 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005931 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005932}
5933
5934void AudioFlinger::DuplicatingThread::threadLoop_standby()
5935{
5936 // DuplicatingThread implements standby by stopping all tracks
5937 for (size_t i = 0; i < outputTracks.size(); i++) {
5938 outputTracks[i]->stop();
5939 }
5940}
5941
5942void AudioFlinger::DuplicatingThread::saveOutputTracks()
5943{
5944 outputTracks = mOutputTracks;
5945}
5946
5947void AudioFlinger::DuplicatingThread::clearOutputTracks()
5948{
5949 outputTracks.clear();
5950}
5951
5952void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5953{
5954 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005955 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5956 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5957 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5958 const size_t frameCount =
5959 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5960 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5961 // from different OutputTracks and their associated MixerThreads (e.g. one may
5962 // nearly empty and the other may be dropping data).
5963
5964 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005965 this,
5966 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005967 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005968 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005969 frameCount,
5970 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005971 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5972 if (status != NO_ERROR) {
5973 ALOGE("addOutputTrack() initCheck failed %d", status);
5974 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005975 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005976 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5977 mOutputTracks.add(outputTrack);
5978 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5979 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005980}
5981
5982void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5983{
5984 Mutex::Autolock _l(mLock);
5985 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5986 if (mOutputTracks[i]->thread() == thread) {
5987 mOutputTracks[i]->destroy();
5988 mOutputTracks.removeAt(i);
5989 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005990 if (thread->getOutput() == mOutput) {
5991 mOutput = NULL;
5992 }
Eric Laurent81784c32012-11-19 14:55:58 -08005993 return;
5994 }
5995 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005996 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005997}
5998
5999// caller must hold mLock
6000void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6001{
6002 mWaitTimeMs = UINT_MAX;
6003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6004 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6005 if (strong != 0) {
6006 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6007 if (waitTimeMs < mWaitTimeMs) {
6008 mWaitTimeMs = waitTimeMs;
6009 }
6010 }
6011 }
6012}
6013
6014
6015bool AudioFlinger::DuplicatingThread::outputsReady(
6016 const SortedVector< sp<OutputTrack> > &outputTracks)
6017{
6018 for (size_t i = 0; i < outputTracks.size(); i++) {
6019 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6020 if (thread == 0) {
6021 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6022 outputTracks[i].get());
6023 return false;
6024 }
6025 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6026 // see note at standby() declaration
6027 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6028 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6029 thread.get());
6030 return false;
6031 }
6032 }
6033 return true;
6034}
6035
6036uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6037{
6038 return (mWaitTimeMs * 1000) / 2;
6039}
6040
6041void AudioFlinger::DuplicatingThread::cacheParameters_l()
6042{
6043 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6044 updateWaitTime_l();
6045
6046 MixerThread::cacheParameters_l();
6047}
6048
Eric Laurent6acd1d42017-01-04 14:23:29 -08006049
Eric Laurent81784c32012-11-19 14:55:58 -08006050// ----------------------------------------------------------------------------
6051// Record
6052// ----------------------------------------------------------------------------
6053
6054AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6055 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006056 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006057 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006058 audio_devices_t inDevice,
6059 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006060#ifdef TEE_SINK
6061 , const sp<NBAIO_Sink>& teeSink
6062#endif
6063 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006064 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006065 mInput(input),
6066 mActiveTracks(&this->mLocalLog),
6067 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006068 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006069 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006070#ifdef TEE_SINK
6071 , mTeeSink(teeSink)
6072#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006073 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6074 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006075 // mFastCapture below
6076 , mFastCaptureFutex(0)
6077 // mInputSource
6078 // mPipeSink
6079 // mPipeSource
6080 , mPipeFramesP2(0)
6081 // mPipeMemory
6082 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006083 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006084 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006085{
Glenn Kastend7dca052015-03-05 16:05:54 -08006086 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6087 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006088
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006089 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006090
6091 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006092 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006093 size_t numCounterOffers = 0;
6094 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006095#if !LOG_NDEBUG
6096 ssize_t index =
6097#else
6098 (void)
6099#endif
6100 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006101 ALOG_ASSERT(index == 0);
6102
6103 // initialize fast capture depending on configuration
6104 bool initFastCapture;
6105 switch (kUseFastCapture) {
6106 case FastCapture_Never:
6107 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006108 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006109 break;
6110 case FastCapture_Always:
6111 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006112 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006113 break;
6114 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006115 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006116 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6117 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6118 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006119 break;
6120 // case FastCapture_Dynamic:
6121 }
6122
6123 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006124 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006125 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006126 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6127 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006128 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006129 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006130 const sp<MemoryDealer> roHeap(readOnlyHeap());
6131 sp<IMemory> pipeMemory;
6132 if ((roHeap == 0) ||
6133 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006134 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6135 ALOGE("not enough memory for pipe buffer size=%zu; "
6136 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6137 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6138 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006139 goto failed;
6140 }
6141 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6142 memset(pipeBuffer, 0, pipeSize);
6143 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6144 const NBAIO_Format offers[1] = {format};
6145 size_t numCounterOffers = 0;
6146 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6147 ALOG_ASSERT(index == 0);
6148 mPipeSink = pipe;
6149 PipeReader *pipeReader = new PipeReader(*pipe);
6150 numCounterOffers = 0;
6151 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6152 ALOG_ASSERT(index == 0);
6153 mPipeSource = pipeReader;
6154 mPipeFramesP2 = pipeFramesP2;
6155 mPipeMemory = pipeMemory;
6156
6157 // create fast capture
6158 mFastCapture = new FastCapture();
6159 FastCaptureStateQueue *sq = mFastCapture->sq();
6160#ifdef STATE_QUEUE_DUMP
6161 // FIXME
6162#endif
6163 FastCaptureState *state = sq->begin();
6164 state->mCblk = NULL;
6165 state->mInputSource = mInputSource.get();
6166 state->mInputSourceGen++;
6167 state->mPipeSink = pipe;
6168 state->mPipeSinkGen++;
6169 state->mFrameCount = mFrameCount;
6170 state->mCommand = FastCaptureState::COLD_IDLE;
6171 // already done in constructor initialization list
6172 //mFastCaptureFutex = 0;
6173 state->mColdFutexAddr = &mFastCaptureFutex;
6174 state->mColdGen++;
6175 state->mDumpState = &mFastCaptureDumpState;
6176#ifdef TEE_SINK
6177 // FIXME
6178#endif
6179 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6180 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6181 sq->end();
6182 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6183
6184 // start the fast capture
6185 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6186 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006187 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006188 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006189#ifdef AUDIO_WATCHDOG
6190 // FIXME
6191#endif
6192
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006193 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006194 }
6195failed: ;
6196
6197 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006198}
6199
Eric Laurent81784c32012-11-19 14:55:58 -08006200AudioFlinger::RecordThread::~RecordThread()
6201{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006202 if (mFastCapture != 0) {
6203 FastCaptureStateQueue *sq = mFastCapture->sq();
6204 FastCaptureState *state = sq->begin();
6205 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6206 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6207 if (old == -1) {
6208 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6209 }
6210 }
6211 state->mCommand = FastCaptureState::EXIT;
6212 sq->end();
6213 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6214 mFastCapture->join();
6215 mFastCapture.clear();
6216 }
6217 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006218 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006219 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006220}
6221
6222void AudioFlinger::RecordThread::onFirstRef()
6223{
Glenn Kastend7dca052015-03-05 16:05:54 -08006224 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006225}
6226
Eric Laurent555530a2017-02-07 18:17:24 -08006227void AudioFlinger::RecordThread::preExit()
6228{
6229 ALOGV(" preExit()");
6230 Mutex::Autolock _l(mLock);
6231 for (size_t i = 0; i < mTracks.size(); i++) {
6232 sp<RecordTrack> track = mTracks[i];
6233 track->invalidate();
6234 }
6235 mActiveTracks.clear();
6236 mStartStopCond.broadcast();
6237}
6238
Eric Laurent81784c32012-11-19 14:55:58 -08006239bool AudioFlinger::RecordThread::threadLoop()
6240{
Eric Laurent81784c32012-11-19 14:55:58 -08006241 nsecs_t lastWarning = 0;
6242
6243 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006244
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006245reacquire_wakelock:
6246 sp<RecordTrack> activeTrack;
6247 {
6248 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006249 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006250 }
6251
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006252 // used to request a deferred sleep, to be executed later while mutex is unlocked
6253 uint32_t sleepUs = 0;
6254
6255 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006256 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006257 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006258
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006259 // activeTracks accumulates a copy of a subset of mActiveTracks
6260 Vector< sp<RecordTrack> > activeTracks;
6261
Glenn Kasten735f45f2014-08-18 15:51:59 -07006262 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006263 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006264
Glenn Kasten735f45f2014-08-18 15:51:59 -07006265 // reference to a fast track which is about to be removed
6266 sp<RecordTrack> fastTrackToRemove;
6267
Eric Laurent81784c32012-11-19 14:55:58 -08006268 { // scope for mLock
6269 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006270
Eric Laurent021cf962014-05-13 10:18:14 -07006271 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006272
Eric Laurent000a4192014-01-29 15:17:32 -08006273 // check exitPending here because checkForNewParameters_l() and
6274 // checkForNewParameters_l() can temporarily release mLock
6275 if (exitPending()) {
6276 break;
6277 }
6278
Eric Laurent5c25d562016-07-13 17:17:45 -07006279 // sleep with mutex unlocked
6280 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006281 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006282 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6283 ATRACE_END();
6284 sleepUs = 0;
6285 continue;
6286 }
6287
Glenn Kasten2b806402013-11-20 16:37:38 -08006288 // if no active track(s), then standby and release wakelock
6289 size_t size = mActiveTracks.size();
6290 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006291 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006292 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006293 releaseWakeLock_l();
6294 ALOGV("RecordThread: loop stopping");
6295 // go to sleep
6296 mWaitWorkCV.wait(mLock);
6297 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006298 goto reacquire_wakelock;
6299 }
6300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006302 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006303 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006304
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006305 activeTrack = mActiveTracks[i];
6306 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006307 if (activeTrack->isFastTrack()) {
6308 ALOG_ASSERT(fastTrackToRemove == 0);
6309 fastTrackToRemove = activeTrack;
6310 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006311 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006312 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006313 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006314 continue;
6315 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006316
6317 TrackBase::track_state activeTrackState = activeTrack->mState;
6318 switch (activeTrackState) {
6319
6320 case TrackBase::PAUSING:
6321 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006322 doBroadcast = true;
6323 size--;
6324 continue;
6325
6326 case TrackBase::STARTING_1:
6327 sleepUs = 10000;
6328 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006329 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006330 continue;
6331
6332 case TrackBase::STARTING_2:
6333 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006334 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006335 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006336 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006337 break;
6338
6339 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006340 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006341 break;
6342
6343 case TrackBase::IDLE:
6344 i++;
6345 continue;
6346
6347 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006348 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006349 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006350
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006351 activeTracks.add(activeTrack);
6352 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006353
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006354 if (activeTrack->isFastTrack()) {
6355 ALOG_ASSERT(!mFastTrackAvail);
6356 ALOG_ASSERT(fastTrack == 0);
6357 fastTrack = activeTrack;
6358 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006359 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006360
Andy Hungdae27702016-10-31 14:01:16 -07006361 mActiveTracks.updatePowerState(this);
6362
Eric Laurent5c25d562016-07-13 17:17:45 -07006363 if (allStopped) {
6364 standbyIfNotAlreadyInStandby();
6365 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006366 if (doBroadcast) {
6367 mStartStopCond.broadcast();
6368 }
6369
6370 // sleep if there are no active tracks to process
6371 if (activeTracks.size() == 0) {
6372 if (sleepUs == 0) {
6373 sleepUs = kRecordThreadSleepUs;
6374 }
6375 continue;
6376 }
6377 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006378
Eric Laurent81784c32012-11-19 14:55:58 -08006379 lockEffectChains_l(effectChains);
6380 }
6381
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006383
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006384 size_t size = effectChains.size();
6385 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006386 // thread mutex is not locked, but effect chain is locked
6387 effectChains[i]->process_l();
6388 }
6389
Glenn Kasten735f45f2014-08-18 15:51:59 -07006390 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006391 if (mFastCapture != 0) {
6392 FastCaptureStateQueue *sq = mFastCapture->sq();
6393 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006394 bool didModify = false;
6395 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006396 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6397 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6398 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6399 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6400 if (old == -1) {
6401 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6402 }
6403 }
6404 state->mCommand = FastCaptureState::READ_WRITE;
6405#if 0 // FIXME
6406 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006407 FastThreadDumpState::kSamplingNforLowRamDevice :
6408 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006409#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006410 didModify = true;
6411 }
6412 audio_track_cblk_t *cblkOld = state->mCblk;
6413 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6414 if (cblkNew != cblkOld) {
6415 state->mCblk = cblkNew;
6416 // block until acked if removing a fast track
6417 if (cblkOld != NULL) {
6418 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6419 }
6420 didModify = true;
6421 }
6422 sq->end(didModify);
6423 if (didModify) {
6424 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006425#if 0
6426 if (kUseFastCapture == FastCapture_Dynamic) {
6427 mNormalSource = mPipeSource;
6428 }
6429#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006430 }
6431 }
6432
Glenn Kasten735f45f2014-08-18 15:51:59 -07006433 // now run the fast track destructor with thread mutex unlocked
6434 fastTrackToRemove.clear();
6435
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6437 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6438 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6439 // If destination is non-contiguous, first read past the nominal end of buffer, then
6440 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006441
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006442 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006443 ssize_t framesRead;
6444
6445 // If an NBAIO source is present, use it to read the normal capture's data
6446 if (mPipeSource != 0) {
6447 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006448 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006449 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006450 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006451 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6452 // buffer size or at least for 20ms.
6453 size_t sleepFrames = max(
6454 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6455 if (framesRead <= (ssize_t) sleepFrames) {
6456 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6457 }
6458 if (framesRead < 0) {
6459 status_t status = (status_t) framesRead;
6460 switch (status) {
6461 case OVERRUN:
6462 ALOGW("overrun on read from pipe");
6463 framesRead = 0;
6464 break;
6465 case NEGOTIATE:
6466 ALOGE("re-negotiation is needed");
6467 framesRead = -1; // Will cause an attempt to recover.
6468 break;
6469 default:
6470 ALOGE("unknown error %d on read from pipe", status);
6471 break;
6472 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006473 }
6474 // otherwise use the HAL / AudioStreamIn directly
6475 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006476 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006477 size_t bytesRead;
6478 status_t result = mInput->stream->read(
6479 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006480 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006481 if (result < 0) {
6482 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006483 } else {
6484 framesRead = bytesRead / mFrameSize;
6485 }
6486 }
6487
Andy Hung3f0c9022016-01-15 17:49:46 -08006488 // Update server timestamp with server stats
6489 // systemTime() is optional if the hardware supports timestamps.
6490 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6491 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6492
6493 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006494 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006495 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006496 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006497 if (ret == NO_ERROR) {
6498 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6499 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6500 // Note: In general record buffers should tend to be empty in
6501 // a properly running pipeline.
6502 //
6503 // Also, it is not advantageous to call get_presentation_position during the read
6504 // as the read obtains a lock, preventing the timestamp call from executing.
6505 }
6506 }
6507 // Use this to track timestamp information
6508 // ALOGD("%s", mTimestamp.toString().c_str());
6509
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006510 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006511 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006512 // Force input into standby so that it tries to recover at next read attempt
6513 inputStandBy();
6514 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006515 }
6516 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006517 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006518 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006519 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006520
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006521 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006522 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006523 }
6524 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006525 {
6526 size_t part1 = mRsmpInFramesP2 - rear;
6527 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006528 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006529 (framesRead - part1) * mFrameSize);
6530 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006531 }
6532 rear = mRsmpInRear += framesRead;
6533
6534 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006535
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006536 // loop over each active track
6537 for (size_t i = 0; i < size; i++) {
6538 activeTrack = activeTracks[i];
6539
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006540 // skip fast tracks, as those are handled directly by FastCapture
6541 if (activeTrack->isFastTrack()) {
6542 continue;
6543 }
6544
Andy Hung73c02e42015-03-29 01:13:58 -07006545 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006546 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6547
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006548 enum {
6549 OVERRUN_UNKNOWN,
6550 OVERRUN_TRUE,
6551 OVERRUN_FALSE
6552 } overrun = OVERRUN_UNKNOWN;
6553
6554 // loop over getNextBuffer to handle circular sink
6555 for (;;) {
6556
6557 activeTrack->mSink.frameCount = ~0;
6558 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6559 size_t framesOut = activeTrack->mSink.frameCount;
6560 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6561
Andy Hung73c02e42015-03-29 01:13:58 -07006562 // check available frames and handle overrun conditions
6563 // if the record track isn't draining fast enough.
6564 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006565 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006566 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6567 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006568 overrun = OVERRUN_TRUE;
6569 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006570 if (framesOut == 0 || framesIn == 0) {
6571 break;
6572 }
6573
Andy Hung6770c6f2015-04-07 13:43:36 -07006574 // Don't allow framesOut to be larger than what is possible with resampling
6575 // from framesIn.
6576 // This isn't strictly necessary but helps limit buffer resizing in
6577 // RecordBufferConverter. TODO: remove when no longer needed.
6578 framesOut = min(framesOut,
6579 destinationFramesPossible(
6580 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006581 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6582 framesOut = activeTrack->mRecordBufferConverter->convert(
6583 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006584
6585 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6586 overrun = OVERRUN_FALSE;
6587 }
6588
6589 if (activeTrack->mFramesToDrop == 0) {
6590 if (framesOut > 0) {
6591 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006592 // Sanitize before releasing if the track has no access to the source data
6593 // An idle UID receives silence from non virtual devices until active
6594 if (activeTrack->isSilenced()) {
6595 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6596 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 activeTrack->releaseBuffer(&activeTrack->mSink);
6598 }
6599 } else {
6600 // FIXME could do a partial drop of framesOut
6601 if (activeTrack->mFramesToDrop > 0) {
6602 activeTrack->mFramesToDrop -= framesOut;
6603 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006604 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006605 }
6606 } else {
6607 activeTrack->mFramesToDrop += framesOut;
6608 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6609 activeTrack->mSyncStartEvent->isCancelled()) {
6610 ALOGW("Synced record %s, session %d, trigger session %d",
6611 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6612 activeTrack->sessionId(),
6613 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006614 activeTrack->mSyncStartEvent->triggerSession() :
6615 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006616 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006617 }
6618 }
6619 }
6620
6621 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006622 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006623 }
6624 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006625
6626 switch (overrun) {
6627 case OVERRUN_TRUE:
6628 // client isn't retrieving buffers fast enough
6629 if (!activeTrack->setOverflow()) {
6630 nsecs_t now = systemTime();
6631 // FIXME should lastWarning per track?
6632 if ((now - lastWarning) > kWarningThrottleNs) {
6633 ALOGW("RecordThread: buffer overflow");
6634 lastWarning = now;
6635 }
6636 }
6637 break;
6638 case OVERRUN_FALSE:
6639 activeTrack->clearOverflow();
6640 break;
6641 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006642 break;
6643 }
6644
Andy Hung3f0c9022016-01-15 17:49:46 -08006645 // update frame information and push timestamp out
6646 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006647 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006648 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6649 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006650 }
6651
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006652unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006653 // enable changes in effect chain
6654 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006655 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006656 }
6657
Glenn Kasten93e471f2013-08-19 08:40:07 -07006658 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006659
6660 {
6661 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006662 for (size_t i = 0; i < mTracks.size(); i++) {
6663 sp<RecordTrack> track = mTracks[i];
6664 track->invalidate();
6665 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006666 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006667 mStartStopCond.broadcast();
6668 }
6669
6670 releaseWakeLock();
6671
6672 ALOGV("RecordThread %p exiting", this);
6673 return false;
6674}
6675
Glenn Kasten93e471f2013-08-19 08:40:07 -07006676void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006677{
6678 if (!mStandby) {
6679 inputStandBy();
6680 mStandby = true;
6681 }
6682}
6683
6684void AudioFlinger::RecordThread::inputStandBy()
6685{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006686 // Idle the fast capture if it's currently running
6687 if (mFastCapture != 0) {
6688 FastCaptureStateQueue *sq = mFastCapture->sq();
6689 FastCaptureState *state = sq->begin();
6690 if (!(state->mCommand & FastCaptureState::IDLE)) {
6691 state->mCommand = FastCaptureState::COLD_IDLE;
6692 state->mColdFutexAddr = &mFastCaptureFutex;
6693 state->mColdGen++;
6694 mFastCaptureFutex = 0;
6695 sq->end();
6696 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6697 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6698#if 0
6699 if (kUseFastCapture == FastCapture_Dynamic) {
6700 // FIXME
6701 }
6702#endif
6703#ifdef AUDIO_WATCHDOG
6704 // FIXME
6705#endif
6706 } else {
6707 sq->end(false /*didModify*/);
6708 }
6709 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006710 status_t result = mInput->stream->standby();
6711 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006712
6713 // If going into standby, flush the pipe source.
6714 if (mPipeSource.get() != nullptr) {
6715 const ssize_t flushed = mPipeSource->flush();
6716 if (flushed > 0) {
6717 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6718 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6719 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6720 }
6721 }
Eric Laurent81784c32012-11-19 14:55:58 -08006722}
6723
Glenn Kasten05997e22014-03-13 15:08:33 -07006724// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006725sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006726 const sp<AudioFlinger::Client>& client,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006727 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006728 audio_format_t format,
6729 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006730 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006731 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006732 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006733 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006734 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006735 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006736 status_t *status,
6737 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006738{
Glenn Kasten74935e42013-12-19 08:56:45 -08006739 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006740 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006741 sp<RecordTrack> track;
6742 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006743 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006744 audio_input_flags_t requestedFlags = *flags;
6745 uint32_t sampleRate;
6746
6747 lStatus = initCheck();
6748 if (lStatus != NO_ERROR) {
6749 ALOGE("createRecordTrack_l() audio driver not initialized");
6750 goto Exit;
6751 }
6752
6753 if (*pSampleRate == 0) {
6754 *pSampleRate = mSampleRate;
6755 }
6756 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006757
6758 // special case for FAST flag considered OK if fast capture is present
6759 if (hasFastCapture()) {
6760 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6761 }
6762
Eric Laurentf14db3c2017-12-08 14:20:36 -08006763 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006764 if ((*flags & inputFlags) != *flags) {
6765 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6766 " input flags (%08x)",
6767 *flags, inputFlags);
6768 *flags = (audio_input_flags_t)(*flags & inputFlags);
6769 }
Eric Laurent81784c32012-11-19 14:55:58 -08006770
Glenn Kasten90e58b12013-07-31 16:16:02 -07006771 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006772 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006773 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006774 // we formerly checked for a callback handler (non-0 tid),
6775 // but that is no longer required for TRANSFER_OBTAIN mode
6776 //
Glenn Kasten74105912014-07-03 12:28:53 -07006777 // frame count is not specified, or is exactly the pipe depth
6778 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006779 // PCM data
6780 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006781 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006782 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006783 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006784 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006785 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006786 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006787 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006788 hasFastCapture() &&
6789 // there are sufficient fast track slots available
6790 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006791 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006792 // check compatibility with audio effects.
6793 Mutex::Autolock _l(mLock);
6794 // Do not accept FAST flag if the session has software effects
6795 sp<EffectChain> chain = getEffectChain_l(sessionId);
6796 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006797 audio_input_flags_t old = *flags;
6798 chain->checkInputFlagCompatibility(flags);
6799 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006800 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6801 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006802 }
6803 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006804 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006805 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6806 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006807 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006808 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6809 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006810 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006811 this, frameCount, mFrameCount, mPipeFramesP2,
6812 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006813 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006814 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006815 }
6816 }
6817
Eric Laurentf14db3c2017-12-08 14:20:36 -08006818 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
6819 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
6820 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
6821 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
6822 lStatus = BAD_TYPE;
6823 goto Exit;
6824 }
6825
Glenn Kasten74105912014-07-03 12:28:53 -07006826 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006827 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006828 // fast track: frame count is exactly the pipe depth
6829 frameCount = mPipeFramesP2;
6830 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08006831 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07006832 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006833 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6834 // or 20 ms if there is a fast capture
6835 // TODO This could be a roundupRatio inline, and const
6836 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6837 * sampleRate + mSampleRate - 1) / mSampleRate;
6838 // minimum number of notification periods is at least kMinNotifications,
6839 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6840 static const size_t kMinNotifications = 3;
6841 static const uint32_t kMinMs = 30;
6842 // TODO This could be a roundupRatio inline
6843 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6844 // TODO This could be a roundupRatio inline
6845 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6846 maxNotificationFrames;
6847 const size_t minFrameCount = maxNotificationFrames *
6848 max(kMinNotifications, minNotificationsByMs);
6849 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08006850 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
6851 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006852 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006853 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006854 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006855 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006856
6857 { // scope for mLock
6858 Mutex::Autolock _l(mLock);
6859
6860 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006861 format, channelMask, frameCount,
6862 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006863 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006864
Glenn Kasten03003332013-08-06 15:40:54 -07006865 lStatus = track->initCheck();
6866 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006867 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006868 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006869 goto Exit;
6870 }
6871 mTracks.add(track);
6872
Eric Laurent05067782016-06-01 18:27:28 -07006873 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006874 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6875 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6876 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006877 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006878 }
Eric Laurent81784c32012-11-19 14:55:58 -08006879 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006880
Eric Laurent81784c32012-11-19 14:55:58 -08006881 lStatus = NO_ERROR;
6882
6883Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006884 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006885 return track;
6886}
6887
6888status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6889 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006890 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006891{
6892 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6893 sp<ThreadBase> strongMe = this;
6894 status_t status = NO_ERROR;
6895
6896 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006897 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006898 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006899 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006900 triggerSession,
6901 recordTrack->sessionId(),
6902 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006903 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006904 // Sync event can be cancelled by the trigger session if the track is not in a
6905 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006906 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006907 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006908 } else {
6909 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08006910 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006911 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006912 }
6913 }
6914
6915 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006916 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006917 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006918 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6919 if (recordTrack->mState == TrackBase::PAUSING) {
6920 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006921 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006922 } else {
6923 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006924 }
6925 return status;
6926 }
6927
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006928 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6929 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6930 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006931 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006932 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006933 status_t status = NO_ERROR;
6934 if (recordTrack->isExternalTrack()) {
6935 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006936 bool silenced;
6937 status = AudioSystem::startInput(mId, recordTrack->sessionId(),
6938 mInDevice, recordTrack->uid(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07006939 mLock.lock();
6940 // FIXME should verify that recordTrack is still in mActiveTracks
6941 if (status != NO_ERROR) {
6942 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006943 recordTrack->clearSyncStartEvent();
6944 ALOGV("RecordThread::start error %d", status);
6945 return status;
6946 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006947 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08006948 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006949 // Catch up with current buffer indices if thread is already running.
6950 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6951 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6952 // see previously buffered data before it called start(), but with greater risk of overrun.
6953
Andy Hung73c02e42015-03-29 01:13:58 -07006954 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006955 // clear any converter state as new data will be discontinuous
6956 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006957 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006958 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006959 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006960 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006961 ALOGV("Record failed to start");
6962 status = BAD_VALUE;
6963 goto startError;
6964 }
Eric Laurent81784c32012-11-19 14:55:58 -08006965 return status;
6966 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006967
Eric Laurent81784c32012-11-19 14:55:58 -08006968startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006969 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006970 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006971 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006972 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006973 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006974 return status;
6975}
6976
Eric Laurent81784c32012-11-19 14:55:58 -08006977void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6978{
6979 sp<SyncEvent> strongEvent = event.promote();
6980
6981 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006982 sp<RefBase> ptr = strongEvent->cookie().promote();
6983 if (ptr != 0) {
6984 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6985 recordTrack->handleSyncStartEvent(strongEvent);
6986 }
Eric Laurent81784c32012-11-19 14:55:58 -08006987 }
6988}
6989
Glenn Kastena8356f62013-07-25 14:37:52 -07006990bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006991 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006992 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006993 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006994 return false;
6995 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006996 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006997 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006998 // signal thread to stop
6999 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007000 // do not wait for mStartStopCond if exiting
7001 if (exitPending()) {
7002 return true;
7003 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007004 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007005 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007006 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007007 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007008 ALOGV("Record stopped OK");
7009 return true;
7010 }
7011 return false;
7012}
7013
Glenn Kasten0f11b512014-01-31 16:18:54 -08007014bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007015{
7016 return false;
7017}
7018
Glenn Kasten0f11b512014-01-31 16:18:54 -08007019status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007020{
7021#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7022 if (!isValidSyncEvent(event)) {
7023 return BAD_VALUE;
7024 }
7025
Glenn Kastend848eb42016-03-08 13:42:11 -08007026 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007027 status_t ret = NAME_NOT_FOUND;
7028
7029 Mutex::Autolock _l(mLock);
7030
7031 for (size_t i = 0; i < mTracks.size(); i++) {
7032 sp<RecordTrack> track = mTracks[i];
7033 if (eventSession == track->sessionId()) {
7034 (void) track->setSyncEvent(event);
7035 ret = NO_ERROR;
7036 }
7037 }
7038 return ret;
7039#else
7040 return BAD_VALUE;
7041#endif
7042}
7043
7044// destroyTrack_l() must be called with ThreadBase::mLock held
7045void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7046{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007047 track->terminate();
7048 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007049 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007050 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007051 removeTrack_l(track);
7052 }
7053}
7054
7055void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7056{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007057 String8 result;
7058 track->appendDump(result, false /* active */);
7059 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7060
Eric Laurent81784c32012-11-19 14:55:58 -08007061 mTracks.remove(track);
7062 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007063 if (track->isFastTrack()) {
7064 ALOG_ASSERT(!mFastTrackAvail);
7065 mFastTrackAvail = true;
7066 }
Eric Laurent81784c32012-11-19 14:55:58 -08007067}
7068
7069void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7070{
7071 dumpInternals(fd, args);
7072 dumpTracks(fd, args);
7073 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007074 dprintf(fd, " Local log:\n");
7075 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007076}
7077
7078void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7079{
Glenn Kasten44182c22015-03-05 17:12:23 -08007080 dumpBase(fd, args);
7081
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007082 AudioStreamIn *input = mInput;
7083 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7084 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7085 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007086 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007087 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007088 }
Andy Hungbfa64962017-06-12 14:43:19 -07007089
7090 if (input != nullptr) {
7091 dprintf(fd, " Hal stream dump:\n");
7092 (void)input->stream->dump(fd);
7093 }
7094
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007095 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007096 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007097
Glenn Kasten2f90c512015-12-02 11:40:09 -08007098 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7099 // while we are dumping it. It may be inconsistent, but it won't mutate!
7100 // This is a large object so we place it on the heap.
7101 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7102 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7103 copy->dump(fd);
7104 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007105}
7106
Glenn Kasten0f11b512014-01-31 16:18:54 -08007107void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007108{
Eric Laurent81784c32012-11-19 14:55:58 -08007109 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007110 size_t numtracks = mTracks.size();
7111 size_t numactive = mActiveTracks.size();
7112 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007113 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007114 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007115 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007116 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007117 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007118 RecordTrack::appendDumpHeader(result);
7119 for (size_t i = 0; i < numtracks ; ++i) {
7120 sp<RecordTrack> track = mTracks[i];
7121 if (track != 0) {
7122 bool active = mActiveTracks.indexOf(track) >= 0;
7123 if (active) {
7124 numactiveseen++;
7125 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007126 result.append(prefix);
7127 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007128 }
Eric Laurent81784c32012-11-19 14:55:58 -08007129 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007130 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007131 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
7133
Marco Nelissenb2208842014-02-07 14:00:50 -08007134 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007135 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007136 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007137 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007138 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007139 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007140 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007141 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007142 result.append(prefix);
7143 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007144 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007145 }
Eric Laurent81784c32012-11-19 14:55:58 -08007146
7147 }
7148 write(fd, result.string(), result.size());
7149}
7150
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007151void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7152{
7153 Mutex::Autolock _l(mLock);
7154 for (size_t i = 0; i < mTracks.size() ; i++) {
7155 sp<RecordTrack> track = mTracks[i];
7156 if (track != 0 && track->uid() == uid) {
7157 track->setSilenced(silenced);
7158 }
7159 }
7160}
Andy Hung73c02e42015-03-29 01:13:58 -07007161
7162void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7163{
7164 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7165 RecordThread *recordThread = (RecordThread *) threadBase.get();
7166 mRsmpInFront = recordThread->mRsmpInRear;
7167 mRsmpInUnrel = 0;
7168}
7169
7170void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7171 size_t *framesAvailable, bool *hasOverrun)
7172{
7173 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7174 RecordThread *recordThread = (RecordThread *) threadBase.get();
7175 const int32_t rear = recordThread->mRsmpInRear;
7176 const int32_t front = mRsmpInFront;
7177 const ssize_t filled = rear - front;
7178
7179 size_t framesIn;
7180 bool overrun = false;
7181 if (filled < 0) {
7182 // should not happen, but treat like a massive overrun and re-sync
7183 framesIn = 0;
7184 mRsmpInFront = rear;
7185 overrun = true;
7186 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7187 framesIn = (size_t) filled;
7188 } else {
7189 // client is not keeping up with server, but give it latest data
7190 framesIn = recordThread->mRsmpInFrames;
7191 mRsmpInFront = /* front = */ rear - framesIn;
7192 overrun = true;
7193 }
7194 if (framesAvailable != NULL) {
7195 *framesAvailable = framesIn;
7196 }
7197 if (hasOverrun != NULL) {
7198 *hasOverrun = overrun;
7199 }
7200}
7201
Eric Laurent81784c32012-11-19 14:55:58 -08007202// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007203status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007204 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007205{
Andy Hung73c02e42015-03-29 01:13:58 -07007206 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007207 if (threadBase == 0) {
7208 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007209 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007210 return NOT_ENOUGH_DATA;
7211 }
7212 RecordThread *recordThread = (RecordThread *) threadBase.get();
7213 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007214 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007215 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007216 // FIXME should not be P2 (don't want to increase latency)
7217 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007218 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007219 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007220 front &= recordThread->mRsmpInFramesP2 - 1;
7221 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007222 if (part1 > (size_t) filled) {
7223 part1 = filled;
7224 }
7225 size_t ask = buffer->frameCount;
7226 ALOG_ASSERT(ask > 0);
7227 if (part1 > ask) {
7228 part1 = ask;
7229 }
7230 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007231 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007232 buffer->raw = NULL;
7233 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007234 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007235 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007236 }
7237
Andy Hung57446612015-04-19 23:56:46 -07007238 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007239 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007240 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007241 return NO_ERROR;
7242}
7243
7244// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007245void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7246 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007247{
Glenn Kasten85948432013-08-19 12:09:05 -07007248 size_t stepCount = buffer->frameCount;
7249 if (stepCount == 0) {
7250 return;
7251 }
Andy Hung73c02e42015-03-29 01:13:58 -07007252 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7253 mRsmpInUnrel -= stepCount;
7254 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007255 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007256 buffer->frameCount = 0;
7257}
7258
Eric Laurentd8365c52017-07-16 15:27:05 -07007259void AudioFlinger::RecordThread::checkBtNrec()
7260{
7261 Mutex::Autolock _l(mLock);
7262 checkBtNrec_l();
7263}
7264
7265void AudioFlinger::RecordThread::checkBtNrec_l()
7266{
7267 // disable AEC and NS if the device is a BT SCO headset supporting those
7268 // pre processings
7269 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7270 mAudioFlinger->btNrecIsOff();
7271 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7272 for (size_t i = 0; i < mEffectChains.size(); i++) {
7273 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7274 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7275 }
7276 }
7277}
7278
Andy Hung97a893e2015-03-29 01:03:07 -07007279
Eric Laurent10351942014-05-08 18:49:52 -07007280bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7281 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007282{
7283 bool reconfig = false;
7284
Eric Laurent10351942014-05-08 18:49:52 -07007285 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007286
Eric Laurent10351942014-05-08 18:49:52 -07007287 audio_format_t reqFormat = mFormat;
7288 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007289 // 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 -07007290 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7291
7292 AudioParameter param = AudioParameter(keyValuePair);
7293 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007294
7295 // scope for AutoPark extends to end of method
7296 AutoPark<FastCapture> park(mFastCapture);
7297
Eric Laurent10351942014-05-08 18:49:52 -07007298 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7299 // channel count change can be requested. Do we mandate the first client defines the
7300 // HAL sampling rate and channel count or do we allow changes on the fly?
7301 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7302 samplingRate = value;
7303 reconfig = true;
7304 }
7305 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007306 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007307 status = BAD_VALUE;
7308 } else {
7309 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007310 reconfig = true;
7311 }
Eric Laurent10351942014-05-08 18:49:52 -07007312 }
7313 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7314 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007315 if (!audio_is_input_channel(mask) ||
7316 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007317 status = BAD_VALUE;
7318 } else {
7319 channelMask = mask;
7320 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007321 }
Eric Laurent10351942014-05-08 18:49:52 -07007322 }
7323 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7324 // do not accept frame count changes if tracks are open as the track buffer
7325 // size depends on frame count and correct behavior would not be guaranteed
7326 // if frame count is changed after track creation
7327 if (mActiveTracks.size() > 0) {
7328 status = INVALID_OPERATION;
7329 } else {
7330 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007331 }
Eric Laurent10351942014-05-08 18:49:52 -07007332 }
7333 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7334 // forward device change to effects that have requested to be
7335 // aware of attached audio device.
7336 for (size_t i = 0; i < mEffectChains.size(); i++) {
7337 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007338 }
Eric Laurent81784c32012-11-19 14:55:58 -08007339
Eric Laurent10351942014-05-08 18:49:52 -07007340 // store input device and output device but do not forward output device to audio HAL.
7341 // Note that status is ignored by the caller for output device
7342 // (see AudioFlinger::setParameters()
7343 if (audio_is_output_devices(value)) {
7344 mOutDevice = value;
7345 status = BAD_VALUE;
7346 } else {
7347 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007348 if (value != AUDIO_DEVICE_NONE) {
7349 mPrevInDevice = value;
7350 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007351 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007352 }
Eric Laurent10351942014-05-08 18:49:52 -07007353 }
7354 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7355 mAudioSource != (audio_source_t)value) {
7356 // forward device change to effects that have requested to be
7357 // aware of attached audio device.
7358 for (size_t i = 0; i < mEffectChains.size(); i++) {
7359 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007360 }
Eric Laurent10351942014-05-08 18:49:52 -07007361 mAudioSource = (audio_source_t)value;
7362 }
Glenn Kastene198c362013-08-13 09:13:36 -07007363
Eric Laurent10351942014-05-08 18:49:52 -07007364 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007365 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007366 if (status == INVALID_OPERATION) {
7367 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007368 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007369 }
7370 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007371 if (status == BAD_VALUE) {
7372 uint32_t sRate;
7373 audio_channel_mask_t channelMask;
7374 audio_format_t format;
7375 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7376 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7377 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7378 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7379 status = NO_ERROR;
7380 }
Eric Laurent81784c32012-11-19 14:55:58 -08007381 }
Eric Laurent10351942014-05-08 18:49:52 -07007382 if (status == NO_ERROR) {
7383 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007384 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007385 }
7386 }
Eric Laurent81784c32012-11-19 14:55:58 -08007387 }
Eric Laurent10351942014-05-08 18:49:52 -07007388
Eric Laurent81784c32012-11-19 14:55:58 -08007389 return reconfig;
7390}
7391
7392String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7393{
Eric Laurent81784c32012-11-19 14:55:58 -08007394 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007395 if (initCheck() == NO_ERROR) {
7396 String8 out_s8;
7397 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7398 return out_s8;
7399 }
Eric Laurent81784c32012-11-19 14:55:58 -08007400 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007401 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007402}
7403
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007404void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007405 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7406
7407 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007408
7409 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007410 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007411 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007412 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007413 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007414 desc->mChannelMask = mChannelMask;
7415 desc->mSamplingRate = mSampleRate;
7416 desc->mFormat = mFormat;
7417 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007418 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007419 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007420 break;
7421
Eric Laurent73e26b62015-04-27 16:55:58 -07007422 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007423 default:
7424 break;
7425 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007426 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007427}
7428
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007429void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007430{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007431 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7432 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007433 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007434 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007435 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007436 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7437 result = mInput->stream->getFrameSize(&mFrameSize);
7438 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7439 result = mInput->stream->getBufferSize(&mBufferSize);
7440 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007441 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007442 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7443 "mBufferSize=%lld, mFrameCount=%lld",
7444 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7445 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007446 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007447 // 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 -07007448 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007449 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007450 // A larger value should allow more old data to be read after a track calls start(),
7451 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007452 //
7453 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007454 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007455 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007456 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007457 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007458
7459 // TODO optimize audio capture buffer sizes ...
7460 // Here we calculate the size of the sliding buffer used as a source
7461 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7462 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7463 // be better to have it derived from the pipe depth in the long term.
7464 // The current value is higher than necessary. However it should not add to latency.
7465
Glenn Kasten85948432013-08-19 12:09:05 -07007466 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007467 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7468 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007469 // if posix_memalign fails, will segv here.
7470 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007471
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007472 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7473 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007474}
7475
Glenn Kasten5f972c02014-01-13 09:59:31 -08007476uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007477{
7478 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007479 uint32_t result;
7480 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7481 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007482 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007483 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007484}
7485
Eric Laurent4c415062016-06-17 16:14:16 -07007486// hasAudioSession_l() must be called with ThreadBase::mLock held
7487uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007488{
Eric Laurent81784c32012-11-19 14:55:58 -08007489 uint32_t result = 0;
7490 if (getEffectChain_l(sessionId) != 0) {
7491 result = EFFECT_SESSION;
7492 }
7493
7494 for (size_t i = 0; i < mTracks.size(); ++i) {
7495 if (sessionId == mTracks[i]->sessionId()) {
7496 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007497 if (mTracks[i]->isFastTrack()) {
7498 result |= FAST_SESSION;
7499 }
Eric Laurent81784c32012-11-19 14:55:58 -08007500 break;
7501 }
7502 }
7503
7504 return result;
7505}
7506
Glenn Kastend848eb42016-03-08 13:42:11 -08007507KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007508{
Glenn Kastend848eb42016-03-08 13:42:11 -08007509 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007510 Mutex::Autolock _l(mLock);
7511 for (size_t j = 0; j < mTracks.size(); ++j) {
7512 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007513 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007514 if (ids.indexOfKey(sessionId) < 0) {
7515 ids.add(sessionId, true);
7516 }
7517 }
7518 return ids;
7519}
7520
7521AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7522{
7523 Mutex::Autolock _l(mLock);
7524 AudioStreamIn *input = mInput;
7525 mInput = NULL;
7526 return input;
7527}
7528
7529// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007530sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007531{
7532 if (mInput == NULL) {
7533 return NULL;
7534 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007535 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007536}
7537
7538status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7539{
7540 // only one chain per input thread
7541 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007542 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007543 return INVALID_OPERATION;
7544 }
7545 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007546 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007547 chain->setInBuffer(NULL);
7548 chain->setOutBuffer(NULL);
7549
7550 checkSuspendOnAddEffectChain_l(chain);
7551
Eric Laurent1b928682014-10-02 19:41:47 -07007552 // make sure enabled pre processing effects state is communicated to the HAL as we
7553 // just moved them to a new input stream.
7554 chain->syncHalEffectsState();
7555
Eric Laurent81784c32012-11-19 14:55:58 -08007556 mEffectChains.add(chain);
7557
7558 return NO_ERROR;
7559}
7560
7561size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7562{
7563 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7564 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007565 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007566 chain.get(), mEffectChains.size(), this);
7567 if (mEffectChains.size() == 1) {
7568 mEffectChains.removeAt(0);
7569 }
7570 return 0;
7571}
7572
Eric Laurent1c333e22014-05-20 10:48:17 -07007573status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7574 audio_patch_handle_t *handle)
7575{
7576 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007577
7578 // store new device and send to effects
7579 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007580 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007581 for (size_t i = 0; i < mEffectChains.size(); i++) {
7582 mEffectChains[i]->setDevice_l(mInDevice);
7583 }
7584
Eric Laurentd8365c52017-07-16 15:27:05 -07007585 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007586
7587 // store new source and send to effects
7588 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7589 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007590 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007591 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007592 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007593 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007594
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007595 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007596 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7597 status = hwDevice->createAudioPatch(patch->num_sources,
7598 patch->sources,
7599 patch->num_sinks,
7600 patch->sinks,
7601 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007602 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007603 char *address;
7604 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7605 address = audio_device_address_to_parameter(
7606 patch->sources[0].ext.device.type,
7607 patch->sources[0].ext.device.address);
7608 } else {
7609 address = (char *)calloc(1, 1);
7610 }
7611 AudioParameter param = AudioParameter(String8(address));
7612 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007613 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007614 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007615 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007616 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007617 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007618 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007619 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007620
Eric Laurente8726fe2015-06-26 09:39:24 -07007621 if (mInDevice != mPrevInDevice) {
7622 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7623 mPrevInDevice = mInDevice;
7624 }
Eric Laurent296fb132015-05-01 11:38:42 -07007625
Eric Laurent1c333e22014-05-20 10:48:17 -07007626 return status;
7627}
7628
7629status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7630{
7631 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007632
7633 mInDevice = AUDIO_DEVICE_NONE;
7634
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007635 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007636 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7637 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007638 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007639 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007640 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007641 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007642 }
7643 return status;
7644}
7645
Eric Laurent83b88082014-06-20 18:31:16 -07007646void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7647{
7648 Mutex::Autolock _l(mLock);
7649 mTracks.add(record);
7650}
7651
7652void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7653{
7654 Mutex::Autolock _l(mLock);
7655 destroyTrack_l(record);
7656}
7657
7658void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7659{
7660 ThreadBase::getAudioPortConfig(config);
7661 config->role = AUDIO_PORT_ROLE_SINK;
7662 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7663 config->ext.mix.usecase.source = mAudioSource;
7664}
Eric Laurent1c333e22014-05-20 10:48:17 -07007665
Eric Laurent6acd1d42017-01-04 14:23:29 -08007666// ----------------------------------------------------------------------------
7667// Mmap
7668// ----------------------------------------------------------------------------
7669
7670AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7671 : mThread(thread)
7672{
Phil Burk9fabbf82017-08-03 12:02:00 -07007673 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007674}
7675
7676AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7677{
Phil Burk9fabbf82017-08-03 12:02:00 -07007678 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007679}
7680
7681status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7682 struct audio_mmap_buffer_info *info)
7683{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007684 return mThread->createMmapBuffer(minSizeFrames, info);
7685}
7686
7687status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7688{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007689 return mThread->getMmapPosition(position);
7690}
7691
Eric Laurenta54f1282017-07-01 19:39:32 -07007692status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007693 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007694
7695{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007696 return mThread->start(client, handle);
7697}
7698
7699status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7700{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007701 return mThread->stop(handle);
7702}
7703
Eric Laurent18b57012017-02-13 16:23:52 -08007704status_t AudioFlinger::MmapThreadHandle::standby()
7705{
Eric Laurent18b57012017-02-13 16:23:52 -08007706 return mThread->standby();
7707}
7708
Eric Laurent6acd1d42017-01-04 14:23:29 -08007709
7710AudioFlinger::MmapThread::MmapThread(
7711 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7712 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7713 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7714 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007715 mSessionId(AUDIO_SESSION_NONE),
7716 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007717 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7718 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007719{
Eric Laurent18b57012017-02-13 16:23:52 -08007720 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007721 readHalParameters_l();
7722}
7723
7724AudioFlinger::MmapThread::~MmapThread()
7725{
Eric Laurent18b57012017-02-13 16:23:52 -08007726 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007727}
7728
7729void AudioFlinger::MmapThread::onFirstRef()
7730{
7731 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7732}
7733
7734void AudioFlinger::MmapThread::disconnect()
7735{
7736 for (const sp<MmapTrack> &t : mActiveTracks) {
7737 stop(t->portId());
7738 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007739 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007740 if (isOutput()) {
7741 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7742 } else {
7743 AudioSystem::releaseInput(mId, mSessionId);
7744 }
7745}
7746
7747
7748void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7749 audio_stream_type_t streamType __unused,
7750 audio_session_t sessionId,
7751 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007752 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007753 audio_port_handle_t portId)
7754{
7755 mAttr = *attr;
7756 mSessionId = sessionId;
7757 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007758 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007759 mPortId = portId;
7760}
7761
7762status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7763 struct audio_mmap_buffer_info *info)
7764{
7765 if (mHalStream == 0) {
7766 return NO_INIT;
7767 }
Eric Laurent18b57012017-02-13 16:23:52 -08007768 mStandby = true;
7769 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007770 return mHalStream->createMmapBuffer(minSizeFrames, info);
7771}
7772
7773status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7774{
7775 if (mHalStream == 0) {
7776 return NO_INIT;
7777 }
7778 return mHalStream->getMmapPosition(position);
7779}
7780
Eric Laurenta54f1282017-07-01 19:39:32 -07007781status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007782 audio_port_handle_t *handle)
7783{
Eric Laurenta54f1282017-07-01 19:39:32 -07007784 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7785 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007786 if (mHalStream == 0) {
7787 return NO_INIT;
7788 }
7789
7790 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007791
Eric Laurenta54f1282017-07-01 19:39:32 -07007792 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007793 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007794 ret = mHalStream->start();
7795 if (ret != NO_ERROR) {
7796 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7797 return ret;
7798 }
Eric Laurent18b57012017-02-13 16:23:52 -08007799 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007800 return NO_ERROR;
7801 }
7802
Phil Burk81ad5ec2017-09-01 10:45:41 -07007803 if (!isOutput() && !recordingAllowed(client.packageName, client.clientPid, client.clientUid)) {
7804 return PERMISSION_DENIED;
7805 }
7806
Eric Laurenta54f1282017-07-01 19:39:32 -07007807 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7808
7809 audio_io_handle_t io = mId;
7810 if (isOutput()) {
7811 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7812 config.sample_rate = mSampleRate;
7813 config.channel_mask = mChannelMask;
7814 config.format = mFormat;
7815 audio_stream_type_t stream = streamType();
7816 audio_output_flags_t flags =
7817 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007818 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007819 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7820 mSessionId,
7821 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02007822 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07007823 client.clientUid,
7824 &config,
7825 flags,
7826 &deviceId,
7827 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007828 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007829 audio_config_base_t config;
7830 config.sample_rate = mSampleRate;
7831 config.channel_mask = mChannelMask;
7832 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007833 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007834 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7835 mSessionId,
7836 client.clientPid,
7837 client.clientUid,
7838 &config,
7839 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7840 &deviceId,
7841 &portId);
7842 }
7843 // APM should not chose a different input or output stream for the same set of attributes
7844 // and audo configuration
7845 if (ret != NO_ERROR || io != mId) {
7846 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7847 __FUNCTION__, ret, io, mId);
7848 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007849 }
7850
7851 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007852 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007853 } else {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007854 // TODO: Block recording for idle UIDs (b/72134552)
7855 bool silenced;
7856 ret = AudioSystem::startInput(mId, mSessionId, mInDevice, client.clientUid, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007857 }
7858
7859 // abort if start is rejected by audio policy manager
7860 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007861 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007862 if (mActiveTracks.size() != 0) {
7863 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007864 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007865 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007866 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007867 }
Eric Laurent18b57012017-02-13 16:23:52 -08007868 } else {
7869 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007870 }
7871 return PERMISSION_DENIED;
7872 }
7873
Eric Laurenta54f1282017-07-01 19:39:32 -07007874 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7875 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007876
7877 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007878 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007879 if (chain != 0) {
7880 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7881 chain->incTrackCnt();
7882 chain->incActiveTrackCnt();
7883 }
7884
7885 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007886 broadcast_l();
7887
Eric Laurenta54f1282017-07-01 19:39:32 -07007888 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007889
7890 return NO_ERROR;
7891}
7892
7893status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7894{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007895 ALOGV("%s handle %d", __FUNCTION__, handle);
7896
7897 if (mHalStream == 0) {
7898 return NO_INIT;
7899 }
7900
Eric Laurenta54f1282017-07-01 19:39:32 -07007901 if (handle == mPortId) {
7902 mHalStream->stop();
7903 return NO_ERROR;
7904 }
7905
Eric Laurent6acd1d42017-01-04 14:23:29 -08007906 sp<MmapTrack> track;
7907 for (const sp<MmapTrack> &t : mActiveTracks) {
7908 if (handle == t->portId()) {
7909 track = t;
7910 break;
7911 }
7912 }
7913 if (track == 0) {
7914 return BAD_VALUE;
7915 }
7916
7917 mActiveTracks.remove(track);
7918
7919 if (isOutput()) {
7920 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007921 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007922 } else {
7923 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007924 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007925 }
7926
7927 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7928 if (chain != 0) {
7929 chain->decActiveTrackCnt();
7930 chain->decTrackCnt();
7931 }
7932
7933 broadcast_l();
7934
Eric Laurent6acd1d42017-01-04 14:23:29 -08007935 return NO_ERROR;
7936}
7937
Eric Laurent18b57012017-02-13 16:23:52 -08007938status_t AudioFlinger::MmapThread::standby()
7939{
7940 ALOGV("%s", __FUNCTION__);
7941
7942 if (mHalStream == 0) {
7943 return NO_INIT;
7944 }
7945 if (mActiveTracks.size() != 0) {
7946 return INVALID_OPERATION;
7947 }
7948 mHalStream->standby();
7949 mStandby = true;
7950 releaseWakeLock();
7951 return NO_ERROR;
7952}
7953
Eric Laurent6acd1d42017-01-04 14:23:29 -08007954
7955void AudioFlinger::MmapThread::readHalParameters_l()
7956{
7957 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7958 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7959 mFormat = mHALFormat;
7960 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7961 result = mHalStream->getFrameSize(&mFrameSize);
7962 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7963 result = mHalStream->getBufferSize(&mBufferSize);
7964 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7965 mFrameCount = mBufferSize / mFrameSize;
7966}
7967
7968bool AudioFlinger::MmapThread::threadLoop()
7969{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007970 checkSilentMode_l();
7971
7972 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7973
7974 while (!exitPending())
7975 {
7976 Mutex::Autolock _l(mLock);
7977 Vector< sp<EffectChain> > effectChains;
7978
7979 if (mSignalPending) {
7980 // A signal was raised while we were unlocked
7981 mSignalPending = false;
7982 } else {
7983 if (mConfigEvents.isEmpty()) {
7984 // we're about to wait, flush the binder command buffer
7985 IPCThreadState::self()->flushCommands();
7986
7987 if (exitPending()) {
7988 break;
7989 }
7990
Eric Laurent6acd1d42017-01-04 14:23:29 -08007991 // wait until we have something to do...
7992 ALOGV("%s going to sleep", myName.string());
7993 mWaitWorkCV.wait(mLock);
7994 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007995
7996 checkSilentMode_l();
7997
7998 continue;
7999 }
8000 }
8001
8002 processConfigEvents_l();
8003
8004 processVolume_l();
8005
8006 checkInvalidTracks_l();
8007
8008 mActiveTracks.updatePowerState(this);
8009
8010 lockEffectChains_l(effectChains);
8011 for (size_t i = 0; i < effectChains.size(); i ++) {
8012 effectChains[i]->process_l();
8013 }
8014 // enable changes in effect chain
8015 unlockEffectChains(effectChains);
8016 // Effect chains will be actually deleted here if they were removed from
8017 // mEffectChains list during mixing or effects processing
8018 }
8019
8020 threadLoop_exit();
8021
8022 if (!mStandby) {
8023 threadLoop_standby();
8024 mStandby = true;
8025 }
8026
Eric Laurent6acd1d42017-01-04 14:23:29 -08008027 ALOGV("Thread %p type %d exiting", this, mType);
8028 return false;
8029}
8030
8031// checkForNewParameter_l() must be called with ThreadBase::mLock held
8032bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8033 status_t& status)
8034{
8035 AudioParameter param = AudioParameter(keyValuePair);
8036 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008037 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008038 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008039 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008040 // forward device change to effects that have requested to be
8041 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008042 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008043 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008044 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008045 }
8046 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008047 if (audio_is_output_devices(device)) {
8048 mOutDevice = device;
8049 if (!isOutput()) {
8050 sendToHal = false;
8051 }
8052 } else {
8053 mInDevice = device;
8054 if (device != AUDIO_DEVICE_NONE) {
8055 mPrevInDevice = value;
8056 }
8057 // TODO: implement and call checkBtNrec_l();
8058 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008059 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008060 if (sendToHal) {
8061 status = mHalStream->setParameters(keyValuePair);
8062 } else {
8063 status = NO_ERROR;
8064 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008065
8066 return false;
8067}
8068
8069String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8070{
8071 Mutex::Autolock _l(mLock);
8072 String8 out_s8;
8073 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8074 return out_s8;
8075 }
8076 return String8();
8077}
8078
8079void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8080 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8081
8082 desc->mIoHandle = mId;
8083
8084 switch (event) {
8085 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008086 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008087 case AUDIO_INPUT_CONFIG_CHANGED:
8088 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008089 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008090 case AUDIO_OUTPUT_CONFIG_CHANGED:
8091 desc->mPatch = mPatch;
8092 desc->mChannelMask = mChannelMask;
8093 desc->mSamplingRate = mSampleRate;
8094 desc->mFormat = mFormat;
8095 desc->mFrameCount = mFrameCount;
8096 desc->mFrameCountHAL = mFrameCount;
8097 desc->mLatency = 0;
8098 break;
8099
8100 case AUDIO_INPUT_CLOSED:
8101 case AUDIO_OUTPUT_CLOSED:
8102 default:
8103 break;
8104 }
8105 mAudioFlinger->ioConfigChanged(event, desc, pid);
8106}
8107
8108status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8109 audio_patch_handle_t *handle)
8110{
8111 status_t status = NO_ERROR;
8112
8113 // store new device and send to effects
8114 audio_devices_t type = AUDIO_DEVICE_NONE;
8115 audio_port_handle_t deviceId;
8116 if (isOutput()) {
8117 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8118 type |= patch->sinks[i].ext.device.type;
8119 }
8120 deviceId = patch->sinks[0].id;
8121 } else {
8122 type = patch->sources[0].ext.device.type;
8123 deviceId = patch->sources[0].id;
8124 }
8125
8126 for (size_t i = 0; i < mEffectChains.size(); i++) {
8127 mEffectChains[i]->setDevice_l(type);
8128 }
8129
8130 if (isOutput()) {
8131 mOutDevice = type;
8132 } else {
8133 mInDevice = type;
8134 // store new source and send to effects
8135 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8136 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8137 for (size_t i = 0; i < mEffectChains.size(); i++) {
8138 mEffectChains[i]->setAudioSource_l(mAudioSource);
8139 }
8140 }
8141 }
8142
8143 if (mAudioHwDev->supportsAudioPatches()) {
8144 status = mHalDevice->createAudioPatch(patch->num_sources,
8145 patch->sources,
8146 patch->num_sinks,
8147 patch->sinks,
8148 handle);
8149 } else {
8150 char *address;
8151 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8152 //FIXME: we only support address on first sink with HAL version < 3.0
8153 address = audio_device_address_to_parameter(
8154 patch->sinks[0].ext.device.type,
8155 patch->sinks[0].ext.device.address);
8156 } else {
8157 address = (char *)calloc(1, 1);
8158 }
8159 AudioParameter param = AudioParameter(String8(address));
8160 free(address);
8161 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8162 if (!isOutput()) {
8163 param.addInt(String8(AudioParameter::keyInputSource),
8164 (int)patch->sinks[0].ext.mix.usecase.source);
8165 }
8166 status = mHalStream->setParameters(param.toString());
8167 *handle = AUDIO_PATCH_HANDLE_NONE;
8168 }
8169
8170 if (isOutput() && mPrevOutDevice != mOutDevice) {
8171 mPrevOutDevice = type;
8172 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008173 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008174 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008175 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008176 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008177 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008178 }
8179 if (!isOutput() && mPrevInDevice != mInDevice) {
8180 mPrevInDevice = type;
8181 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008182 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008183 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008184 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008185 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008186 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008187 }
8188 return status;
8189}
8190
8191status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8192{
8193 status_t status = NO_ERROR;
8194
8195 mInDevice = AUDIO_DEVICE_NONE;
8196
8197 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8198 supportsAudioPatches : false;
8199
8200 if (supportsAudioPatches) {
8201 status = mHalDevice->releaseAudioPatch(handle);
8202 } else {
8203 AudioParameter param;
8204 param.addInt(String8(AudioParameter::keyRouting), 0);
8205 status = mHalStream->setParameters(param.toString());
8206 }
8207 return status;
8208}
8209
8210void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8211{
8212 ThreadBase::getAudioPortConfig(config);
8213 if (isOutput()) {
8214 config->role = AUDIO_PORT_ROLE_SOURCE;
8215 config->ext.mix.hw_module = mAudioHwDev->handle();
8216 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8217 } else {
8218 config->role = AUDIO_PORT_ROLE_SINK;
8219 config->ext.mix.hw_module = mAudioHwDev->handle();
8220 config->ext.mix.usecase.source = mAudioSource;
8221 }
8222}
8223
8224status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8225{
8226 audio_session_t session = chain->sessionId();
8227
8228 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8229 // Attach all tracks with same session ID to this chain.
8230 // indicate all active tracks in the chain
8231 for (const sp<MmapTrack> &track : mActiveTracks) {
8232 if (session == track->sessionId()) {
8233 chain->incTrackCnt();
8234 chain->incActiveTrackCnt();
8235 }
8236 }
8237
8238 chain->setThread(this);
8239 chain->setInBuffer(nullptr);
8240 chain->setOutBuffer(nullptr);
8241 chain->syncHalEffectsState();
8242
8243 mEffectChains.add(chain);
8244 checkSuspendOnAddEffectChain_l(chain);
8245 return NO_ERROR;
8246}
8247
8248size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8249{
8250 audio_session_t session = chain->sessionId();
8251
8252 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8253
8254 for (size_t i = 0; i < mEffectChains.size(); i++) {
8255 if (chain == mEffectChains[i]) {
8256 mEffectChains.removeAt(i);
8257 // detach all active tracks from the chain
8258 // detach all tracks with same session ID from this chain
8259 for (const sp<MmapTrack> &track : mActiveTracks) {
8260 if (session == track->sessionId()) {
8261 chain->decActiveTrackCnt();
8262 chain->decTrackCnt();
8263 }
8264 }
8265 break;
8266 }
8267 }
8268 return mEffectChains.size();
8269}
8270
8271// hasAudioSession_l() must be called with ThreadBase::mLock held
8272uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8273{
8274 uint32_t result = 0;
8275 if (getEffectChain_l(sessionId) != 0) {
8276 result = EFFECT_SESSION;
8277 }
8278
8279 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8280 sp<MmapTrack> track = mActiveTracks[i];
8281 if (sessionId == track->sessionId()) {
8282 result |= TRACK_SESSION;
8283 if (track->isFastTrack()) {
8284 result |= FAST_SESSION;
8285 }
8286 break;
8287 }
8288 }
8289
8290 return result;
8291}
8292
8293void AudioFlinger::MmapThread::threadLoop_standby()
8294{
8295 mHalStream->standby();
8296}
8297
8298void AudioFlinger::MmapThread::threadLoop_exit()
8299{
Phil Burk7dce7282017-09-27 13:51:41 -07008300 // Do not call callback->onTearDown() because it is redundant for thread exit
8301 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008302}
8303
8304status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8305{
8306 return BAD_VALUE;
8307}
8308
8309bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8310{
8311 return false;
8312}
8313
8314status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8315 const effect_descriptor_t *desc, audio_session_t sessionId)
8316{
8317 // No global effect sessions on mmap threads
8318 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8319 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8320 desc->name, mThreadName);
8321 return BAD_VALUE;
8322 }
8323
8324 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8325 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8326 desc->name);
8327 return BAD_VALUE;
8328 }
8329 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008330 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8331 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008332 return BAD_VALUE;
8333 }
8334
8335 // Only allow effects without processing load or latency
8336 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8337 return BAD_VALUE;
8338 }
8339
8340 return NO_ERROR;
8341
8342}
8343
8344void AudioFlinger::MmapThread::checkInvalidTracks_l()
8345{
8346 for (const sp<MmapTrack> &track : mActiveTracks) {
8347 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008348 sp<MmapStreamCallback> callback = mCallback.promote();
8349 if (callback != 0) {
8350 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008351 }
8352 break;
8353 }
8354 }
8355}
8356
8357void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8358{
8359 dumpInternals(fd, args);
8360 dumpTracks(fd, args);
8361 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008362 dprintf(fd, " Local log:\n");
8363 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008364}
8365
8366void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8367{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008368 dumpBase(fd, args);
8369
8370 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8371 mAttr.content_type, mAttr.usage, mAttr.source);
8372 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8373 if (mActiveTracks.size() == 0) {
8374 dprintf(fd, " No active clients\n");
8375 }
8376}
8377
8378void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8379{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008380 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008381 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008382 dprintf(fd, " %zu Tracks\n", numtracks);
8383 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008384 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008385 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008386 MmapTrack::appendDumpHeader(result);
8387 for (size_t i = 0; i < numtracks ; ++i) {
8388 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008389 result.append(prefix);
8390 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008391 }
8392 } else {
8393 dprintf(fd, "\n");
8394 }
8395 write(fd, result.string(), result.size());
8396}
8397
8398AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8399 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8400 AudioHwDevice *hwDev, AudioStreamOut *output,
8401 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8402 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8403 mStreamType(AUDIO_STREAM_MUSIC),
8404 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8405{
8406 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8407 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8408 mMasterVolume = audioFlinger->masterVolume_l();
8409 mMasterMute = audioFlinger->masterMute_l();
8410 if (mAudioHwDev) {
8411 if (mAudioHwDev->canSetMasterVolume()) {
8412 mMasterVolume = 1.0;
8413 }
8414
8415 if (mAudioHwDev->canSetMasterMute()) {
8416 mMasterMute = false;
8417 }
8418 }
8419}
8420
8421void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8422 audio_stream_type_t streamType,
8423 audio_session_t sessionId,
8424 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008425 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008426 audio_port_handle_t portId)
8427{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008428 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008429 mStreamType = streamType;
8430}
8431
8432AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8433{
8434 Mutex::Autolock _l(mLock);
8435 AudioStreamOut *output = mOutput;
8436 mOutput = NULL;
8437 return output;
8438}
8439
8440void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8441{
8442 Mutex::Autolock _l(mLock);
8443 // Don't apply master volume in SW if our HAL can do it for us.
8444 if (mAudioHwDev &&
8445 mAudioHwDev->canSetMasterVolume()) {
8446 mMasterVolume = 1.0;
8447 } else {
8448 mMasterVolume = value;
8449 }
8450}
8451
8452void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8453{
8454 Mutex::Autolock _l(mLock);
8455 // Don't apply master mute in SW if our HAL can do it for us.
8456 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8457 mMasterMute = false;
8458 } else {
8459 mMasterMute = muted;
8460 }
8461}
8462
8463void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8464{
8465 Mutex::Autolock _l(mLock);
8466 if (stream == mStreamType) {
8467 mStreamVolume = value;
8468 broadcast_l();
8469 }
8470}
8471
8472float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8473{
8474 Mutex::Autolock _l(mLock);
8475 if (stream == mStreamType) {
8476 return mStreamVolume;
8477 }
8478 return 0.0f;
8479}
8480
8481void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8482{
8483 Mutex::Autolock _l(mLock);
8484 if (stream == mStreamType) {
8485 mStreamMute= muted;
8486 broadcast_l();
8487 }
8488}
8489
8490void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8491{
8492 Mutex::Autolock _l(mLock);
8493 if (streamType == mStreamType) {
8494 for (const sp<MmapTrack> &track : mActiveTracks) {
8495 track->invalidate();
8496 }
8497 broadcast_l();
8498 }
8499}
8500
8501void AudioFlinger::MmapPlaybackThread::processVolume_l()
8502{
8503 float volume;
8504
8505 if (mMasterMute || mStreamMute) {
8506 volume = 0;
8507 } else {
8508 volume = mMasterVolume * mStreamVolume;
8509 }
8510
8511 if (volume != mHalVolFloat) {
8512 mHalVolFloat = volume;
8513
8514 // Convert volumes from float to 8.24
8515 uint32_t vol = (uint32_t)(volume * (1 << 24));
8516
8517 // Delegate volume control to effect in track effect chain if needed
8518 // only one effect chain can be present on DirectOutputThread, so if
8519 // there is one, the track is connected to it
8520 if (!mEffectChains.isEmpty()) {
8521 mEffectChains[0]->setVolume_l(&vol, &vol);
8522 volume = (float)vol / (1 << 24);
8523 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008524 // Try to use HW volume control and fall back to SW control if not implemented
8525 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8526 sp<MmapStreamCallback> callback = mCallback.promote();
8527 if (callback != 0) {
8528 int channelCount;
8529 if (isOutput()) {
8530 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8531 } else {
8532 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8533 }
8534 Vector<float> values;
8535 for (int i = 0; i < channelCount; i++) {
8536 values.add(volume);
8537 }
8538 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008539 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008540 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008541 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 }
8543 }
8544}
8545
8546void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8547{
8548 if (!mMasterMute) {
8549 char value[PROPERTY_VALUE_MAX];
8550 if (property_get("ro.audio.silent", value, "0") > 0) {
8551 char *endptr;
8552 unsigned long ul = strtoul(value, &endptr, 0);
8553 if (*endptr == '\0' && ul != 0) {
8554 ALOGD("Silence is golden");
8555 // The setprop command will not allow a property to be changed after
8556 // the first time it is set, so we don't have to worry about un-muting.
8557 setMasterMute_l(true);
8558 }
8559 }
8560 }
8561}
8562
8563void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8564{
8565 MmapThread::dumpInternals(fd, args);
8566
Glenn Kastend3bb6452016-12-05 18:14:37 -08008567 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8568 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008569 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8570}
8571
8572AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8573 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8574 AudioHwDevice *hwDev, AudioStreamIn *input,
8575 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8576 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8577 mInput(input)
8578{
8579 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8580 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8581}
8582
8583AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8584{
8585 Mutex::Autolock _l(mLock);
8586 AudioStreamIn *input = mInput;
8587 mInput = NULL;
8588 return input;
8589}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008590} // namespace android