blob: d5def4858c93aeb3a56df3d51ccf7c88a87a3cc3 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten691b02a2017-10-03 10:12:20 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x4000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800446 case MMAP:
447 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800534 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Mikhail Naganov83f04272017-02-07 10:45:09 -0800615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700616{
617 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
623 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700700 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
701 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700705 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 CreateAudioPatchConfigEventData *data =
707 (CreateAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t newDevice = getDevice();
710 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
711 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
712 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 } break;
714 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 ReleaseAudioPatchConfigEventData *data =
717 (ReleaseAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t newDevice = getDevice();
720 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
721 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
722 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 default:
Eric Laurent10351942014-05-08 18:49:52 -0700725 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
729 Mutex::Autolock _l(event->mLock);
730 if (event->mWaitStatus) {
731 event->mWaitStatus = false;
732 event->mCond.signal();
733 }
734 }
735 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
736 }
737
738 if (configChanged) {
739 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Marco Nelissenb2208842014-02-07 14:00:50 -0800743String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
744 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700745 const audio_channel_representation_t representation =
746 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700789 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800810 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
811 this, mThreadName, getTid(), type(), threadTypeToString(type()));
812
Eric Laurent81784c32012-11-19 14:55:58 -0800813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800815 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700823 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700828 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Andy Hung293558a2017-03-21 12:19:20 -0700840 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
842 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 if (locked) {
846 mLock.unlock();
847 }
848}
849
850void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000857 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800858 write(fd, buffer, strlen(buffer));
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800861 sp<EffectChain> chain = mEffectChains[i];
862 if (chain != 0) {
863 chain->dump(fd, args);
864 }
865 }
866}
867
Andy Hungdae27702016-10-31 14:01:16 -0700868void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800869{
870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700871 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872}
873
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874String16 AudioFlinger::ThreadBase::getWakeLockTag()
875{
876 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 case MIXER:
878 return String16("AudioMix");
879 case DIRECT:
880 return String16("AudioDirectOut");
881 case DUPLICATING:
882 return String16("AudioDup");
883 case RECORD:
884 return String16("AudioIn");
885 case OFFLOAD:
886 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800887 case MMAP:
888 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Andy Hungdae27702016-10-31 14:01:16 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700900 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
901 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700904 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (status == NO_ERROR) {
907 mWakeLockToken = binder;
908 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Wei Jia3f273d12015-11-24 09:06:49 -0800911
Andy Hung3f0c9022016-01-15 17:49:46 -0800912 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800913 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
914 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800915}
916
917void AudioFlinger::ThreadBase::releaseWakeLock()
918{
919 Mutex::Autolock _l(mLock);
920 releaseWakeLock_l();
921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock_l()
924{
Andy Hung3f0c9022016-01-15 17:49:46 -0800925 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800934}
935
936void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700937 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938 // use checkService() to avoid blocking if power service is not up yet
939 sp<IBinder> binder =
940 defaultServiceManager()->checkService(String16("power"));
941 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800942 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 } else {
944 mPowerManager = interface_cast<IPowerManager>(binder);
945 binder->linkToDeath(mDeathRecipient);
946 }
947 }
948}
949
Andy Hungd01b0f12016-11-07 16:10:30 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700952
953#if !LOG_NDEBUG
954 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800955 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700956 s << uid << " ";
957 }
958 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
959#endif
960
Andy Hung438e7572015-12-14 15:51:17 -0800961 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
962 if (mSystemReady) {
963 ALOGE("no wake lock to update, but system ready!");
964 } else {
965 ALOGW("no wake lock to update, system not ready yet");
966 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 return;
968 }
969 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800970 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
971 status_t status = mPowerManager->updateWakeLockUids(
972 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
973 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800974 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 }
976}
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978void AudioFlinger::ThreadBase::clearPowerManager()
979{
980 Mutex::Autolock _l(mLock);
981 releaseWakeLock_l();
982 mPowerManager.clear();
983}
984
Glenn Kasten0f11b512014-01-31 16:18:54 -0800985void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 sp<ThreadBase> thread = mThread.promote();
988 if (thread != 0) {
989 thread->clearPowerManager();
990 }
991 ALOGW("power manager service died !!!");
992}
993
Eric Laurent81784c32012-11-19 14:55:58 -0800994void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800995 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001020 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001035 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001104 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
Eric Laurent4c415062016-06-17 16:14:16 -07001123// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1124status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1125 const effect_descriptor_t *desc, audio_session_t sessionId)
1126{
1127 // No global effect sessions on record threads
1128 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1129 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1130 desc->name, mThreadName);
1131 return BAD_VALUE;
1132 }
1133 // only pre processing effects on record thread
1134 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1135 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001139
1140 // always allow effects without processing load or latency
1141 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1142 return NO_ERROR;
1143 }
1144
Eric Laurent4c415062016-06-17 16:14:16 -07001145 audio_input_flags_t flags = mInput->flags;
1146 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1147 if (flags & AUDIO_INPUT_FLAG_RAW) {
1148 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1153 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
1161// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1162status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1163 const effect_descriptor_t *desc, audio_session_t sessionId)
1164{
1165 // no preprocessing on playback threads
1166 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1167 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1168 " thread %s", desc->name, mThreadName);
1169 return BAD_VALUE;
1170 }
1171
Eric Laurent3e4de772017-07-16 16:55:08 -07001172 // always allow effects without processing load or latency
1173 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1174 return NO_ERROR;
1175 }
1176
Eric Laurent4c415062016-06-17 16:14:16 -07001177 switch (mType) {
1178 case MIXER: {
1179 // Reject any effect on mixer multichannel sinks.
1180 // TODO: fix both format and multichannel issues with effects.
1181 if (mChannelCount != FCC_2) {
1182 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1183 " thread %s", desc->name, mChannelCount, mThreadName);
1184 return BAD_VALUE;
1185 }
1186 audio_output_flags_t flags = mOutput->flags;
1187 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1188 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1189 // global effects are applied only to non fast tracks if they are SW
1190 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1191 break;
1192 }
1193 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1194 // only post processing on output stage session
1195 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1196 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1197 " on output stage session", desc->name);
1198 return BAD_VALUE;
1199 }
1200 } else {
1201 // no restriction on effects applied on non fast tracks
1202 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1203 break;
1204 }
1205 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001270 status_t *status,
1271 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
1273 sp<EffectModule> effect;
1274 sp<EffectHandle> handle;
1275 status_t lStatus;
1276 sp<EffectChain> chain;
1277 bool chainCreated = false;
1278 bool effectCreated = false;
1279 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001280 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001281
1282 lStatus = initCheck();
1283 if (lStatus != NO_ERROR) {
1284 ALOGW("createEffect_l() Audio driver not initialized.");
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1289
1290 { // scope for mLock
1291 Mutex::Autolock _l(mLock);
1292
Eric Laurent4c415062016-06-17 16:14:16 -07001293 lStatus = checkEffectCompatibility_l(desc, sessionId);
1294 if (lStatus != NO_ERROR) {
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // check for existing effect chain with the requested audio session
1299 chain = getEffectChain_l(sessionId);
1300 if (chain == 0) {
1301 // create a new chain for this session
1302 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1303 chain = new EffectChain(this, sessionId);
1304 addEffectChain_l(chain);
1305 chain->setStrategy(getStrategyForSession_l(sessionId));
1306 chainCreated = true;
1307 } else {
1308 effect = chain->getEffectFromDesc_l(desc);
1309 }
1310
1311 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1312
1313 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001315 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001316 lStatus = AudioSystem::registerEffect(
1317 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectRegistered = true;
1322 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectCreated = true;
1328
1329 effect->setDevice(mOutDevice);
1330 effect->setDevice(mInDevice);
1331 effect->setMode(mAudioFlinger->getMode());
1332 effect->setAudioSource(mAudioSource);
1333 }
1334 // create effect handle and connect it to effect module
1335 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001336 lStatus = handle->initCheck();
1337 if (lStatus == OK) {
1338 lStatus = effect->addHandle(handle.get());
1339 }
Eric Laurent81784c32012-11-19 14:55:58 -08001340 if (enabled != NULL) {
1341 *enabled = (int)effect->isEnabled();
1342 }
1343 }
1344
1345Exit:
1346 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1347 Mutex::Autolock _l(mLock);
1348 if (effectCreated) {
1349 chain->removeEffect_l(effect);
1350 }
1351 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001352 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001353 }
1354 if (chainCreated) {
1355 removeEffectChain_l(chain);
1356 }
1357 handle.clear();
1358 }
1359
Glenn Kasten9156ef32013-08-06 15:39:08 -07001360 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 return handle;
1362}
1363
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001364void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1365 bool unpinIfLast)
1366{
1367 bool remove = false;
1368 sp<EffectModule> effect;
1369 {
1370 Mutex::Autolock _l(mLock);
1371
1372 effect = handle->effect().promote();
1373 if (effect == 0) {
1374 return;
1375 }
1376 // restore suspended effects if the disconnected handle was enabled and the last one.
1377 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1378 if (remove) {
1379 removeEffect_l(effect, true);
1380 }
1381 }
1382 if (remove) {
1383 mAudioFlinger->updateOrphanEffectChains(effect);
1384 AudioSystem::unregisterEffect(effect->id());
1385 if (handle->enabled()) {
1386 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1387 }
1388 }
1389}
1390
Glenn Kastend848eb42016-03-08 13:42:11 -08001391sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1392 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001393{
1394 Mutex::Autolock _l(mLock);
1395 return getEffect_l(sessionId, effectId);
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1403}
1404
1405// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1406// PlaybackThread::mLock held
1407status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1408{
1409 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 bool chainCreated = false;
1413
Eric Laurent5baf2af2013-09-12 17:37:00 -07001414 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001415 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001416 this, effect->desc().name, effect->desc().flags);
1417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 if (chain == 0) {
1419 // create a new chain for this session
1420 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1421 chain = new EffectChain(this, sessionId);
1422 addEffectChain_l(chain);
1423 chain->setStrategy(getStrategyForSession_l(sessionId));
1424 chainCreated = true;
1425 }
1426 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1427
1428 if (chain->getEffectFromId_l(effect->id()) != 0) {
1429 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1430 this, effect->desc().name, chain.get());
1431 return BAD_VALUE;
1432 }
1433
Eric Laurent5baf2af2013-09-12 17:37:00 -07001434 effect->setOffloaded(mType == OFFLOAD, mId);
1435
Eric Laurent81784c32012-11-19 14:55:58 -08001436 status_t status = chain->addEffect_l(effect);
1437 if (status != NO_ERROR) {
1438 if (chainCreated) {
1439 removeEffectChain_l(chain);
1440 }
1441 return status;
1442 }
1443
1444 effect->setDevice(mOutDevice);
1445 effect->setDevice(mInDevice);
1446 effect->setMode(mAudioFlinger->getMode());
1447 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001448
Eric Laurent81784c32012-11-19 14:55:58 -08001449 return NO_ERROR;
1450}
1451
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001454 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t desc = effect->desc();
1456 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1457 detachAuxEffect_l(effect->id());
1458 }
1459
1460 sp<EffectChain> chain = effect->chain().promote();
1461 if (chain != 0) {
1462 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001463 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001464 removeEffectChain_l(chain);
1465 }
1466 } else {
1467 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1468 }
1469}
1470
1471void AudioFlinger::ThreadBase::lockEffectChains_l(
1472 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1473{
1474 effectChains = mEffectChains;
1475 for (size_t i = 0; i < mEffectChains.size(); i++) {
1476 mEffectChains[i]->lock();
1477 }
1478}
1479
1480void AudioFlinger::ThreadBase::unlockEffectChains(
1481 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1482{
1483 for (size_t i = 0; i < effectChains.size(); i++) {
1484 effectChains[i]->unlock();
1485 }
1486}
1487
Glenn Kastend848eb42016-03-08 13:42:11 -08001488sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 Mutex::Autolock _l(mLock);
1491 return getEffectChain_l(sessionId);
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1495 const
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 size_t size = mEffectChains.size();
1498 for (size_t i = 0; i < size; i++) {
1499 if (mEffectChains[i]->sessionId() == sessionId) {
1500 return mEffectChains[i];
1501 }
1502 }
1503 return 0;
1504}
1505
1506void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1507{
1508 Mutex::Autolock _l(mLock);
1509 size_t size = mEffectChains.size();
1510 for (size_t i = 0; i < size; i++) {
1511 mEffectChains[i]->setMode_l(mode);
1512 }
1513}
1514
Eric Laurent83b88082014-06-20 18:31:16 -07001515void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1516{
1517 config->type = AUDIO_PORT_TYPE_MIX;
1518 config->ext.mix.handle = mId;
1519 config->sample_rate = mSampleRate;
1520 config->format = mFormat;
1521 config->channel_mask = mChannelMask;
1522 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1523 AUDIO_PORT_CONFIG_FORMAT;
1524}
1525
Eric Laurent72e3f392015-05-20 14:43:50 -07001526void AudioFlinger::ThreadBase::systemReady()
1527{
1528 Mutex::Autolock _l(mLock);
1529 if (mSystemReady) {
1530 return;
1531 }
1532 mSystemReady = true;
1533
1534 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1535 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1536 }
1537 mPendingConfigEvents.clear();
1538}
1539
Andy Hungdae27702016-10-31 14:01:16 -07001540template <typename T>
1541ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1542 ssize_t index = mActiveTracks.indexOf(track);
1543 if (index >= 0) {
1544 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1545 return index;
1546 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001547 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001548 mActiveTracksGeneration++;
1549 mLatestActiveTrack = track;
1550 ++mBatteryCounter[track->uid()].second;
1551 return mActiveTracks.add(track);
1552}
1553
1554template <typename T>
1555ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1556 ssize_t index = mActiveTracks.remove(track);
1557 if (index < 0) {
1558 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1559 return index;
1560 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001561 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001562 mActiveTracksGeneration++;
1563 --mBatteryCounter[track->uid()].second;
1564 // mLatestActiveTrack is not cleared even if is the same as track.
1565 return index;
1566}
1567
1568template <typename T>
1569void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1570 for (const sp<T> &track : mActiveTracks) {
1571 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001572 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001573 }
1574 mLastActiveTracksGeneration = mActiveTracksGeneration;
1575 mActiveTracks.clear();
1576 mLatestActiveTrack.clear();
1577 mBatteryCounter.clear();
1578}
1579
1580template <typename T>
1581void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1582 sp<ThreadBase> thread, bool force) {
1583 // Updates ActiveTracks client uids to the thread wakelock.
1584 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1585 thread->updateWakeLockUids_l(getWakeLockUids());
1586 mLastActiveTracksGeneration = mActiveTracksGeneration;
1587 }
1588
1589 // Updates BatteryNotifier uids
1590 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1591 const uid_t uid = it->first;
1592 ssize_t &previous = it->second.first;
1593 ssize_t &current = it->second.second;
1594 if (current > 0) {
1595 if (previous == 0) {
1596 BatteryNotifier::getInstance().noteStartAudio(uid);
1597 }
1598 previous = current;
1599 ++it;
1600 } else if (current == 0) {
1601 if (previous > 0) {
1602 BatteryNotifier::getInstance().noteStopAudio(uid);
1603 }
1604 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1605 } else /* (current < 0) */ {
1606 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1607 }
1608 }
1609}
Eric Laurent83b88082014-06-20 18:31:16 -07001610
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001611template <typename T>
1612void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1613 const char *funcName, const sp<T> &track) const {
1614 if (mLocalLog != nullptr) {
1615 String8 result;
1616 track->appendDump(result, false /* active */);
1617 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1618 }
1619}
1620
Eric Laurent6acd1d42017-01-04 14:23:29 -08001621void AudioFlinger::ThreadBase::broadcast_l()
1622{
1623 // Thread could be blocked waiting for async
1624 // so signal it to handle state changes immediately
1625 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1626 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1627 mSignalPending = true;
1628 mWaitWorkCV.broadcast();
1629}
1630
Eric Laurent81784c32012-11-19 14:55:58 -08001631// ----------------------------------------------------------------------------
1632// Playback
1633// ----------------------------------------------------------------------------
1634
1635AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1636 AudioStreamOut* output,
1637 audio_io_handle_t id,
1638 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001639 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001640 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001641 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001642 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001643 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001644 mMixerBuffer(NULL),
1645 mMixerBufferSize(0),
1646 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1647 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001648 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001649 mEffectBuffer(NULL),
1650 mEffectBufferSize(0),
1651 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1652 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001653 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001654 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001655 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001656 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // mStreamTypes[] initialized in constructor body
1658 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001659 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mMixerStatus(MIXER_IDLE),
1661 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001662 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 mBytesRemaining(0),
1664 mCurrentWriteLength(0),
1665 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001666 mWriteAckSequence(0),
1667 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001668 mScreenState(AudioFlinger::mScreenState),
1669 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001670 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001671 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1672 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001673{
Glenn Kastend7dca052015-03-05 16:05:54 -08001674 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1675 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001676
1677 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1678 // it would be safer to explicitly pass initial masterVolume/masterMute as
1679 // parameter.
1680 //
1681 // If the HAL we are using has support for master volume or master mute,
1682 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1683 // and the mute set to false).
1684 mMasterVolume = audioFlinger->masterVolume_l();
1685 mMasterMute = audioFlinger->masterMute_l();
1686 if (mOutput && mOutput->audioHwDev) {
1687 if (mOutput->audioHwDev->canSetMasterVolume()) {
1688 mMasterVolume = 1.0;
1689 }
1690
1691 if (mOutput->audioHwDev->canSetMasterMute()) {
1692 mMasterMute = false;
1693 }
1694 }
1695
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001696 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001697
Eric Laurent223fd5c2014-11-11 13:43:36 -08001698 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001699 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001700 stream = (audio_stream_type_t) (stream + 1)) {
1701 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1702 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1703 }
Eric Laurent81784c32012-11-19 14:55:58 -08001704}
1705
1706AudioFlinger::PlaybackThread::~PlaybackThread()
1707{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001708 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001709 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001710 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001711 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001712}
1713
1714void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1715{
1716 dumpInternals(fd, args);
1717 dumpTracks(fd, args);
1718 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001719 dprintf(fd, " Local log:\n");
1720 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001721}
1722
Glenn Kasten0f11b512014-01-31 16:18:54 -08001723void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001724{
Eric Laurent81784c32012-11-19 14:55:58 -08001725 String8 result;
1726
Marco Nelissenb2208842014-02-07 14:00:50 -08001727 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001728 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1729 const stream_type_t *st = &mStreamTypes[i];
1730 if (i > 0) {
1731 result.appendFormat(", ");
1732 }
1733 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1734 if (st->mute) {
1735 result.append("M");
1736 }
1737 }
1738 result.append("\n");
1739 write(fd, result.string(), result.length());
1740 result.clear();
1741
Eric Laurent81784c32012-11-19 14:55:58 -08001742 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1743 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001744 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001745 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001746
1747 size_t numtracks = mTracks.size();
1748 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001749 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001750 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001751 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001752 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001753 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001754 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001755 Track::appendDumpHeader(result);
1756 for (size_t i = 0; i < numtracks; ++i) {
1757 sp<Track> track = mTracks[i];
1758 if (track != 0) {
1759 bool active = mActiveTracks.indexOf(track) >= 0;
1760 if (active) {
1761 numactiveseen++;
1762 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001763 result.append(prefix);
1764 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001765 }
1766 }
1767 } else {
1768 result.append("\n");
1769 }
1770 if (numactiveseen != numactive) {
1771 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001772 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001773 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001774 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775 Track::appendDumpHeader(result);
1776 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001777 sp<Track> track = mActiveTracks[i];
1778 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001779 result.append(prefix);
1780 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001781 }
1782 }
1783 }
1784
1785 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001786}
1787
1788void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1789{
Glenn Kasten44182c22015-03-05 17:12:23 -08001790 dumpBase(fd, args);
1791
Elliott Hughes87cebad2014-05-22 10:14:43 -07001792 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001793 dprintf(fd, " Last write occurred (msecs): %llu\n",
1794 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001795 dprintf(fd, " Total writes: %d\n", mNumWrites);
1796 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1797 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1798 dprintf(fd, " Suspend count: %d\n", mSuspended);
1799 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1800 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1801 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1802 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001803 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001804 AudioStreamOut *output = mOutput;
1805 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001806 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1807 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001808 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1809 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1810 if (mPipeSink.get() != nullptr) {
1811 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1812 }
1813 if (output != nullptr) {
1814 dprintf(fd, " Hal stream dump:\n");
1815 (void)output->stream->dump(fd);
1816 }
Eric Laurent81784c32012-11-19 14:55:58 -08001817}
1818
1819// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001820
1821void AudioFlinger::PlaybackThread::onFirstRef()
1822{
Glenn Kastend7dca052015-03-05 16:05:54 -08001823 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001824}
1825
1826// ThreadBase virtuals
1827void AudioFlinger::PlaybackThread::preExit()
1828{
1829 ALOGV(" preExit()");
1830 // FIXME this is using hard-coded strings but in the future, this functionality will be
1831 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001832 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1833 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001834}
1835
1836// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1837sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1838 const sp<AudioFlinger::Client>& client,
1839 audio_stream_type_t streamType,
Eric Laurent21da6472017-11-09 16:29:26 -08001840 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001841 audio_format_t format,
1842 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001843 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001844 size_t *pNotificationFrameCount,
1845 uint32_t notificationsPerBuffer,
1846 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001847 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001848 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001849 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001850 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001851 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001852 status_t *status,
1853 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001854{
Glenn Kasten74935e42013-12-19 08:56:45 -08001855 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001856 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001857 sp<Track> track;
1858 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001859 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001860 audio_output_flags_t requestedFlags = *flags;
1861
1862 if (*pSampleRate == 0) {
1863 *pSampleRate = mSampleRate;
1864 }
1865 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001866
1867 // special case for FAST flag considered OK if fast mixer is present
1868 if (hasFastMixer()) {
1869 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1870 }
1871
1872 // Check if requested flags are compatible with output stream flags
1873 if ((*flags & outputFlags) != *flags) {
1874 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1875 *flags, outputFlags);
1876 *flags = (audio_output_flags_t)(*flags & outputFlags);
1877 }
Eric Laurent81784c32012-11-19 14:55:58 -08001878
Eric Laurent81784c32012-11-19 14:55:58 -08001879 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001880 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001881 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001882 // PCM data
1883 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001884 // TODO: extract as a data library function that checks that a computationally
1885 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001886 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001887 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1888 (channelMask == AUDIO_CHANNEL_OUT_MONO
1889 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001890 // hardware sample rate
1891 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001892 // normal mixer has an associated fast mixer
1893 hasFastMixer() &&
1894 // there are sufficient fast track slots available
1895 (mFastTrackAvailMask != 0)
1896 // FIXME test that MixerThread for this fast track has a capable output HAL
1897 // FIXME add a permission test also?
1898 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001899 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1900 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001901 // read the fast track multiplier property the first time it is needed
1902 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1903 if (ok != 0) {
1904 ALOGE("%s pthread_once failed: %d", __func__, ok);
1905 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001906 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001907 }
Eric Laurent4c415062016-06-17 16:14:16 -07001908
1909 // check compatibility with audio effects.
1910 { // scope for mLock
1911 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001912 for (audio_session_t session : {
1913 AUDIO_SESSION_OUTPUT_STAGE,
1914 AUDIO_SESSION_OUTPUT_MIX,
1915 sessionId,
1916 }) {
1917 sp<EffectChain> chain = getEffectChain_l(session);
1918 if (chain.get() != nullptr) {
1919 audio_output_flags_t old = *flags;
1920 chain->checkOutputFlagCompatibility(flags);
1921 if (old != *flags) {
1922 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1923 (int)session, (int)old, (int)*flags);
1924 }
Eric Laurent4c415062016-06-17 16:14:16 -07001925 }
1926 }
1927 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001928 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001929 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1930 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001931 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001932 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1933 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001934 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001935 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001936 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001937 audio_is_linear_pcm(format),
1938 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001939 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001940 }
1941 }
Eric Laurent21da6472017-11-09 16:29:26 -08001942
1943 if (!audio_has_proportional_frames(format)) {
1944 if (sharedBuffer != 0) {
1945 // Same comment as below about ignoring frameCount parameter for set()
1946 frameCount = sharedBuffer->size();
1947 } else if (frameCount == 0) {
1948 frameCount = mNormalFrameCount;
1949 }
1950 if (notificationFrameCount != frameCount) {
1951 notificationFrameCount = frameCount;
1952 }
1953 } else if (sharedBuffer != 0) {
1954 // FIXME: Ensure client side memory buffers need
1955 // not have additional alignment beyond sample
1956 // (e.g. 16 bit stereo accessed as 32 bit frame).
1957 size_t alignment = audio_bytes_per_sample(format);
1958 if (alignment & 1) {
1959 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1960 alignment = 1;
1961 }
1962 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1963 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1964 if (channelCount > 1) {
1965 // More than 2 channels does not require stronger alignment than stereo
1966 alignment <<= 1;
1967 }
1968 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
1969 ALOGE("Invalid buffer alignment: address %p, channel count %u",
1970 sharedBuffer->pointer(), channelCount);
1971 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001972 goto Exit;
1973 }
Eric Laurent21da6472017-11-09 16:29:26 -08001974
1975 // When initializing a shared buffer AudioTrack via constructors,
1976 // there's no frameCount parameter.
1977 // But when initializing a shared buffer AudioTrack via set(),
1978 // there _is_ a frameCount parameter. We silently ignore it.
1979 frameCount = sharedBuffer->size() / frameSize;
1980 } else {
1981 size_t minFrameCount = 0;
1982 // For fast tracks we try to respect the application's request for notifications per buffer.
1983 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
1984 if (notificationsPerBuffer > 0) {
1985 // Avoid possible arithmetic overflow during multiplication.
1986 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
1987 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
1988 notificationsPerBuffer, mFrameCount);
1989 } else {
1990 minFrameCount = mFrameCount * notificationsPerBuffer;
1991 }
1992 }
1993 } else {
1994 // For normal PCM streaming tracks, update minimum frame count.
1995 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
1996 // cover audio hardware latency.
1997 // This is probably too conservative, but legacy application code may depend on it.
1998 // If you change this calculation, also review the start threshold which is related.
1999 uint32_t latencyMs = latency_l();
2000 if (latencyMs == 0) {
2001 ALOGE("Error when retrieving output stream latency");
2002 lStatus = UNKNOWN_ERROR;
2003 goto Exit;
2004 }
2005
2006 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2007 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2008
Eric Laurent81784c32012-11-19 14:55:58 -08002009 }
Eric Laurent21da6472017-11-09 16:29:26 -08002010 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002011 frameCount = minFrameCount;
2012 }
Eric Laurent81784c32012-11-19 14:55:58 -08002013 }
Eric Laurent21da6472017-11-09 16:29:26 -08002014
2015 // Make sure that application is notified with sufficient margin before underrun.
2016 // The client can divide the AudioTrack buffer into sub-buffers,
2017 // and expresses its desire to server as the notification frame count.
2018 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2019 size_t maxNotificationFrames;
2020 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2021 // notify every HAL buffer, regardless of the size of the track buffer
2022 maxNotificationFrames = mFrameCount;
2023 } else {
2024 // For normal tracks, use at least double-buffering if no sample rate conversion,
2025 // or at least triple-buffering if there is sample rate conversion
2026 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2027 maxNotificationFrames = frameCount / nBuffering;
2028 // If client requested a fast track but this was denied, then use the smaller maximum.
2029 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2030 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2031 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2032 maxNotificationFrames = maxNotificationFramesFastDenied;
2033 }
2034 }
2035 }
2036 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2037 if (notificationFrameCount == 0) {
2038 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2039 maxNotificationFrames, frameCount);
2040 } else {
2041 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2042 notificationFrameCount, maxNotificationFrames, frameCount);
2043 }
2044 notificationFrameCount = maxNotificationFrames;
2045 }
2046 }
2047
Glenn Kasten74935e42013-12-19 08:56:45 -08002048 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002049 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002050
Glenn Kastenc3df8382014-03-13 15:05:25 -07002051 switch (mType) {
2052
2053 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002054 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002055 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002056 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2057 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002058 sampleRate, format, channelMask, mOutput, mFormat);
2059 lStatus = BAD_VALUE;
2060 goto Exit;
2061 }
2062 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002063 break;
2064
2065 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002066 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002067 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2068 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002069 sampleRate, format, channelMask, mOutput, mFormat);
2070 lStatus = BAD_VALUE;
2071 goto Exit;
2072 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002073 break;
2074
2075 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002076 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002077 ALOGE("createTrack_l() Bad parameter: format %#x \""
2078 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002079 format, mOutput, mFormat);
2080 lStatus = BAD_VALUE;
2081 goto Exit;
2082 }
Andy Hungcd044842014-08-07 11:04:34 -07002083 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002084 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2085 lStatus = BAD_VALUE;
2086 goto Exit;
2087 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002088 break;
2089
Eric Laurent81784c32012-11-19 14:55:58 -08002090 }
2091
2092 lStatus = initCheck();
2093 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002094 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002095 goto Exit;
2096 }
2097
2098 { // scope for mLock
2099 Mutex::Autolock _l(mLock);
2100
2101 // all tracks in same audio session must share the same routing strategy otherwise
2102 // conflicts will happen when tracks are moved from one output to another by audio policy
2103 // manager
2104 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2105 for (size_t i = 0; i < mTracks.size(); ++i) {
2106 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002107 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002108 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2109 if (sessionId == t->sessionId() && strategy != actual) {
2110 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2111 strategy, actual);
2112 lStatus = BAD_VALUE;
2113 goto Exit;
2114 }
2115 }
2116 }
2117
Glenn Kastend79072e2016-01-06 08:41:20 -08002118 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002119 channelMask, frameCount,
2120 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002121 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002122
Glenn Kasten03003332013-08-06 15:40:54 -07002123 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2124 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002125 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002126 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002127 goto Exit;
2128 }
2129 mTracks.add(track);
2130
2131 sp<EffectChain> chain = getEffectChain_l(sessionId);
2132 if (chain != 0) {
2133 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2134 track->setMainBuffer(chain->inBuffer());
2135 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2136 chain->incTrackCnt();
2137 }
2138
Eric Laurent05067782016-06-01 18:27:28 -07002139 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002140 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2141 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2142 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002143 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002144 }
2145 }
2146
2147 lStatus = NO_ERROR;
2148
2149Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002150 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002151 return track;
2152}
2153
2154uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2155{
2156 return latency;
2157}
2158
2159uint32_t AudioFlinger::PlaybackThread::latency() const
2160{
2161 Mutex::Autolock _l(mLock);
2162 return latency_l();
2163}
2164uint32_t AudioFlinger::PlaybackThread::latency_l() const
2165{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002166 uint32_t latency;
2167 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2168 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002169 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002170 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002171}
2172
2173void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2174{
2175 Mutex::Autolock _l(mLock);
2176 // Don't apply master volume in SW if our HAL can do it for us.
2177 if (mOutput && mOutput->audioHwDev &&
2178 mOutput->audioHwDev->canSetMasterVolume()) {
2179 mMasterVolume = 1.0;
2180 } else {
2181 mMasterVolume = value;
2182 }
2183}
2184
2185void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2186{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002187 if (isDuplicating()) {
2188 return;
2189 }
Eric Laurent81784c32012-11-19 14:55:58 -08002190 Mutex::Autolock _l(mLock);
2191 // Don't apply master mute in SW if our HAL can do it for us.
2192 if (mOutput && mOutput->audioHwDev &&
2193 mOutput->audioHwDev->canSetMasterMute()) {
2194 mMasterMute = false;
2195 } else {
2196 mMasterMute = muted;
2197 }
2198}
2199
2200void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2201{
2202 Mutex::Autolock _l(mLock);
2203 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002204 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002205}
2206
2207void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2208{
2209 Mutex::Autolock _l(mLock);
2210 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002211 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002212}
2213
2214float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2215{
2216 Mutex::Autolock _l(mLock);
2217 return mStreamTypes[stream].volume;
2218}
2219
2220// addTrack_l() must be called with ThreadBase::mLock held
2221status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2222{
2223 status_t status = ALREADY_EXISTS;
2224
Eric Laurent81784c32012-11-19 14:55:58 -08002225 if (mActiveTracks.indexOf(track) < 0) {
2226 // the track is newly added, make sure it fills up all its
2227 // buffers before playing. This is to ensure the client will
2228 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002229 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002230 TrackBase::track_state state = track->mState;
2231 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002232 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002233 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002234 mLock.lock();
2235 // abort track was stopped/paused while we released the lock
2236 if (state != track->mState) {
2237 if (status == NO_ERROR) {
2238 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002239 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002240 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002241 mLock.lock();
2242 }
2243 return INVALID_OPERATION;
2244 }
2245 // abort if start is rejected by audio policy manager
2246 if (status != NO_ERROR) {
2247 return PERMISSION_DENIED;
2248 }
2249#ifdef ADD_BATTERY_DATA
2250 // to track the speaker usage
2251 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2252#endif
2253 }
2254
Eric Laurent51716182016-02-29 18:00:56 -08002255 // set retry count for buffer fill
2256 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002257 if (track->isStopping_1()) {
2258 track->mRetryCount = kMaxTrackStopRetriesOffload;
2259 } else {
2260 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2261 }
2262 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002263 } else {
2264 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002265 track->mFillingUpStatus =
2266 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002267 }
2268
Eric Laurent81784c32012-11-19 14:55:58 -08002269 track->mResetDone = false;
2270 track->mPresentationCompleteFrames = 0;
2271 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002272 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2273 if (chain != 0) {
2274 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2275 track->sessionId());
2276 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002277 }
2278
2279 status = NO_ERROR;
2280 }
2281
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002282 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002283 return status;
2284}
2285
Eric Laurentbfb1b832013-01-07 09:53:42 -08002286bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002287{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002288 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002289 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002290 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2291 track->mState = TrackBase::STOPPED;
2292 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002293 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002294 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002297
2298 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002299}
2300
2301void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2302{
2303 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002304
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002305 String8 result;
2306 track->appendDump(result, false /* active */);
2307 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002308
Eric Laurent81784c32012-11-19 14:55:58 -08002309 mTracks.remove(track);
2310 deleteTrackName_l(track->name());
2311 // redundant as track is about to be destroyed, for dumpsys only
2312 track->mName = -1;
2313 if (track->isFastTrack()) {
2314 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002315 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002316 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2317 mFastTrackAvailMask |= 1 << index;
2318 // redundant as track is about to be destroyed, for dumpsys only
2319 track->mFastIndex = -1;
2320 }
2321 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2322 if (chain != 0) {
2323 chain->decTrackCnt();
2324 }
2325}
2326
2327String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2328{
Eric Laurent81784c32012-11-19 14:55:58 -08002329 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002330 String8 out_s8;
2331 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2332 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002333 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002334 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002335}
2336
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002337void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002338 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2339 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002340
Eric Laurent73e26b62015-04-27 16:55:58 -07002341 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002342
2343 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002344 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002345 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002346 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002347 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002348 desc->mChannelMask = mChannelMask;
2349 desc->mSamplingRate = mSampleRate;
2350 desc->mFormat = mFormat;
2351 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002352 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002353 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002354 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002355 break;
2356
Eric Laurent73e26b62015-04-27 16:55:58 -07002357 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002358 default:
2359 break;
2360 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002361 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002362}
2363
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002364void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002366 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002367}
2368
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002369void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002371 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372}
2373
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002374void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002375{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002376 mCallbackThread->setAsyncError();
2377}
2378
Eric Laurent3b4529e2013-09-05 18:09:19 -07002379void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380{
2381 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002382 // reject out of sequence requests
2383 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2384 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385 mWaitWorkCV.signal();
2386 }
2387}
2388
Eric Laurent3b4529e2013-09-05 18:09:19 -07002389void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390{
2391 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002392 // reject out of sequence requests
2393 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2394 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002395 mWaitWorkCV.signal();
2396 }
2397}
2398
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002399void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002400{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002401 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002402 mSampleRate = mOutput->getSampleRate();
2403 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002404 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002405 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002406 }
Andy Hung9a592762014-07-21 21:56:01 -07002407 if ((mType == MIXER || mType == DUPLICATING)
2408 && !isValidPcmSinkChannelMask(mChannelMask)) {
2409 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2410 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002411 }
Andy Hunge5412692014-05-16 11:25:07 -07002412 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002413
2414 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002415 status_t result = mOutput->stream->getFormat(&mHALFormat);
2416 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002417 // Get format from the shim, which will be different than the HAL format
2418 // if playing compressed audio over HDMI passthrough.
2419 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002420 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002421 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002422 }
Andy Hung6146c082014-03-18 11:56:15 -07002423 if ((mType == MIXER || mType == DUPLICATING)
2424 && !isValidPcmSinkFormat(mFormat)) {
2425 LOG_FATAL("HAL format %#x not supported for mixed output",
2426 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002427 }
Phil Burk062e67a2015-02-11 13:40:50 -08002428 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002429 result = mOutput->stream->getBufferSize(&mBufferSize);
2430 LOG_ALWAYS_FATAL_IF(result != OK,
2431 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002432 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002433 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002434 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002435 mFrameCount);
2436 }
2437
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002438 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2439 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002440 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002441 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002442 }
2443 }
2444
Eric Laurentd1f69b02014-12-15 14:33:13 -08002445 mHwSupportsPause = false;
2446 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002447 bool supportsPause = false, supportsResume = false;
2448 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2449 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002450 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002451 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002452 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002453 } else if (supportsResume) {
2454 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002455 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002456 }
2457 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002458 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2459 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2460 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002461
Andy Hungfbfc3952015-01-15 13:33:51 -08002462 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2463 // For best precision, we use float instead of the associated output
2464 // device format (typically PCM 16 bit).
2465
2466 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2467 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2468 mBufferSize = mFrameSize * mFrameCount;
2469
2470 // TODO: We currently use the associated output device channel mask and sample rate.
2471 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2472 // (if a valid mask) to avoid premature downmix.
2473 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2474 // instead of the output device sample rate to avoid loss of high frequency information.
2475 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2476 }
2477
Andy Hung09a50072014-02-27 14:30:47 -08002478 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002479 double multiplier = 1.0;
2480 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2481 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002482 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2483 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002484
Eric Laurent81784c32012-11-19 14:55:58 -08002485 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2486 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2487 maxNormalFrameCount = maxNormalFrameCount & ~15;
2488 if (maxNormalFrameCount < minNormalFrameCount) {
2489 maxNormalFrameCount = minNormalFrameCount;
2490 }
2491 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2492 if (multiplier <= 1.0) {
2493 multiplier = 1.0;
2494 } else if (multiplier <= 2.0) {
2495 if (2 * mFrameCount <= maxNormalFrameCount) {
2496 multiplier = 2.0;
2497 } else {
2498 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2499 }
2500 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002501 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002502 }
2503 }
2504 mNormalFrameCount = multiplier * mFrameCount;
2505 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002506 if (mType == MIXER || mType == DUPLICATING) {
2507 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2508 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002509 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002510 mNormalFrameCount);
2511
Andy Hung08fb1742015-05-31 23:22:10 -07002512 // Check if we want to throttle the processing to no more than 2x normal rate
2513 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002514 mThreadThrottleTimeMs = 0;
2515 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002516 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2517
Andy Hung010a1a12014-03-13 13:57:33 -07002518 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2519 // Originally this was int16_t[] array, need to remove legacy implications.
2520 free(mSinkBuffer);
2521 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002522 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2523 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2524 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002525 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002526
Andy Hung69aed5f2014-02-25 17:24:40 -08002527 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2528 // drives the output.
2529 free(mMixerBuffer);
2530 mMixerBuffer = NULL;
2531 if (mMixerBufferEnabled) {
2532 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2533 mMixerBufferSize = mNormalFrameCount * mChannelCount
2534 * audio_bytes_per_sample(mMixerBufferFormat);
2535 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2536 }
Andy Hung98ef9782014-03-04 14:46:50 -08002537 free(mEffectBuffer);
2538 mEffectBuffer = NULL;
2539 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002540 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002541 mEffectBufferSize = mNormalFrameCount * mChannelCount
2542 * audio_bytes_per_sample(mEffectBufferFormat);
2543 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2544 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002545
Eric Laurent81784c32012-11-19 14:55:58 -08002546 // force reconfiguration of effect chains and engines to take new buffer size and audio
2547 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002548 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002549 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2550 // matter.
2551 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2552 Vector< sp<EffectChain> > effectChains = mEffectChains;
2553 for (size_t i = 0; i < effectChains.size(); i ++) {
2554 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2555 }
2556}
2557
2558
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002559status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002560{
2561 if (halFrames == NULL || dspFrames == NULL) {
2562 return BAD_VALUE;
2563 }
2564 Mutex::Autolock _l(mLock);
2565 if (initCheck() != NO_ERROR) {
2566 return INVALID_OPERATION;
2567 }
Andy Hung818e7a32016-02-16 18:08:07 -08002568 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002569 *halFrames = framesWritten;
2570
2571 if (isSuspended()) {
2572 // return an estimation of rendered frames when the output is suspended
2573 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002574 *dspFrames = (uint32_t)
2575 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002576 return NO_ERROR;
2577 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002578 status_t status;
2579 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002580 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002581 *dspFrames = (size_t)frames;
2582 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002583 }
2584}
2585
Eric Laurent4c415062016-06-17 16:14:16 -07002586// hasAudioSession_l() must be called with ThreadBase::mLock held
2587uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002588{
Eric Laurent81784c32012-11-19 14:55:58 -08002589 uint32_t result = 0;
2590 if (getEffectChain_l(sessionId) != 0) {
2591 result = EFFECT_SESSION;
2592 }
2593
2594 for (size_t i = 0; i < mTracks.size(); ++i) {
2595 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002596 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002597 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002598 if (track->isFastTrack()) {
2599 result |= FAST_SESSION;
2600 }
Eric Laurent81784c32012-11-19 14:55:58 -08002601 break;
2602 }
2603 }
2604
2605 return result;
2606}
2607
Glenn Kastend848eb42016-03-08 13:42:11 -08002608uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002609{
2610 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2611 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2612 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2613 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2614 }
2615 for (size_t i = 0; i < mTracks.size(); i++) {
2616 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002617 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002618 return AudioSystem::getStrategyForStream(track->streamType());
2619 }
2620 }
2621 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2622}
2623
2624
Phil Burk062e67a2015-02-11 13:40:50 -08002625AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002626{
2627 Mutex::Autolock _l(mLock);
2628 return mOutput;
2629}
2630
Phil Burk062e67a2015-02-11 13:40:50 -08002631AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002632{
2633 Mutex::Autolock _l(mLock);
2634 AudioStreamOut *output = mOutput;
2635 mOutput = NULL;
2636 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2637 // must push a NULL and wait for ack
2638 mOutputSink.clear();
2639 mPipeSink.clear();
2640 mNormalSink.clear();
2641 return output;
2642}
2643
2644// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002645sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002646{
2647 if (mOutput == NULL) {
2648 return NULL;
2649 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002650 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002651}
2652
2653uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2654{
2655 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2656}
2657
2658status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2659{
2660 if (!isValidSyncEvent(event)) {
2661 return BAD_VALUE;
2662 }
2663
2664 Mutex::Autolock _l(mLock);
2665
2666 for (size_t i = 0; i < mTracks.size(); ++i) {
2667 sp<Track> track = mTracks[i];
2668 if (event->triggerSession() == track->sessionId()) {
2669 (void) track->setSyncEvent(event);
2670 return NO_ERROR;
2671 }
2672 }
2673
2674 return NAME_NOT_FOUND;
2675}
2676
2677bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2678{
2679 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2680}
2681
2682void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2683 const Vector< sp<Track> >& tracksToRemove)
2684{
2685 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002686 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002687 for (size_t i = 0 ; i < count ; i++) {
2688 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002689 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002690 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002691 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692#ifdef ADD_BATTERY_DATA
2693 // to track the speaker usage
2694 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2695#endif
2696 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002697 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002698 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002699 }
Eric Laurent81784c32012-11-19 14:55:58 -08002700 }
2701 }
2702 }
Eric Laurent81784c32012-11-19 14:55:58 -08002703}
2704
2705void AudioFlinger::PlaybackThread::checkSilentMode_l()
2706{
2707 if (!mMasterMute) {
2708 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002709 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2710 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2711 return;
2712 }
Eric Laurent81784c32012-11-19 14:55:58 -08002713 if (property_get("ro.audio.silent", value, "0") > 0) {
2714 char *endptr;
2715 unsigned long ul = strtoul(value, &endptr, 0);
2716 if (*endptr == '\0' && ul != 0) {
2717 ALOGD("Silence is golden");
2718 // The setprop command will not allow a property to be changed after
2719 // the first time it is set, so we don't have to worry about un-muting.
2720 setMasterMute_l(true);
2721 }
2722 }
2723 }
2724}
2725
2726// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002727ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002728{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002729 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002730 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002731 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002732 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002733
2734 // If an NBAIO sink is present, use it to write the normal mixer's submix
2735 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002736
Andy Hung010a1a12014-03-13 13:57:33 -07002737 const size_t count = mBytesRemaining / mFrameSize;
2738
Simon Wilson2d590962012-11-29 15:18:50 -08002739 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002740 // update the setpoint when AudioFlinger::mScreenState changes
2741 uint32_t screenState = AudioFlinger::mScreenState;
2742 if (screenState != mScreenState) {
2743 mScreenState = screenState;
2744 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2745 if (pipe != NULL) {
2746 pipe->setAvgFrames((mScreenState & 1) ?
2747 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2748 }
2749 }
Andy Hung010a1a12014-03-13 13:57:33 -07002750 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002751 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002752 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002753 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002754 } else {
2755 bytesWritten = framesWritten;
2756 }
2757 // otherwise use the HAL / AudioStreamOut directly
2758 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002759 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002760
Eric Laurentbfb1b832013-01-07 09:53:42 -08002761 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002762 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2763 mWriteAckSequence += 2;
2764 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002765 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002766 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002767 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002768 // FIXME We should have an implementation of timestamps for direct output threads.
2769 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002770 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002771
Eric Laurentbfb1b832013-01-07 09:53:42 -08002772 if (mUseAsyncWrite &&
2773 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2774 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002775 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002776 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002777 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002778 }
Eric Laurent81784c32012-11-19 14:55:58 -08002779 }
2780
Eric Laurent81784c32012-11-19 14:55:58 -08002781 mNumWrites++;
2782 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002783 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002784 return bytesWritten;
2785}
2786
2787void AudioFlinger::PlaybackThread::threadLoop_drain()
2788{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002789 bool supportsDrain = false;
2790 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2792 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002793 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2794 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002795 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002796 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002797 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002798 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002799 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002800 }
2801}
2802
2803void AudioFlinger::PlaybackThread::threadLoop_exit()
2804{
Eric Laurent275e8e92014-11-30 15:14:47 -08002805 {
2806 Mutex::Autolock _l(mLock);
2807 for (size_t i = 0; i < mTracks.size(); i++) {
2808 sp<Track> track = mTracks[i];
2809 track->invalidate();
2810 }
Andy Hungdae27702016-10-31 14:01:16 -07002811 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2812 // After we exit there are no more track changes sent to BatteryNotifier
2813 // because that requires an active threadLoop.
2814 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2815 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002816 }
Eric Laurent81784c32012-11-19 14:55:58 -08002817}
2818
2819/*
2820The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002821 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002822 - mActiveSleepTimeUs from activeSleepTimeUs()
2823 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002824 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2825 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002826 - maxPeriod from frame count and sample rate (MIXER only)
2827
2828The parameters that affect these derived values are:
2829 - frame count
2830 - frame size
2831 - sample rate
2832 - device type: A2DP or not
2833 - device latency
2834 - format: PCM or not
2835 - active sleep time
2836 - idle sleep time
2837*/
2838
2839void AudioFlinger::PlaybackThread::cacheParameters_l()
2840{
Andy Hung25c2dac2014-02-27 14:56:00 -08002841 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002842 mActiveSleepTimeUs = activeSleepTimeUs();
2843 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002844
2845 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2846 // truncating audio when going to standby.
2847 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2848 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2849 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2850 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2851 }
2852 }
Eric Laurent81784c32012-11-19 14:55:58 -08002853}
2854
Eric Laurent13084622016-05-17 10:51:49 -07002855bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002856{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002857 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002858 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002859 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002860 size_t size = mTracks.size();
2861 for (size_t i = 0; i < size; i++) {
2862 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002863 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002864 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002865 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002866 }
2867 }
Eric Laurent13084622016-05-17 10:51:49 -07002868 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002869}
2870
Haynes Mathew George05317d22016-05-03 16:34:26 -07002871void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2872{
2873 Mutex::Autolock _l(mLock);
2874 invalidateTracks_l(streamType);
2875}
2876
Eric Laurent81784c32012-11-19 14:55:58 -08002877status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2878{
Glenn Kastend848eb42016-03-08 13:42:11 -08002879 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002880 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2881 status_t result = EffectBufferHalInterface::mirror(
2882 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2883 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2884 &halInBuffer);
2885 if (result != OK) return result;
2886 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002887 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002888 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002889 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002890 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002891 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002892 if (mType != DIRECT) {
2893 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002894 status_t result = EffectBufferHalInterface::allocate(
rago94a1ee82017-07-21 15:11:02 -07002895 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002896 &halInBuffer);
2897 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002898#ifdef FLOAT_EFFECT_CHAIN
2899 buffer = halInBuffer->audioBuffer()->f32;
2900#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08002901 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07002902#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08002903 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2904 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002905 }
2906
2907 // Attach all tracks with same session ID to this chain.
2908 for (size_t i = 0; i < mTracks.size(); ++i) {
2909 sp<Track> track = mTracks[i];
2910 if (session == track->sessionId()) {
2911 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2912 buffer);
2913 track->setMainBuffer(buffer);
2914 chain->incTrackCnt();
2915 }
2916 }
2917
2918 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002919 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002920 if (session == track->sessionId()) {
2921 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2922 chain->incActiveTrackCnt();
2923 }
2924 }
2925 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002926 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002927 chain->setInBuffer(halInBuffer);
2928 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002929 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002930 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002931 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2932 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002933 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002934 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002935 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002936 // Effect chain for other sessions are inserted at beginning of effect
2937 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002938 // sessions is not important.
2939 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2940 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2941 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002942 size_t size = mEffectChains.size();
2943 size_t i = 0;
2944 for (i = 0; i < size; i++) {
2945 if (mEffectChains[i]->sessionId() < session) {
2946 break;
2947 }
2948 }
2949 mEffectChains.insertAt(chain, i);
2950 checkSuspendOnAddEffectChain_l(chain);
2951
2952 return NO_ERROR;
2953}
2954
2955size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2956{
Glenn Kastend848eb42016-03-08 13:42:11 -08002957 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002958
2959 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2960
2961 for (size_t i = 0; i < mEffectChains.size(); i++) {
2962 if (chain == mEffectChains[i]) {
2963 mEffectChains.removeAt(i);
2964 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002965 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002966 if (session == track->sessionId()) {
2967 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2968 chain.get(), session);
2969 chain->decActiveTrackCnt();
2970 }
2971 }
2972
2973 // detach all tracks with same session ID from this chain
2974 for (size_t i = 0; i < mTracks.size(); ++i) {
2975 sp<Track> track = mTracks[i];
2976 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07002977 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002978 chain->decTrackCnt();
2979 }
2980 }
2981 break;
2982 }
2983 }
2984 return mEffectChains.size();
2985}
2986
2987status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002988 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002989{
2990 Mutex::Autolock _l(mLock);
2991 return attachAuxEffect_l(track, EffectId);
2992}
2993
2994status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002995 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002996{
2997 status_t status = NO_ERROR;
2998
2999 if (EffectId == 0) {
3000 track->setAuxBuffer(0, NULL);
3001 } else {
3002 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3003 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3004 if (effect != 0) {
3005 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3006 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3007 } else {
3008 status = INVALID_OPERATION;
3009 }
3010 } else {
3011 status = BAD_VALUE;
3012 }
3013 }
3014 return status;
3015}
3016
3017void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3018{
3019 for (size_t i = 0; i < mTracks.size(); ++i) {
3020 sp<Track> track = mTracks[i];
3021 if (track->auxEffectId() == effectId) {
3022 attachAuxEffect_l(track, 0);
3023 }
3024 }
3025}
3026
3027bool AudioFlinger::PlaybackThread::threadLoop()
3028{
Glenn Kasten388d5712017-04-07 14:38:41 -07003029 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003030
Eric Laurent81784c32012-11-19 14:55:58 -08003031 Vector< sp<Track> > tracksToRemove;
3032
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003033 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003034 nsecs_t lastWriteFinished = -1; // time last server write completed
3035 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003036
3037 // MIXER
3038 nsecs_t lastWarning = 0;
3039
3040 // DUPLICATING
3041 // FIXME could this be made local to while loop?
3042 writeFrames = 0;
3043
3044 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003045 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003046
3047 if (mType == MIXER) {
3048 sleepTimeShift = 0;
3049 }
3050
3051 CpuStats cpuStats;
3052 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3053
3054 acquireWakeLock();
3055
Glenn Kasteneef598c2017-04-03 14:41:13 -07003056 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3057 // thread associated with this PlaybackThread.
3058 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3059 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003060 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3061 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003062 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003063 const char *logString = NULL;
3064
rago1bb90822017-05-02 18:31:48 -07003065 // Estimated time for next buffer to be written to hal. This is used only on
3066 // suspended mode (for now) to help schedule the wait time until next iteration.
3067 nsecs_t timeLoopNextNs = 0;
3068
Eric Laurent664539d2013-09-23 18:24:31 -07003069 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003070
Eric Laurent81784c32012-11-19 14:55:58 -08003071 while (!exitPending())
3072 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003073 // Log merge requests are performed during AudioFlinger binder transactions, but
3074 // that does not cover audio playback. It's requested here for that reason.
3075 mAudioFlinger->requestLogMerge();
3076
Eric Laurent81784c32012-11-19 14:55:58 -08003077 cpuStats.sample(myName);
3078
3079 Vector< sp<EffectChain> > effectChains;
3080
Eric Laurent81784c32012-11-19 14:55:58 -08003081 { // scope for mLock
3082
3083 Mutex::Autolock _l(mLock);
3084
Eric Laurent021cf962014-05-13 10:18:14 -07003085 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003086
Glenn Kasteneef598c2017-04-03 14:41:13 -07003087 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003088 if (logString != NULL) {
3089 mNBLogWriter->logTimestamp();
3090 mNBLogWriter->log(logString);
3091 logString = NULL;
3092 }
3093
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003094 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003095 // and associate with the sink frames written out. We need
3096 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003097 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003098 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003099 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003100 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003101 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003102 ExtendedTimestamp timestamp; // use private copy to fetch
3103 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003104
3105 // We keep track of the last valid kernel position in case we are in underrun
3106 // and the normal mixer period is the same as the fast mixer period, or there
3107 // is some error from the HAL.
3108 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3109 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3110 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3111 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3112 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3113
3114 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3115 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3116 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3117 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003118 }
3119
3120 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3121 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003122 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003123 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003124 }
3125
Andy Hung818e7a32016-02-16 18:08:07 -08003126 // copy over kernel info
3127 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003128 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3129 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003130 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3131 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003132 }
3133 // mFramesWritten for non-offloaded tracks are contiguous
3134 // even after standby() is called. This is useful for the track frame
3135 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003136 bool serverLocationUpdate = false;
3137 if (mFramesWritten != lastFramesWritten) {
3138 serverLocationUpdate = true;
3139 lastFramesWritten = mFramesWritten;
3140 }
3141 // Only update timestamps if there is a meaningful change.
3142 // Either the kernel timestamp must be valid or we have written something.
3143 if (kernelLocationUpdate || serverLocationUpdate) {
3144 if (serverLocationUpdate) {
3145 // use the time before we called the HAL write - it is a bit more accurate
3146 // to when the server last read data than the current time here.
3147 //
3148 // If we haven't written anything, mLastWriteTime will be -1
3149 // and we use systemTime().
3150 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3151 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3152 ? systemTime() : mLastWriteTime;
3153 }
Andy Hungdae27702016-10-31 14:01:16 -07003154
3155 for (const sp<Track> &t : mActiveTracks) {
3156 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003157 t->updateTrackFrameInfo(
3158 t->mAudioTrackServerProxy->framesReleased(),
3159 mFramesWritten,
3160 mTimestamp);
3161 }
Andy Hunge10393e2015-06-12 13:59:33 -07003162 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003163 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003164#if 0
3165 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003166 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003167 timespec ts;
3168 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003169 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003170 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003171 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003172 }
3173 ++z;
3174#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003175 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176 if (mSignalPending) {
3177 // A signal was raised while we were unlocked
3178 mSignalPending = false;
3179 } else if (waitingAsyncCallback_l()) {
3180 if (exitPending()) {
3181 break;
3182 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003183 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003184 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003185 releaseWakeLock_l();
3186 released = true;
3187 }
Andy Hung10cbff12017-02-21 17:30:14 -08003188
3189 const int64_t waitNs = computeWaitTimeNs_l();
3190 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3191 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3192 if (status == TIMED_OUT) {
3193 mSignalPending = true; // if timeout recheck everything
3194 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003195 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003196 if (released) {
3197 acquireWakeLock_l();
3198 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003199 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3200 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003201
3202 continue;
3203 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003204 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003205 isSuspended()) {
3206 // put audio hardware into standby after short delay
3207 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003208
3209 threadLoop_standby();
3210
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003211 // This is where we go into standby
3212 if (!mStandby) {
3213 LOG_AUDIO_STATE();
3214 }
Eric Laurent81784c32012-11-19 14:55:58 -08003215 mStandby = true;
3216 }
3217
3218 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3219 // we're about to wait, flush the binder command buffer
3220 IPCThreadState::self()->flushCommands();
3221
3222 clearOutputTracks();
3223
3224 if (exitPending()) {
3225 break;
3226 }
3227
3228 releaseWakeLock_l();
3229 // wait until we have something to do...
3230 ALOGV("%s going to sleep", myName.string());
3231 mWaitWorkCV.wait(mLock);
3232 ALOGV("%s waking up", myName.string());
3233 acquireWakeLock_l();
3234
3235 mMixerStatus = MIXER_IDLE;
3236 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3237 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003238 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003239 checkSilentMode_l();
3240
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003241 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3242 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003243 if (mType == MIXER) {
3244 sleepTimeShift = 0;
3245 }
3246
3247 continue;
3248 }
3249 }
Eric Laurent81784c32012-11-19 14:55:58 -08003250 // mMixerStatusIgnoringFastTracks is also updated internally
3251 mMixerStatus = prepareTracks_l(&tracksToRemove);
3252
Andy Hungdae27702016-10-31 14:01:16 -07003253 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003254
Eric Laurent81784c32012-11-19 14:55:58 -08003255 // prevent any changes in effect chain list and in each effect chain
3256 // during mixing and effect process as the audio buffers could be deleted
3257 // or modified if an effect is created or deleted
3258 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003259 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003260
Eric Laurentbfb1b832013-01-07 09:53:42 -08003261 if (mBytesRemaining == 0) {
3262 mCurrentWriteLength = 0;
3263 if (mMixerStatus == MIXER_TRACKS_READY) {
3264 // threadLoop_mix() sets mCurrentWriteLength
3265 threadLoop_mix();
3266 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3267 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003268 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 // must be written to HAL
3270 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003271 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003272 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003273 }
3274 }
Andy Hung98ef9782014-03-04 14:46:50 -08003275 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003276 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003277 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3278 // or mSinkBuffer (if there are no effects).
3279 //
3280 // This is done pre-effects computation; if effects change to
3281 // support higher precision, this needs to move.
3282 //
3283 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003284 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003285 if (mMixerBufferValid) {
3286 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3287 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3288
Andy Hung2ddee192015-12-18 17:34:44 -08003289 // mono blend occurs for mixer threads only (not direct or offloaded)
3290 // and is handled here if we're going directly to the sink.
3291 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003292 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3293 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003294 }
3295
Andy Hung98ef9782014-03-04 14:46:50 -08003296 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3297 mNormalFrameCount * mChannelCount);
3298 }
3299
Eric Laurentbfb1b832013-01-07 09:53:42 -08003300 mBytesRemaining = mCurrentWriteLength;
3301 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003302 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3303 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3304 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3305 mBytesWritten += mBytesRemaining;
3306 mFramesWritten += framesRemaining;
3307 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003308 mBytesRemaining = 0;
3309 }
Eric Laurent81784c32012-11-19 14:55:58 -08003310
Eric Laurentbfb1b832013-01-07 09:53:42 -08003311 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003312 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003313 for (size_t i = 0; i < effectChains.size(); i ++) {
3314 effectChains[i]->process_l();
3315 }
Eric Laurent81784c32012-11-19 14:55:58 -08003316 }
3317 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003318 // Process effect chains for offloaded thread even if no audio
3319 // was read from audio track: process only updates effect state
3320 // and thus does have to be synchronized with audio writes but may have
3321 // to be called while waiting for async write callback
3322 if (mType == OFFLOAD) {
3323 for (size_t i = 0; i < effectChains.size(); i ++) {
3324 effectChains[i]->process_l();
3325 }
3326 }
Eric Laurent81784c32012-11-19 14:55:58 -08003327
Andy Hung98ef9782014-03-04 14:46:50 -08003328 // Only if the Effects buffer is enabled and there is data in the
3329 // Effects buffer (buffer valid), we need to
3330 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003331 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003332 if (mEffectBufferValid) {
3333 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003334
3335 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003336 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3337 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003338 }
3339
Andy Hung98ef9782014-03-04 14:46:50 -08003340 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3341 mNormalFrameCount * mChannelCount);
3342 }
3343
Eric Laurent81784c32012-11-19 14:55:58 -08003344 // enable changes in effect chain
3345 unlockEffectChains(effectChains);
3346
Eric Laurentbfb1b832013-01-07 09:53:42 -08003347 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003348 // mSleepTimeUs == 0 means we must write to audio hardware
3349 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003350 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003351 // We save lastWriteFinished here, as previousLastWriteFinished,
3352 // for throttling. On thread start, previousLastWriteFinished will be
3353 // set to -1, which properly results in no throttling after the first write.
3354 nsecs_t previousLastWriteFinished = lastWriteFinished;
3355 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003356 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003357 // FIXME rewrite to reduce number of system calls
3358 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003359 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003360 lastWriteFinished = systemTime();
3361 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003362 if (ret < 0) {
3363 mBytesRemaining = 0;
3364 } else {
3365 mBytesWritten += ret;
3366 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003367 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003368 }
3369 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3370 (mMixerStatus == MIXER_DRAIN_ALL)) {
3371 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003372 }
Andy Hung08fb1742015-05-31 23:22:10 -07003373 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003374 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003375 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003376 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003377 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003378 ATRACE_NAME("underrun");
3379 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003380 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003381 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003382 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003383 }
Andy Hung08fb1742015-05-31 23:22:10 -07003384
3385 if (mThreadThrottle
3386 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3387 && ret > 0) { // we wrote something
3388 // Limit MixerThread data processing to no more than twice the
3389 // expected processing rate.
3390 //
3391 // This helps prevent underruns with NuPlayer and other applications
3392 // which may set up buffers that are close to the minimum size, or use
3393 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3394 //
3395 // The throttle smooths out sudden large data drains from the device,
3396 // e.g. when it comes out of standby, which often causes problems with
3397 // (1) mixer threads without a fast mixer (which has its own warm-up)
3398 // (2) minimum buffer sized tracks (even if the track is full,
3399 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003400 //
3401 // Total time spent in last processing cycle equals time spent in
3402 // 1. threadLoop_write, as well as time spent in
3403 // 2. threadLoop_mix (significant for heavy mixing, especially
3404 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003405
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003406 // it's OK if deltaMs (and deltaNs) is an overestimate.
3407 nsecs_t deltaNs;
3408 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3409 __builtin_sub_overflow(
3410 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3411 const int32_t deltaMs = deltaNs / 1000000;
3412
Ivan Lozanoea04d392017-11-07 14:37:07 -08003413 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003414 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3415 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003416 // notify of throttle start on verbose log
3417 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3418 "mixer(%p) throttle begin:"
3419 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003420 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003421 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003422 // Throttle must be attributed to the previous mixer loop's write time
3423 // to allow back-to-back throttling.
3424 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003425 } else {
3426 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3427 if (diff > 0) {
3428 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003429 // but prevent spamming for bluetooth
3430 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3431 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003432 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3433 }
Andy Hung08fb1742015-05-31 23:22:10 -07003434 }
3435 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003436 }
Eric Laurent81784c32012-11-19 14:55:58 -08003437
Eric Laurentbfb1b832013-01-07 09:53:42 -08003438 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003439 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003440 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003441 // suspended requires accurate metering of sleep time.
3442 if (isSuspended()) {
3443 // advance by expected sleepTime
3444 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3445 const nsecs_t nowNs = systemTime();
3446
3447 // compute expected next time vs current time.
3448 // (negative deltas are treated as delays).
3449 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3450 if (deltaNs < -kMaxNextBufferDelayNs) {
3451 // Delays longer than the max allowed trigger a reset.
3452 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3453 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3454 timeLoopNextNs = nowNs + deltaNs;
3455 } else if (deltaNs < 0) {
3456 // Delays within the max delay allowed: zero the delta/sleepTime
3457 // to help the system catch up in the next iteration(s)
3458 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3459 deltaNs = 0;
3460 }
3461 // update sleep time (which is >= 0)
3462 mSleepTimeUs = deltaNs / 1000;
3463 }
Eric Laurente93cc032016-05-05 10:15:10 -07003464 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3465 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003466 }
Glenn Kastene7754022014-10-31 12:11:26 -07003467 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003468 }
Eric Laurent81784c32012-11-19 14:55:58 -08003469 }
3470
3471 // Finally let go of removed track(s), without the lock held
3472 // since we can't guarantee the destructors won't acquire that
3473 // same lock. This will also mutate and push a new fast mixer state.
3474 threadLoop_removeTracks(tracksToRemove);
3475 tracksToRemove.clear();
3476
3477 // FIXME I don't understand the need for this here;
3478 // it was in the original code but maybe the
3479 // assignment in saveOutputTracks() makes this unnecessary?
3480 clearOutputTracks();
3481
3482 // Effect chains will be actually deleted here if they were removed from
3483 // mEffectChains list during mixing or effects processing
3484 effectChains.clear();
3485
3486 // FIXME Note that the above .clear() is no longer necessary since effectChains
3487 // is now local to this block, but will keep it for now (at least until merge done).
3488 }
3489
Eric Laurentbfb1b832013-01-07 09:53:42 -08003490 threadLoop_exit();
3491
Eric Laurentcf817a22014-08-04 20:36:31 -07003492 if (!mStandby) {
3493 threadLoop_standby();
3494 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003495 }
3496
3497 releaseWakeLock();
3498
3499 ALOGV("Thread %p type %d exiting", this, mType);
3500 return false;
3501}
3502
Eric Laurentbfb1b832013-01-07 09:53:42 -08003503// removeTracks_l() must be called with ThreadBase::mLock held
3504void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3505{
3506 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003507 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003508 for (size_t i=0 ; i<count ; i++) {
3509 const sp<Track>& track = tracksToRemove.itemAt(i);
3510 mActiveTracks.remove(track);
3511 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3512 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3513 if (chain != 0) {
3514 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3515 track->sessionId());
3516 chain->decActiveTrackCnt();
3517 }
3518 if (track->isTerminated()) {
3519 removeTrack_l(track);
3520 }
3521 }
3522 }
3523
3524}
Eric Laurent81784c32012-11-19 14:55:58 -08003525
Eric Laurentaccc1472013-09-20 09:36:34 -07003526status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3527{
3528 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003529 ExtendedTimestamp ets;
3530 status_t status = mNormalSink->getTimestamp(ets);
3531 if (status == NO_ERROR) {
3532 status = ets.getBestTimestamp(&timestamp);
3533 }
3534 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003535 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003536 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003537 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003538 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003539 timestamp.mPosition = (uint32_t)position64;
3540 return NO_ERROR;
3541 }
3542 }
3543 return INVALID_OPERATION;
3544}
Eric Laurent1c333e22014-05-20 10:48:17 -07003545
Eric Laurent054d9d32015-04-24 08:48:48 -07003546status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3547 audio_patch_handle_t *handle)
3548{
Andy Hungf60abce2016-08-26 11:37:54 -07003549 status_t status;
3550 if (property_get_bool("af.patch_park", false /* default_value */)) {
3551 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3552 // or if HAL does not properly lock against access.
3553 AutoPark<FastMixer> park(mFastMixer);
3554 status = PlaybackThread::createAudioPatch_l(patch, handle);
3555 } else {
3556 status = PlaybackThread::createAudioPatch_l(patch, handle);
3557 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003558 return status;
3559}
3560
Eric Laurent1c333e22014-05-20 10:48:17 -07003561status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3562 audio_patch_handle_t *handle)
3563{
3564 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003565
3566 // store new device and send to effects
3567 audio_devices_t type = AUDIO_DEVICE_NONE;
3568 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3569 type |= patch->sinks[i].ext.device.type;
3570 }
3571
3572#ifdef ADD_BATTERY_DATA
3573 // when changing the audio output device, call addBatteryData to notify
3574 // the change
3575 if (mOutDevice != type) {
3576 uint32_t params = 0;
3577 // check whether speaker is on
3578 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3579 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003580 }
3581
Eric Laurent054d9d32015-04-24 08:48:48 -07003582 audio_devices_t deviceWithoutSpeaker
3583 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3584 // check if any other device (except speaker) is on
3585 if (type & deviceWithoutSpeaker) {
3586 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3587 }
3588
3589 if (params != 0) {
3590 addBatteryData(params);
3591 }
3592 }
3593#endif
3594
3595 for (size_t i = 0; i < mEffectChains.size(); i++) {
3596 mEffectChains[i]->setDevice_l(type);
3597 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003598
3599 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3600 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3601 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003602 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003603 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003604
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003605 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003606 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3607 status = hwDevice->createAudioPatch(patch->num_sources,
3608 patch->sources,
3609 patch->num_sinks,
3610 patch->sinks,
3611 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003612 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003613 char *address;
3614 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3615 //FIXME: we only support address on first sink with HAL version < 3.0
3616 address = audio_device_address_to_parameter(
3617 patch->sinks[0].ext.device.type,
3618 patch->sinks[0].ext.device.address);
3619 } else {
3620 address = (char *)calloc(1, 1);
3621 }
3622 AudioParameter param = AudioParameter(String8(address));
3623 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003624 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003625 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003626 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003627 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003628 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003629 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003630 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3631 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003632 return status;
3633}
3634
Eric Laurent054d9d32015-04-24 08:48:48 -07003635status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3636{
Andy Hungf60abce2016-08-26 11:37:54 -07003637 status_t status;
3638 if (property_get_bool("af.patch_park", false /* default_value */)) {
3639 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3640 // or if HAL does not properly lock against access.
3641 AutoPark<FastMixer> park(mFastMixer);
3642 status = PlaybackThread::releaseAudioPatch_l(handle);
3643 } else {
3644 status = PlaybackThread::releaseAudioPatch_l(handle);
3645 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003646 return status;
3647}
3648
Eric Laurent1c333e22014-05-20 10:48:17 -07003649status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3650{
3651 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003652
3653 mOutDevice = AUDIO_DEVICE_NONE;
3654
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003655 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003656 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3657 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003658 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003659 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003660 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003661 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003662 }
3663 return status;
3664}
3665
Eric Laurent83b88082014-06-20 18:31:16 -07003666void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3667{
3668 Mutex::Autolock _l(mLock);
3669 mTracks.add(track);
3670}
3671
3672void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3673{
3674 Mutex::Autolock _l(mLock);
3675 destroyTrack_l(track);
3676}
3677
3678void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3679{
3680 ThreadBase::getAudioPortConfig(config);
3681 config->role = AUDIO_PORT_ROLE_SOURCE;
3682 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3683 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3684}
3685
Eric Laurent81784c32012-11-19 14:55:58 -08003686// ----------------------------------------------------------------------------
3687
3688AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003689 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3690 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003691 // mAudioMixer below
3692 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003693 mFastMixerFutex(0),
3694 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003695 // mOutputSink below
3696 // mPipeSink below
3697 // mNormalSink below
3698{
3699 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003700 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003701 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003702 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3703 mNormalFrameCount);
3704 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3705
Andy Hungfbfc3952015-01-15 13:33:51 -08003706 if (type == DUPLICATING) {
3707 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3708 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3709 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3710 return;
3711 }
Eric Laurent81784c32012-11-19 14:55:58 -08003712 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003713 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003714 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003715 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003716#if !LOG_NDEBUG
3717 ssize_t index =
3718#else
3719 (void)
3720#endif
3721 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003722 ALOG_ASSERT(index == 0);
3723
3724 // initialize fast mixer depending on configuration
3725 bool initFastMixer;
3726 switch (kUseFastMixer) {
3727 case FastMixer_Never:
3728 initFastMixer = false;
3729 break;
3730 case FastMixer_Always:
3731 initFastMixer = true;
3732 break;
3733 case FastMixer_Static:
3734 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003735 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3736 // where the period is less than an experimentally determined threshold that can be
3737 // scheduled reliably with CFS. However, the BT A2DP HAL is
3738 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3739 initFastMixer = mFrameCount < mNormalFrameCount
3740 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003741 break;
3742 }
Andy Hungfda69402017-02-15 14:33:12 -08003743 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3744 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3745 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003746 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003747 audio_format_t fastMixerFormat;
3748 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3749 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3750 } else {
3751 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3752 }
3753 if (mFormat != fastMixerFormat) {
3754 // change our Sink format to accept our intermediate precision
3755 mFormat = fastMixerFormat;
3756 free(mSinkBuffer);
3757 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3758 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3759 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3760 }
Eric Laurent81784c32012-11-19 14:55:58 -08003761
3762 // create a MonoPipe to connect our submix to FastMixer
3763 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003764#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003765 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003766#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003767 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003768 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003769 format.mFormat = fastMixerFormat;
3770 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3771
Eric Laurent81784c32012-11-19 14:55:58 -08003772 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3773 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3774 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3775 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3776 const NBAIO_Format offers[1] = {format};
3777 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003778#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003779 ssize_t index =
3780#else
3781 (void)
3782#endif
3783 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 ALOG_ASSERT(index == 0);
3785 monoPipe->setAvgFrames((mScreenState & 1) ?
3786 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3787 mPipeSink = monoPipe;
3788
Glenn Kasten46909e72013-02-26 09:20:22 -08003789#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003790 if (mTeeSinkOutputEnabled) {
3791 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003792 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3793 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003794 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003795 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003796 ALOG_ASSERT(index == 0);
3797 mTeeSink = teeSink;
3798 PipeReader *teeSource = new PipeReader(*teeSink);
3799 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003800 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003801 ALOG_ASSERT(index == 0);
3802 mTeeSource = teeSource;
3803 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003804#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003805
3806 // create fast mixer and configure it initially with just one fast track for our submix
3807 mFastMixer = new FastMixer();
3808 FastMixerStateQueue *sq = mFastMixer->sq();
3809#ifdef STATE_QUEUE_DUMP
3810 sq->setObserverDump(&mStateQueueObserverDump);
3811 sq->setMutatorDump(&mStateQueueMutatorDump);
3812#endif
3813 FastMixerState *state = sq->begin();
3814 FastTrack *fastTrack = &state->mFastTracks[0];
3815 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3816 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3817 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003818 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3819 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003820 fastTrack->mGeneration++;
3821 state->mFastTracksGen++;
3822 state->mTrackMask = 1;
3823 // fast mixer will use the HAL output sink
3824 state->mOutputSink = mOutputSink.get();
3825 state->mOutputSinkGen++;
3826 state->mFrameCount = mFrameCount;
3827 state->mCommand = FastMixerState::COLD_IDLE;
3828 // already done in constructor initialization list
3829 //mFastMixerFutex = 0;
3830 state->mColdFutexAddr = &mFastMixerFutex;
3831 state->mColdGen++;
3832 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003833#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003834 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003835#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003836 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3837 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003838 sq->end();
3839 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3840
3841 // start the fast mixer
3842 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3843 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003844 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003845 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003846
3847#ifdef AUDIO_WATCHDOG
3848 // create and start the watchdog
3849 mAudioWatchdog = new AudioWatchdog();
3850 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3851 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3852 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003853 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003854#endif
3855
Eric Laurent81784c32012-11-19 14:55:58 -08003856 }
3857
3858 switch (kUseFastMixer) {
3859 case FastMixer_Never:
3860 case FastMixer_Dynamic:
3861 mNormalSink = mOutputSink;
3862 break;
3863 case FastMixer_Always:
3864 mNormalSink = mPipeSink;
3865 break;
3866 case FastMixer_Static:
3867 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3868 break;
3869 }
3870}
3871
3872AudioFlinger::MixerThread::~MixerThread()
3873{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003874 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003875 FastMixerStateQueue *sq = mFastMixer->sq();
3876 FastMixerState *state = sq->begin();
3877 if (state->mCommand == FastMixerState::COLD_IDLE) {
3878 int32_t old = android_atomic_inc(&mFastMixerFutex);
3879 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003880 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003881 }
3882 }
3883 state->mCommand = FastMixerState::EXIT;
3884 sq->end();
3885 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3886 mFastMixer->join();
3887 // Though the fast mixer thread has exited, it's state queue is still valid.
3888 // We'll use that extract the final state which contains one remaining fast track
3889 // corresponding to our sub-mix.
3890 state = sq->begin();
3891 ALOG_ASSERT(state->mTrackMask == 1);
3892 FastTrack *fastTrack = &state->mFastTracks[0];
3893 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3894 delete fastTrack->mBufferProvider;
3895 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003896 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003897#ifdef AUDIO_WATCHDOG
3898 if (mAudioWatchdog != 0) {
3899 mAudioWatchdog->requestExit();
3900 mAudioWatchdog->requestExitAndWait();
3901 mAudioWatchdog.clear();
3902 }
3903#endif
3904 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003905 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003906 delete mAudioMixer;
3907}
3908
3909
3910uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3911{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003912 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003913 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3914 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3915 }
3916 return latency;
3917}
3918
3919
3920void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3921{
3922 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3923}
3924
Eric Laurentbfb1b832013-01-07 09:53:42 -08003925ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003926{
3927 // FIXME we should only do one push per cycle; confirm this is true
3928 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003929 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003930 FastMixerStateQueue *sq = mFastMixer->sq();
3931 FastMixerState *state = sq->begin();
3932 if (state->mCommand != FastMixerState::MIX_WRITE &&
3933 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3934 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003935
3936 // FIXME workaround for first HAL write being CPU bound on some devices
3937 ATRACE_BEGIN("write");
3938 mOutput->write((char *)mSinkBuffer, 0);
3939 ATRACE_END();
3940
Eric Laurent81784c32012-11-19 14:55:58 -08003941 int32_t old = android_atomic_inc(&mFastMixerFutex);
3942 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003943 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003944 }
3945#ifdef AUDIO_WATCHDOG
3946 if (mAudioWatchdog != 0) {
3947 mAudioWatchdog->resume();
3948 }
3949#endif
3950 }
3951 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003952#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003953 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003954 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003955#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003956 sq->end();
3957 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3958 if (kUseFastMixer == FastMixer_Dynamic) {
3959 mNormalSink = mPipeSink;
3960 }
3961 } else {
3962 sq->end(false /*didModify*/);
3963 }
3964 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003965 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003966}
3967
3968void AudioFlinger::MixerThread::threadLoop_standby()
3969{
3970 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003971 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003972 FastMixerStateQueue *sq = mFastMixer->sq();
3973 FastMixerState *state = sq->begin();
3974 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003975 // Report any frames trapped in the Monopipe
3976 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3977 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3978 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3979 "monoPipeWritten:%lld monoPipeLeft:%lld",
3980 (long long)mFramesWritten, (long long)mSuspendedFrames,
3981 (long long)mPipeSink->framesWritten(), pipeFrames);
3982 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3983
Eric Laurent81784c32012-11-19 14:55:58 -08003984 state->mCommand = FastMixerState::COLD_IDLE;
3985 state->mColdFutexAddr = &mFastMixerFutex;
3986 state->mColdGen++;
3987 mFastMixerFutex = 0;
3988 sq->end();
3989 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3990 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3991 if (kUseFastMixer == FastMixer_Dynamic) {
3992 mNormalSink = mOutputSink;
3993 }
3994#ifdef AUDIO_WATCHDOG
3995 if (mAudioWatchdog != 0) {
3996 mAudioWatchdog->pause();
3997 }
3998#endif
3999 } else {
4000 sq->end(false /*didModify*/);
4001 }
4002 }
4003 PlaybackThread::threadLoop_standby();
4004}
4005
Eric Laurentbfb1b832013-01-07 09:53:42 -08004006bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4007{
4008 return false;
4009}
4010
4011bool AudioFlinger::PlaybackThread::shouldStandby_l()
4012{
4013 return !mStandby;
4014}
4015
4016bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4017{
4018 Mutex::Autolock _l(mLock);
4019 return waitingAsyncCallback_l();
4020}
4021
Eric Laurent81784c32012-11-19 14:55:58 -08004022// shared by MIXER and DIRECT, overridden by DUPLICATING
4023void AudioFlinger::PlaybackThread::threadLoop_standby()
4024{
4025 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004026 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004028 // discard any pending drain or write ack by incrementing sequence
4029 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4030 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004031 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004032 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4033 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004034 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004035 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004036}
4037
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004038void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4039{
4040 ALOGV("signal playback thread");
4041 broadcast_l();
4042}
4043
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004044void AudioFlinger::PlaybackThread::onAsyncError()
4045{
4046 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4047 invalidateTracks((audio_stream_type_t)i);
4048 }
4049}
4050
Eric Laurent81784c32012-11-19 14:55:58 -08004051void AudioFlinger::MixerThread::threadLoop_mix()
4052{
Eric Laurent81784c32012-11-19 14:55:58 -08004053 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004054 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004055 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004056 // increase sleep time progressively when application underrun condition clears.
4057 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4058 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4059 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004060 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004061 sleepTimeShift--;
4062 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004063 mSleepTimeUs = 0;
4064 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004065 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004066
Eric Laurent81784c32012-11-19 14:55:58 -08004067}
4068
4069void AudioFlinger::MixerThread::threadLoop_sleepTime()
4070{
4071 // If no tracks are ready, sleep once for the duration of an output
4072 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004073 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004074 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004075 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4076 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4077 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004078 }
4079 // reduce sleep time in case of consecutive application underruns to avoid
4080 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4081 // duration we would end up writing less data than needed by the audio HAL if
4082 // the condition persists.
4083 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4084 sleepTimeShift++;
4085 }
4086 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004087 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004088 }
4089 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004090 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4091 // before effects processing or output.
4092 if (mMixerBufferValid) {
4093 memset(mMixerBuffer, 0, mMixerBufferSize);
4094 } else {
4095 memset(mSinkBuffer, 0, mSinkBufferSize);
4096 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004097 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004098 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4099 "anticipated start");
4100 }
4101 // TODO add standby time extension fct of effect tail
4102}
4103
4104// prepareTracks_l() must be called with ThreadBase::mLock held
4105AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4106 Vector< sp<Track> > *tracksToRemove)
4107{
4108
4109 mixer_state mixerStatus = MIXER_IDLE;
4110 // find out which tracks need to be processed
4111 size_t count = mActiveTracks.size();
4112 size_t mixedTracks = 0;
4113 size_t tracksWithEffect = 0;
4114 // counts only _active_ fast tracks
4115 size_t fastTracks = 0;
4116 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4117
4118 float masterVolume = mMasterVolume;
4119 bool masterMute = mMasterMute;
4120
4121 if (masterMute) {
4122 masterVolume = 0;
4123 }
4124 // Delegate master volume control to effect in output mix effect chain if needed
4125 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4126 if (chain != 0) {
4127 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4128 chain->setVolume_l(&v, &v);
4129 masterVolume = (float)((v + (1 << 23)) >> 24);
4130 chain.clear();
4131 }
4132
4133 // prepare a new state to push
4134 FastMixerStateQueue *sq = NULL;
4135 FastMixerState *state = NULL;
4136 bool didModify = false;
4137 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004138 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004139 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004140 sq = mFastMixer->sq();
4141 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004142 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004143 }
4144
Andy Hung69aed5f2014-02-25 17:24:40 -08004145 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004146 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004147
Eric Laurent81784c32012-11-19 14:55:58 -08004148 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004149 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004150
4151 // this const just means the local variable doesn't change
4152 Track* const track = t.get();
4153
4154 // process fast tracks
4155 if (track->isFastTrack()) {
4156
4157 // It's theoretically possible (though unlikely) for a fast track to be created
4158 // and then removed within the same normal mix cycle. This is not a problem, as
4159 // the track never becomes active so it's fast mixer slot is never touched.
4160 // The converse, of removing an (active) track and then creating a new track
4161 // at the identical fast mixer slot within the same normal mix cycle,
4162 // is impossible because the slot isn't marked available until the end of each cycle.
4163 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004164 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004165 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4166 FastTrack *fastTrack = &state->mFastTracks[j];
4167
4168 // Determine whether the track is currently in underrun condition,
4169 // and whether it had a recent underrun.
4170 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4171 FastTrackUnderruns underruns = ftDump->mUnderruns;
4172 uint32_t recentFull = (underruns.mBitFields.mFull -
4173 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4174 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4175 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4176 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4177 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4178 uint32_t recentUnderruns = recentPartial + recentEmpty;
4179 track->mObservedUnderruns = underruns;
4180 // don't count underruns that occur while stopping or pausing
4181 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004182 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4183 recentUnderruns > 0) {
4184 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4185 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004186 } else {
4187 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004188 }
4189
4190 // This is similar to the state machine for normal tracks,
4191 // with a few modifications for fast tracks.
4192 bool isActive = true;
4193 switch (track->mState) {
4194 case TrackBase::STOPPING_1:
4195 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004196 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004197 track->mState = TrackBase::STOPPING_2;
4198 }
4199 break;
4200 case TrackBase::PAUSING:
4201 // ramp down is not yet implemented
4202 track->setPaused();
4203 break;
4204 case TrackBase::RESUMING:
4205 // ramp up is not yet implemented
4206 track->mState = TrackBase::ACTIVE;
4207 break;
4208 case TrackBase::ACTIVE:
4209 if (recentFull > 0 || recentPartial > 0) {
4210 // track has provided at least some frames recently: reset retry count
4211 track->mRetryCount = kMaxTrackRetries;
4212 }
4213 if (recentUnderruns == 0) {
4214 // no recent underruns: stay active
4215 break;
4216 }
4217 // there has recently been an underrun of some kind
4218 if (track->sharedBuffer() == 0) {
4219 // were any of the recent underruns "empty" (no frames available)?
4220 if (recentEmpty == 0) {
4221 // no, then ignore the partial underruns as they are allowed indefinitely
4222 break;
4223 }
4224 // there has recently been an "empty" underrun: decrement the retry counter
4225 if (--(track->mRetryCount) > 0) {
4226 break;
4227 }
4228 // indicate to client process that the track was disabled because of underrun;
4229 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004230 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004231 // remove from active list, but state remains ACTIVE [confusing but true]
4232 isActive = false;
4233 break;
4234 }
4235 // fall through
4236 case TrackBase::STOPPING_2:
4237 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004238 case TrackBase::STOPPED:
4239 case TrackBase::FLUSHED: // flush() while active
4240 // Check for presentation complete if track is inactive
4241 // We have consumed all the buffers of this track.
4242 // This would be incomplete if we auto-paused on underrun
4243 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004244 uint32_t latency = 0;
4245 status_t result = mOutput->stream->getLatency(&latency);
4246 ALOGE_IF(result != OK,
4247 "Error when retrieving output stream latency: %d", result);
4248 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004249 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004250 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4251 // track stays in active list until presentation is complete
4252 break;
4253 }
4254 }
4255 if (track->isStopping_2()) {
4256 track->mState = TrackBase::STOPPED;
4257 }
4258 if (track->isStopped()) {
4259 // Can't reset directly, as fast mixer is still polling this track
4260 // track->reset();
4261 // So instead mark this track as needing to be reset after push with ack
4262 resetMask |= 1 << i;
4263 }
4264 isActive = false;
4265 break;
4266 case TrackBase::IDLE:
4267 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004268 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004269 }
4270
4271 if (isActive) {
4272 // was it previously inactive?
4273 if (!(state->mTrackMask & (1 << j))) {
4274 ExtendedAudioBufferProvider *eabp = track;
4275 VolumeProvider *vp = track;
4276 fastTrack->mBufferProvider = eabp;
4277 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004278 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004279 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004280 fastTrack->mGeneration++;
4281 state->mTrackMask |= 1 << j;
4282 didModify = true;
4283 // no acknowledgement required for newly active tracks
4284 }
4285 // cache the combined master volume and stream type volume for fast mixer; this
4286 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004287 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004288 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004289 track->mCachedVolume = masterVolume
4290 * mStreamTypes[track->streamType()].volume
4291 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004292 ++fastTracks;
4293 } else {
4294 // was it previously active?
4295 if (state->mTrackMask & (1 << j)) {
4296 fastTrack->mBufferProvider = NULL;
4297 fastTrack->mGeneration++;
4298 state->mTrackMask &= ~(1 << j);
4299 didModify = true;
4300 // If any fast tracks were removed, we must wait for acknowledgement
4301 // because we're about to decrement the last sp<> on those tracks.
4302 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4303 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004304 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4305 // AudioTrack may start (which may not be with a start() but with a write()
4306 // after underrun) and immediately paused or released. In that case the
4307 // FastTrack state hasn't had time to update.
4308 // TODO Remove the ALOGW when this theory is confirmed.
4309 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004310 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4311 j, track->mState, state->mTrackMask, recentUnderruns,
4312 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004313 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004314 }
4315 tracksToRemove->add(track);
4316 // Avoids a misleading display in dumpsys
4317 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4318 }
4319 continue;
4320 }
4321
4322 { // local variable scope to avoid goto warning
4323
4324 audio_track_cblk_t* cblk = track->cblk();
4325
4326 // The first time a track is added we wait
4327 // for all its buffers to be filled before processing it
4328 int name = track->name();
4329 // make sure that we have enough frames to mix one full buffer.
4330 // enforce this condition only once to enable draining the buffer in case the client
4331 // app does not call stop() and relies on underrun to stop:
4332 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4333 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004334 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004335 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004336 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004337
4338 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004339 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004340 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4341 // add frames already consumed but not yet released by the resampler
4342 // because mAudioTrackServerProxy->framesReady() will include these frames
4343 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4344
Eric Laurent81784c32012-11-19 14:55:58 -08004345 uint32_t minFrames = 1;
4346 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4347 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004348 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004349 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004350
4351 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004352 if (ATRACE_ENABLED()) {
4353 // I wish we had formatted trace names
4354 char traceName[16];
4355 strcpy(traceName, "nRdy");
4356 int name = track->name();
4357 if (AudioMixer::TRACK0 <= name &&
4358 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4359 name -= AudioMixer::TRACK0;
4360 traceName[4] = (name / 10) + '0';
4361 traceName[5] = (name % 10) + '0';
4362 } else {
4363 traceName[4] = '?';
4364 traceName[5] = '?';
4365 }
4366 traceName[6] = '\0';
4367 ATRACE_INT(traceName, framesReady);
4368 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004369 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004370 !track->isPaused() && !track->isTerminated())
4371 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004372 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004373
4374 mixedTracks++;
4375
Andy Hung69aed5f2014-02-25 17:24:40 -08004376 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4377 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004378 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004379 if (track->mainBuffer() != mSinkBuffer &&
4380 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004381 if (mEffectBufferEnabled) {
4382 mEffectBufferValid = true; // Later can set directly.
4383 }
Eric Laurent81784c32012-11-19 14:55:58 -08004384 chain = getEffectChain_l(track->sessionId());
4385 // Delegate volume control to effect in track effect chain if needed
4386 if (chain != 0) {
4387 tracksWithEffect++;
4388 } else {
4389 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4390 "session %d",
4391 name, track->sessionId());
4392 }
4393 }
4394
4395
4396 int param = AudioMixer::VOLUME;
4397 if (track->mFillingUpStatus == Track::FS_FILLED) {
4398 // no ramp for the first volume setting
4399 track->mFillingUpStatus = Track::FS_ACTIVE;
4400 if (track->mState == TrackBase::RESUMING) {
4401 track->mState = TrackBase::ACTIVE;
4402 param = AudioMixer::RAMP_VOLUME;
4403 }
4404 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004405 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004406 // FIXME should not make a decision based on mServer
4407 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004408 // If the track is stopped before the first frame was mixed,
4409 // do not apply ramp
4410 param = AudioMixer::RAMP_VOLUME;
4411 }
4412
4413 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004414 uint32_t vl, vr; // in U8.24 integer format
4415 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004416 // read original volumes with volume control
4417 float typeVolume = mStreamTypes[track->streamType()].volume;
4418 float v = masterVolume * typeVolume;
4419
Glenn Kastene4756fe2012-11-29 13:38:14 -08004420 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004421 vl = vr = 0;
4422 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004423 if (track->isPausing()) {
4424 track->setPaused();
4425 }
4426 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004427 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004428 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004429 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4430 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004431 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004432 if (vlf > GAIN_FLOAT_UNITY) {
4433 ALOGV("Track left volume out of range: %.3g", vlf);
4434 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004435 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004436 if (vrf > GAIN_FLOAT_UNITY) {
4437 ALOGV("Track right volume out of range: %.3g", vrf);
4438 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004439 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004440 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004441 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004442 // now apply the master volume and stream type volume and shaper volume
4443 vlf *= v * vh;
4444 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004445 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004446 // then derive vl and vr as U8.24 versions for the effect chain
4447 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4448 vl = (uint32_t) (scaleto8_24 * vlf);
4449 vr = (uint32_t) (scaleto8_24 * vrf);
4450 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004451 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004452 // send level comes from shared memory and so may be corrupt
4453 if (sendLevel > MAX_GAIN_INT) {
4454 ALOGV("Track send level out of range: %04X", sendLevel);
4455 sendLevel = MAX_GAIN_INT;
4456 }
Andy Hung6be49402014-05-30 10:42:03 -07004457 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4458 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004459 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004460
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // Delegate volume control to effect in track effect chain if needed
4462 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4463 // Do not ramp volume if volume is controlled by effect
4464 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004465 // Update remaining floating point volume levels
4466 vlf = (float)vl / (1 << 24);
4467 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004468 track->mHasVolumeController = true;
4469 } else {
4470 // force no volume ramp when volume controller was just disabled or removed
4471 // from effect chain to avoid volume spike
4472 if (track->mHasVolumeController) {
4473 param = AudioMixer::VOLUME;
4474 }
4475 track->mHasVolumeController = false;
4476 }
4477
Eric Laurent7c29ec92017-09-20 17:54:22 -07004478 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4479 // still applied by the mixer.
4480 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4481 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4482 if (v != mLeftVolFloat) {
4483 status_t result = mOutput->stream->setVolume(v, v);
4484 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4485 if (result == OK) {
4486 mLeftVolFloat = v;
4487 }
4488 }
4489 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4490 // remove stream volume contribution from software volume.
4491 if (v != 0.0f && mLeftVolFloat == v) {
4492 vlf = min(1.0f, vlf / v);
4493 vrf = min(1.0f, vrf / v);
4494 vaf = min(1.0f, vaf / v);
4495 }
4496 }
Eric Laurent81784c32012-11-19 14:55:58 -08004497 // XXX: these things DON'T need to be done each time
4498 mAudioMixer->setBufferProvider(name, track);
4499 mAudioMixer->enable(name);
4500
Andy Hung6be49402014-05-30 10:42:03 -07004501 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4502 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4503 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004504 mAudioMixer->setParameter(
4505 name,
4506 AudioMixer::TRACK,
4507 AudioMixer::FORMAT, (void *)track->format());
4508 mAudioMixer->setParameter(
4509 name,
4510 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004511 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004512 mAudioMixer->setParameter(
4513 name,
4514 AudioMixer::TRACK,
4515 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004516 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004517 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004518 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004519 if (reqSampleRate == 0) {
4520 reqSampleRate = mSampleRate;
4521 } else if (reqSampleRate > maxSampleRate) {
4522 reqSampleRate = maxSampleRate;
4523 }
Eric Laurent81784c32012-11-19 14:55:58 -08004524 mAudioMixer->setParameter(
4525 name,
4526 AudioMixer::RESAMPLE,
4527 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004528 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004529
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004530 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004531 mAudioMixer->setParameter(
4532 name,
4533 AudioMixer::TIMESTRETCH,
4534 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004535 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004536
Andy Hung69aed5f2014-02-25 17:24:40 -08004537 /*
4538 * Select the appropriate output buffer for the track.
4539 *
Andy Hung98ef9782014-03-04 14:46:50 -08004540 * Tracks with effects go into their own effects chain buffer
4541 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004542 *
4543 * Other tracks can use mMixerBuffer for higher precision
4544 * channel accumulation. If this buffer is enabled
4545 * (mMixerBufferEnabled true), then selected tracks will accumulate
4546 * into it.
4547 *
4548 */
4549 if (mMixerBufferEnabled
4550 && (track->mainBuffer() == mSinkBuffer
4551 || track->mainBuffer() == mMixerBuffer)) {
4552 mAudioMixer->setParameter(
4553 name,
4554 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004555 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004556 mAudioMixer->setParameter(
4557 name,
4558 AudioMixer::TRACK,
4559 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4560 // TODO: override track->mainBuffer()?
4561 mMixerBufferValid = true;
4562 } else {
4563 mAudioMixer->setParameter(
4564 name,
4565 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004566 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004567 mAudioMixer->setParameter(
4568 name,
4569 AudioMixer::TRACK,
4570 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4571 }
Eric Laurent81784c32012-11-19 14:55:58 -08004572 mAudioMixer->setParameter(
4573 name,
4574 AudioMixer::TRACK,
4575 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4576
4577 // reset retry count
4578 track->mRetryCount = kMaxTrackRetries;
4579
4580 // If one track is ready, set the mixer ready if:
4581 // - the mixer was not ready during previous round OR
4582 // - no other track is not ready
4583 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4584 mixerStatus != MIXER_TRACKS_ENABLED) {
4585 mixerStatus = MIXER_TRACKS_READY;
4586 }
4587 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004588 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004589 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4590 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004591 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004592 } else {
4593 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004594 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004595
Eric Laurent81784c32012-11-19 14:55:58 -08004596 // clear effect chain input buffer if an active track underruns to avoid sending
4597 // previous audio buffer again to effects
4598 chain = getEffectChain_l(track->sessionId());
4599 if (chain != 0) {
4600 chain->clearInputBuffer();
4601 }
4602
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004603 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004604 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4605 track->isStopped() || track->isPaused()) {
4606 // We have consumed all the buffers of this track.
4607 // Remove it from the list of active tracks.
4608 // TODO: use actual buffer filling status instead of latency when available from
4609 // audio HAL
4610 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004611 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004612 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4613 if (track->isStopped()) {
4614 track->reset();
4615 }
4616 tracksToRemove->add(track);
4617 }
4618 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004619 // No buffers for this track. Give it a few chances to
4620 // fill a buffer, then remove it from active list.
4621 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004622 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004623 tracksToRemove->add(track);
4624 // indicate to client process that the track was disabled because of underrun;
4625 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004626 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004627 // If one track is not ready, mark the mixer also not ready if:
4628 // - the mixer was ready during previous round OR
4629 // - no other track is ready
4630 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4631 mixerStatus != MIXER_TRACKS_READY) {
4632 mixerStatus = MIXER_TRACKS_ENABLED;
4633 }
4634 }
4635 mAudioMixer->disable(name);
4636 }
4637
4638 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004639
4640 }
4641
4642 // Push the new FastMixer state if necessary
4643 bool pauseAudioWatchdog = false;
4644 if (didModify) {
4645 state->mFastTracksGen++;
4646 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4647 if (kUseFastMixer == FastMixer_Dynamic &&
4648 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4649 state->mCommand = FastMixerState::COLD_IDLE;
4650 state->mColdFutexAddr = &mFastMixerFutex;
4651 state->mColdGen++;
4652 mFastMixerFutex = 0;
4653 if (kUseFastMixer == FastMixer_Dynamic) {
4654 mNormalSink = mOutputSink;
4655 }
4656 // If we go into cold idle, need to wait for acknowledgement
4657 // so that fast mixer stops doing I/O.
4658 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4659 pauseAudioWatchdog = true;
4660 }
Eric Laurent81784c32012-11-19 14:55:58 -08004661 }
4662 if (sq != NULL) {
4663 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004664 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4665 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4666 // when bringing the output sink into standby.)
4667 //
4668 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4669 //
4670 // This occurs with BT suspend when we idle the FastMixer with
4671 // active tracks, which may be added or removed.
4672 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004673 }
4674#ifdef AUDIO_WATCHDOG
4675 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4676 mAudioWatchdog->pause();
4677 }
4678#endif
4679
4680 // Now perform the deferred reset on fast tracks that have stopped
4681 while (resetMask != 0) {
4682 size_t i = __builtin_ctz(resetMask);
4683 ALOG_ASSERT(i < count);
4684 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004685 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004686 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4687 track->reset();
4688 }
4689
4690 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004691 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004692
Eric Laurent97d547d2014-09-02 14:45:53 -07004693 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4694 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004695 }
4696
4697 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004698 // as long as there are effects we should clear the effects buffer, to avoid
4699 // passing a non-clean buffer to the effect chain
4700 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004701 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004702 // sink or mix buffer must be cleared if all tracks are connected to an
4703 // effect chain as in this case the mixer will not write to the sink or mix buffer
4704 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4706 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004707 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004708 if (mMixerBufferValid) {
4709 memset(mMixerBuffer, 0, mMixerBufferSize);
4710 // TODO: In testing, mSinkBuffer below need not be cleared because
4711 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4712 // after mixing.
4713 //
4714 // To enforce this guarantee:
4715 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4716 // (mixedTracks == 0 && fastTracks > 0))
4717 // must imply MIXER_TRACKS_READY.
4718 // Later, we may clear buffers regardless, and skip much of this logic.
4719 }
Andy Hung98ef9782014-03-04 14:46:50 -08004720 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004721 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004722 }
4723
4724 // if any fast tracks, then status is ready
4725 mMixerStatusIgnoringFastTracks = mixerStatus;
4726 if (fastTracks > 0) {
4727 mixerStatus = MIXER_TRACKS_READY;
4728 }
4729 return mixerStatus;
4730}
4731
Eric Laurentad7dd962016-09-22 12:38:37 -07004732// trackCountForUid_l() must be called with ThreadBase::mLock held
4733uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4734{
4735 uint32_t trackCount = 0;
4736 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004737 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004738 trackCount++;
4739 }
4740 }
4741 return trackCount;
4742}
4743
Eric Laurent81784c32012-11-19 14:55:58 -08004744// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004745int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004746 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004747{
Eric Laurentad7dd962016-09-22 12:38:37 -07004748 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4749 return -1;
4750 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004751 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004752}
4753
4754// deleteTrackName_l() must be called with ThreadBase::mLock held
4755void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4756{
4757 ALOGV("remove track (%d) and delete from mixer", name);
4758 mAudioMixer->deleteTrackName(name);
4759}
4760
Eric Laurent10351942014-05-08 18:49:52 -07004761// checkForNewParameter_l() must be called with ThreadBase::mLock held
4762bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4763 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004764{
Eric Laurent81784c32012-11-19 14:55:58 -08004765 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004766 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004767
Eric Laurent10351942014-05-08 18:49:52 -07004768 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004769
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004770 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004771
Eric Laurent10351942014-05-08 18:49:52 -07004772 AudioParameter param = AudioParameter(keyValuePair);
4773 int value;
4774 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4775 reconfig = true;
4776 }
4777 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004778 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004779 status = BAD_VALUE;
4780 } else {
4781 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004782 reconfig = true;
4783 }
Eric Laurent10351942014-05-08 18:49:52 -07004784 }
4785 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004786 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004787 status = BAD_VALUE;
4788 } else {
4789 // no need to save value, since it's constant
4790 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004791 }
Eric Laurent10351942014-05-08 18:49:52 -07004792 }
4793 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4794 // do not accept frame count changes if tracks are open as the track buffer
4795 // size depends on frame count and correct behavior would not be guaranteed
4796 // if frame count is changed after track creation
4797 if (!mTracks.isEmpty()) {
4798 status = INVALID_OPERATION;
4799 } else {
4800 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004801 }
Eric Laurent10351942014-05-08 18:49:52 -07004802 }
4803 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004804#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004805 // when changing the audio output device, call addBatteryData to notify
4806 // the change
4807 if (mOutDevice != value) {
4808 uint32_t params = 0;
4809 // check whether speaker is on
4810 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4811 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004812 }
Eric Laurent10351942014-05-08 18:49:52 -07004813
4814 audio_devices_t deviceWithoutSpeaker
4815 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4816 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004817 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004818 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4819 }
4820
4821 if (params != 0) {
4822 addBatteryData(params);
4823 }
4824 }
Eric Laurent81784c32012-11-19 14:55:58 -08004825#endif
4826
Eric Laurent10351942014-05-08 18:49:52 -07004827 // forward device change to effects that have requested to be
4828 // aware of attached audio device.
4829 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004830 a2dpDeviceChanged =
4831 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004832 mOutDevice = value;
4833 for (size_t i = 0; i < mEffectChains.size(); i++) {
4834 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004835 }
4836 }
Eric Laurent10351942014-05-08 18:49:52 -07004837 }
Eric Laurent81784c32012-11-19 14:55:58 -08004838
Eric Laurent10351942014-05-08 18:49:52 -07004839 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004840 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004841 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004842 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004843 mStandby = true;
4844 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004845 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004846 }
Eric Laurent10351942014-05-08 18:49:52 -07004847 if (status == NO_ERROR && reconfig) {
4848 readOutputParameters_l();
4849 delete mAudioMixer;
4850 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4851 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004852 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004853 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004854 if (name < 0) {
4855 break;
4856 }
4857 mTracks[i]->mName = name;
4858 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004859 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004860 }
Eric Laurent81784c32012-11-19 14:55:58 -08004861 }
4862
Eric Laurent42537be2016-01-08 17:16:42 -08004863 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004864}
4865
4866
4867void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4868{
Eric Laurent81784c32012-11-19 14:55:58 -08004869 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004870 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004871 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004872 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004873
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004874 if (hasFastMixer()) {
4875 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4876
4877 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4878 // while we are dumping it. It may be inconsistent, but it won't mutate!
4879 // This is a large object so we place it on the heap.
4880 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4881 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4882 copy->dump(fd);
4883 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004884
4885#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004886 // Similar for state queue
4887 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4888 observerCopy.dump(fd);
4889 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4890 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004891#endif
4892
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004893#ifdef AUDIO_WATCHDOG
4894 if (mAudioWatchdog != 0) {
4895 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4896 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4897 wdCopy.dump(fd);
4898 }
4899#endif
4900
4901 } else {
4902 dprintf(fd, " No FastMixer\n");
4903 }
4904
Glenn Kasten46909e72013-02-26 09:20:22 -08004905#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004906 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004907 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004908#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004909
Eric Laurent81784c32012-11-19 14:55:58 -08004910}
4911
4912uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4913{
4914 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4915}
4916
4917uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4918{
4919 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4920}
4921
4922void AudioFlinger::MixerThread::cacheParameters_l()
4923{
4924 PlaybackThread::cacheParameters_l();
4925
4926 // FIXME: Relaxed timing because of a certain device that can't meet latency
4927 // Should be reduced to 2x after the vendor fixes the driver issue
4928 // increase threshold again due to low power audio mode. The way this warning
4929 // threshold is calculated and its usefulness should be reconsidered anyway.
4930 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4931}
4932
4933// ----------------------------------------------------------------------------
4934
4935AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004936 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4937 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004938{
4939}
4940
Eric Laurentbfb1b832013-01-07 09:53:42 -08004941AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4942 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004943 ThreadBase::type_t type, bool systemReady)
4944 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08004945 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004946{
4947}
4948
Eric Laurent81784c32012-11-19 14:55:58 -08004949AudioFlinger::DirectOutputThread::~DirectOutputThread()
4950{
4951}
4952
Eric Laurent5850c4c2016-11-10 13:04:31 -08004953void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004954{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004955 float left, right;
4956
4957 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4958 left = right = 0;
4959 } else {
4960 float typeVolume = mStreamTypes[track->streamType()].volume;
4961 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004962 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004963
Andy Hung10cbff12017-02-21 17:30:14 -08004964 // Get volumeshaper scaling
4965 std::pair<float /* volume */, bool /* active */>
4966 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004967 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004968 v *= vh.first;
4969 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004970
Glenn Kastenc56f3422014-03-21 17:53:17 -07004971 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4972 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4973 if (left > GAIN_FLOAT_UNITY) {
4974 left = GAIN_FLOAT_UNITY;
4975 }
4976 left *= v;
4977 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4978 if (right > GAIN_FLOAT_UNITY) {
4979 right = GAIN_FLOAT_UNITY;
4980 }
4981 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004982 }
4983
4984 if (lastTrack) {
4985 if (left != mLeftVolFloat || right != mRightVolFloat) {
4986 mLeftVolFloat = left;
4987 mRightVolFloat = right;
4988
4989 // Convert volumes from float to 8.24
4990 uint32_t vl = (uint32_t)(left * (1 << 24));
4991 uint32_t vr = (uint32_t)(right * (1 << 24));
4992
4993 // Delegate volume control to effect in track effect chain if needed
4994 // only one effect chain can be present on DirectOutputThread, so if
4995 // there is one, the track is connected to it
4996 if (!mEffectChains.isEmpty()) {
4997 mEffectChains[0]->setVolume_l(&vl, &vr);
4998 left = (float)vl / (1 << 24);
4999 right = (float)vr / (1 << 24);
5000 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005001 status_t result = mOutput->stream->setVolume(left, right);
5002 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005003 }
5004 }
5005}
5006
Phil Burk43b4dcc2015-06-09 16:53:44 -07005007void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5008{
5009 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005010 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005011
Eric Laurent0f0631e2015-07-06 18:01:25 -07005012 if (previousTrack != 0 && latestTrack != 0) {
5013 if (mType == DIRECT) {
5014 if (previousTrack.get() != latestTrack.get()) {
5015 mFlushPending = true;
5016 }
5017 } else /* mType == OFFLOAD */ {
5018 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5019 mFlushPending = true;
5020 }
5021 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005022 }
5023 PlaybackThread::onAddNewTrack_l();
5024}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005025
Eric Laurent81784c32012-11-19 14:55:58 -08005026AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5027 Vector< sp<Track> > *tracksToRemove
5028)
5029{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005030 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005031 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005032 bool doHwPause = false;
5033 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005034
5035 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005036 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005037 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005038 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005039 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005040 continue;
5041 }
5042
Eric Laurent5850c4c2016-11-10 13:04:31 -08005043 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005044#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005045 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005046#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005047 // Only consider last track started for volume and mixer state control.
5048 // In theory an older track could underrun and restart after the new one starts
5049 // but as we only care about the transition phase between two tracks on a
5050 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005051 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005052 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005053
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005054 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005055 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005056 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005057 doHwPause = true;
5058 mHwPaused = true;
5059 }
5060 tracksToRemove->add(track);
5061 } else if (track->isFlushPending()) {
5062 track->flushAck();
5063 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005064 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005066 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005067 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005068 if (last) {
5069 mLeftVolFloat = mRightVolFloat = -1.0;
5070 if (mHwPaused) {
5071 doHwResume = true;
5072 mHwPaused = false;
5073 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005074 }
5075 }
5076
Eric Laurent81784c32012-11-19 14:55:58 -08005077 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005078 // for all its buffers to be filled before processing it.
5079 // Allow draining the buffer in case the client
5080 // app does not call stop() and relies on underrun to stop:
5081 // hence the test on (track->mRetryCount > 1).
5082 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005083 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005084 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005085 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005086 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005087 minFrames = mNormalFrameCount;
5088 } else {
5089 minFrames = 1;
5090 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005091
Eric Laurentab5cdba2014-06-09 17:22:27 -07005092 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5093 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005094 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005095 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005096
5097 if (track->mFillingUpStatus == Track::FS_FILLED) {
5098 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005099 if (last) {
5100 // make sure processVolume_l() will apply new volume even if 0
5101 mLeftVolFloat = mRightVolFloat = -1.0;
5102 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005103 if (!mHwSupportsPause) {
5104 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005105 }
5106 }
5107
5108 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005109 processVolume_l(track, last);
5110 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005111 sp<Track> previousTrack = mPreviousTrack.promote();
5112 if (previousTrack != 0) {
5113 if (track != previousTrack.get()) {
5114 // Flush any data still being written from last track
5115 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005116 // Invalidate previous track to force a seek when resuming.
5117 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005118 }
5119 }
5120 mPreviousTrack = track;
5121
Eric Laurentd595b7c2013-04-03 17:27:56 -07005122 // reset retry count
5123 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005124 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005125 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005126 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005127 doHwResume = true;
5128 mHwPaused = false;
5129 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005130 }
Eric Laurent81784c32012-11-19 14:55:58 -08005131 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005132 // clear effect chain input buffer if the last active track started underruns
5133 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005134 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005135 mEffectChains[0]->clearInputBuffer();
5136 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005137 if (track->isStopping_1()) {
5138 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005139 if (last && mHwPaused) {
5140 doHwResume = true;
5141 mHwPaused = false;
5142 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005143 }
5144 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5145 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005146 // We have consumed all the buffers of this track.
5147 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005148 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005149 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005150 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5151 } else {
5152 audioHALFrames = 0;
5153 }
5154
Andy Hung818e7a32016-02-16 18:08:07 -08005155 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005156 if (mStandby || !last ||
5157 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005158 if (track->isStopping_2()) {
5159 track->mState = TrackBase::STOPPED;
5160 }
Eric Laurent81784c32012-11-19 14:55:58 -08005161 if (track->isStopped()) {
5162 track->reset();
5163 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005164 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005165 }
5166 } else {
5167 // No buffers for this track. Give it a few chances to
5168 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005169 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005170 if (--(track->mRetryCount) <= 0) {
5171 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005172 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005173 // indicate to client process that the track was disabled because of underrun;
5174 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005175 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005177 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5178 "minFrames = %u, mFormat = %#x",
5179 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005180 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005181 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005182 doHwPause = true;
5183 mHwPaused = true;
5184 }
Eric Laurent81784c32012-11-19 14:55:58 -08005185 }
5186 }
5187 }
5188 }
5189
Eric Laurentd1f69b02014-12-15 14:33:13 -08005190 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005191 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005192 for (size_t i = 0; i < mTracks.size(); i++) {
5193 if (mTracks[i]->isFlushPending()) {
5194 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005195 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005196 }
5197 }
5198 }
5199
5200 // make sure the pause/flush/resume sequence is executed in the right order.
5201 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5202 // before flush and then resume HW. This can happen in case of pause/flush/resume
5203 // if resume is received before pause is executed.
5204 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005205 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005206 status_t result = mOutput->stream->pause();
5207 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005208 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005209 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005210 flushHw_l();
5211 }
5212 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005213 status_t result = mOutput->stream->resume();
5214 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005215 }
Eric Laurent81784c32012-11-19 14:55:58 -08005216 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005217 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005218
5219 return mixerStatus;
5220}
5221
5222void AudioFlinger::DirectOutputThread::threadLoop_mix()
5223{
Eric Laurent81784c32012-11-19 14:55:58 -08005224 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005225 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005226 // output audio to hardware
5227 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005228 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005229 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005230 status_t status = mActiveTrack->getNextBuffer(&buffer);
5231 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005232 // no need to pad with 0 for compressed audio
5233 if (audio_has_proportional_frames(mFormat)) {
5234 memset(curBuf, 0, frameCount * mFrameSize);
5235 }
Eric Laurent81784c32012-11-19 14:55:58 -08005236 break;
5237 }
5238 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5239 frameCount -= buffer.frameCount;
5240 curBuf += buffer.frameCount * mFrameSize;
5241 mActiveTrack->releaseBuffer(&buffer);
5242 }
Andy Hung2098f272014-02-27 14:00:06 -08005243 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005244 mSleepTimeUs = 0;
5245 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005246 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005247}
5248
5249void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5250{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005251 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005252 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005253 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005254 return;
5255 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005256 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005257 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005258 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005259 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005260 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005261 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005262 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005263 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005264 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005265 }
5266}
5267
Eric Laurentd1f69b02014-12-15 14:33:13 -08005268void AudioFlinger::DirectOutputThread::threadLoop_exit()
5269{
5270 {
5271 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005272 for (size_t i = 0; i < mTracks.size(); i++) {
5273 if (mTracks[i]->isFlushPending()) {
5274 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005275 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005276 }
5277 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005278 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005279 flushHw_l();
5280 }
5281 }
5282 PlaybackThread::threadLoop_exit();
5283}
5284
5285// must be called with thread mutex locked
5286bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5287{
5288 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005289 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005290
vivek mehta9cd7ad12016-03-17 00:18:29 -07005291 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5292 return !mStandby;
5293 }
5294
Eric Laurentd1f69b02014-12-15 14:33:13 -08005295 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5296 // after a timeout and we will enter standby then.
5297 if (mTracks.size() > 0) {
5298 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005299 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5300 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005301 }
5302
Eric Laurent5cff4032015-05-26 13:49:58 -07005303 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005304}
5305
Eric Laurent81784c32012-11-19 14:55:58 -08005306// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005307int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005308 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005309{
Eric Laurentad7dd962016-09-22 12:38:37 -07005310 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5311 return -1;
5312 }
Eric Laurent81784c32012-11-19 14:55:58 -08005313 return 0;
5314}
5315
5316// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005317void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005318{
5319}
5320
Eric Laurent10351942014-05-08 18:49:52 -07005321// checkForNewParameter_l() must be called with ThreadBase::mLock held
5322bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5323 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005324{
5325 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005326 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005327
Eric Laurent10351942014-05-08 18:49:52 -07005328 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005329
Eric Laurent10351942014-05-08 18:49:52 -07005330 AudioParameter param = AudioParameter(keyValuePair);
5331 int value;
5332 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5333 // forward device change to effects that have requested to be
5334 // aware of attached audio device.
5335 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005336 a2dpDeviceChanged =
5337 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005338 mOutDevice = value;
5339 for (size_t i = 0; i < mEffectChains.size(); i++) {
5340 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005341 }
5342 }
Eric Laurent81784c32012-11-19 14:55:58 -08005343 }
Eric Laurent10351942014-05-08 18:49:52 -07005344 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5345 // do not accept frame count changes if tracks are open as the track buffer
5346 // size depends on frame count and correct behavior would not be garantied
5347 // if frame count is changed after track creation
5348 if (!mTracks.isEmpty()) {
5349 status = INVALID_OPERATION;
5350 } else {
5351 reconfig = true;
5352 }
5353 }
5354 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005355 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005356 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005357 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005358 mStandby = true;
5359 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005360 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005361 }
5362 if (status == NO_ERROR && reconfig) {
5363 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005364 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005365 }
5366 }
5367
Eric Laurent42537be2016-01-08 17:16:42 -08005368 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005369}
5370
5371uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5372{
5373 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005374 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005375 time = PlaybackThread::activeSleepTimeUs();
5376 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005377 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005378 }
5379 return time;
5380}
5381
5382uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5383{
5384 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005385 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005386 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5387 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005388 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005389 }
5390 return time;
5391}
5392
5393uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5394{
5395 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005396 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005397 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5398 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005399 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005400 }
5401 return time;
5402}
5403
5404void AudioFlinger::DirectOutputThread::cacheParameters_l()
5405{
5406 PlaybackThread::cacheParameters_l();
5407
5408 // use shorter standby delay as on normal output to release
5409 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005410 // no delay on outputs with HW A/V sync
5411 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005412 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005413 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005414 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005415 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005416 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005417 }
Eric Laurent81784c32012-11-19 14:55:58 -08005418}
5419
Eric Laurente659ef42014-09-29 13:06:46 -07005420void AudioFlinger::DirectOutputThread::flushHw_l()
5421{
Phil Burk062e67a2015-02-11 13:40:50 -08005422 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005423 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005424 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005425}
5426
Andy Hung10cbff12017-02-21 17:30:14 -08005427int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5428 // If a VolumeShaper is active, we must wake up periodically to update volume.
5429 const int64_t NS_PER_MS = 1000000;
5430 return mVolumeShaperActive ?
5431 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5432}
5433
Eric Laurent81784c32012-11-19 14:55:58 -08005434// ----------------------------------------------------------------------------
5435
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005437 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005438 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005439 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005440 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005441 mDrainSequence(0),
5442 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005443{
5444}
5445
5446AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5447{
5448}
5449
5450void AudioFlinger::AsyncCallbackThread::onFirstRef()
5451{
5452 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5453}
5454
5455bool AudioFlinger::AsyncCallbackThread::threadLoop()
5456{
5457 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005458 uint32_t writeAckSequence;
5459 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005460 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005461
5462 {
5463 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005464 while (!((mWriteAckSequence & 1) ||
5465 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005466 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005467 exitPending())) {
5468 mWaitWorkCV.wait(mLock);
5469 }
5470
Eric Laurentbfb1b832013-01-07 09:53:42 -08005471 if (exitPending()) {
5472 break;
5473 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005474 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5475 mWriteAckSequence, mDrainSequence);
5476 writeAckSequence = mWriteAckSequence;
5477 mWriteAckSequence &= ~1;
5478 drainSequence = mDrainSequence;
5479 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005480 asyncError = mAsyncError;
5481 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005482 }
5483 {
Eric Laurent4de95592013-09-26 15:28:21 -07005484 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5485 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005486 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005487 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005488 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005489 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005490 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005491 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005492 if (asyncError) {
5493 playbackThread->onAsyncError();
5494 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 }
5496 }
5497 }
5498 return false;
5499}
5500
5501void AudioFlinger::AsyncCallbackThread::exit()
5502{
5503 ALOGV("AsyncCallbackThread::exit");
5504 Mutex::Autolock _l(mLock);
5505 requestExit();
5506 mWaitWorkCV.broadcast();
5507}
5508
Eric Laurent3b4529e2013-09-05 18:09:19 -07005509void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005510{
5511 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005512 // bit 0 is cleared
5513 mWriteAckSequence = sequence << 1;
5514}
5515
5516void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5517{
5518 Mutex::Autolock _l(mLock);
5519 // ignore unexpected callbacks
5520 if (mWriteAckSequence & 2) {
5521 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005522 mWaitWorkCV.signal();
5523 }
5524}
5525
Eric Laurent3b4529e2013-09-05 18:09:19 -07005526void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005527{
5528 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005529 // bit 0 is cleared
5530 mDrainSequence = sequence << 1;
5531}
5532
5533void AudioFlinger::AsyncCallbackThread::resetDraining()
5534{
5535 Mutex::Autolock _l(mLock);
5536 // ignore unexpected callbacks
5537 if (mDrainSequence & 2) {
5538 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005539 mWaitWorkCV.signal();
5540 }
5541}
5542
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005543void AudioFlinger::AsyncCallbackThread::setAsyncError()
5544{
5545 Mutex::Autolock _l(mLock);
5546 mAsyncError = true;
5547 mWaitWorkCV.signal();
5548}
5549
Eric Laurentbfb1b832013-01-07 09:53:42 -08005550
5551// ----------------------------------------------------------------------------
5552AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005553 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5554 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005555 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5556 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005557{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005558 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005559 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005560 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005561}
5562
Eric Laurentbfb1b832013-01-07 09:53:42 -08005563void AudioFlinger::OffloadThread::threadLoop_exit()
5564{
5565 if (mFlushPending || mHwPaused) {
5566 // If a flush is pending or track was paused, just discard buffered data
5567 flushHw_l();
5568 } else {
5569 mMixerStatus = MIXER_DRAIN_ALL;
5570 threadLoop_drain();
5571 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005572 if (mUseAsyncWrite) {
5573 ALOG_ASSERT(mCallbackThread != 0);
5574 mCallbackThread->exit();
5575 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005576 PlaybackThread::threadLoop_exit();
5577}
5578
5579AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5580 Vector< sp<Track> > *tracksToRemove
5581)
5582{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005583 size_t count = mActiveTracks.size();
5584
5585 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005586 bool doHwPause = false;
5587 bool doHwResume = false;
5588
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005589 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005590
Eric Laurentbfb1b832013-01-07 09:53:42 -08005591 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005592 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005593 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005594#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005595 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005596#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005597 // Only consider last track started for volume and mixer state control.
5598 // In theory an older track could underrun and restart after the new one starts
5599 // but as we only care about the transition phase between two tracks on a
5600 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005601 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005602 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005603
Haynes Mathew George7844f672014-01-15 12:32:55 -08005604 if (track->isInvalid()) {
5605 ALOGW("An invalidated track shouldn't be in active list");
5606 tracksToRemove->add(track);
5607 continue;
5608 }
5609
5610 if (track->mState == TrackBase::IDLE) {
5611 ALOGW("An idle track shouldn't be in active list");
5612 continue;
5613 }
5614
Eric Laurentbfb1b832013-01-07 09:53:42 -08005615 if (track->isPausing()) {
5616 track->setPaused();
5617 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005618 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005619 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005620 mHwPaused = true;
5621 }
5622 // If we were part way through writing the mixbuffer to
5623 // the HAL we must save this until we resume
5624 // BUG - this will be wrong if a different track is made active,
5625 // in that case we want to discard the pending data in the
5626 // mixbuffer and tell the client to present it again when the
5627 // track is resumed
5628 mPausedWriteLength = mCurrentWriteLength;
5629 mPausedBytesRemaining = mBytesRemaining;
5630 mBytesRemaining = 0; // stop writing
5631 }
5632 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005633 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005634 if (track->isStopping_1()) {
5635 track->mRetryCount = kMaxTrackStopRetriesOffload;
5636 } else {
5637 track->mRetryCount = kMaxTrackRetriesOffload;
5638 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005639 track->flushAck();
5640 if (last) {
5641 mFlushPending = true;
5642 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005643 } else if (track->isResumePending()){
5644 track->resumeAck();
5645 if (last) {
5646 if (mPausedBytesRemaining) {
5647 // Need to continue write that was interrupted
5648 mCurrentWriteLength = mPausedWriteLength;
5649 mBytesRemaining = mPausedBytesRemaining;
5650 mPausedBytesRemaining = 0;
5651 }
5652 if (mHwPaused) {
5653 doHwResume = true;
5654 mHwPaused = false;
5655 // threadLoop_mix() will handle the case that we need to
5656 // resume an interrupted write
5657 }
5658 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005659 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005660
Eric Laurent3df841a2016-07-15 15:15:40 -07005661 mLeftVolFloat = mRightVolFloat = -1.0;
5662
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005663 // Do not handle new data in this iteration even if track->framesReady()
5664 mixerStatus = MIXER_TRACKS_ENABLED;
5665 }
5666 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005667 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005668 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005669 if (track->mFillingUpStatus == Track::FS_FILLED) {
5670 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005671 if (last) {
5672 // make sure processVolume_l() will apply new volume even if 0
5673 mLeftVolFloat = mRightVolFloat = -1.0;
5674 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005675 }
5676
5677 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005678 sp<Track> previousTrack = mPreviousTrack.promote();
5679 if (previousTrack != 0) {
5680 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005681 // Flush any data still being written from last track
5682 mBytesRemaining = 0;
5683 if (mPausedBytesRemaining) {
5684 // Last track was paused so we also need to flush saved
5685 // mixbuffer state and invalidate track so that it will
5686 // re-submit that unwritten data when it is next resumed
5687 mPausedBytesRemaining = 0;
5688 // Invalidate is a bit drastic - would be more efficient
5689 // to have a flag to tell client that some of the
5690 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005691 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005692 }
5693 // flush data already sent to the DSP if changing audio session as audio
5694 // comes from a different source. Also invalidate previous track to force a
5695 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005696 if (previousTrack->sessionId() != track->sessionId()) {
5697 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005698 }
5699 }
5700 }
5701 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005702 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005703 if (track->isStopping_1()) {
5704 track->mRetryCount = kMaxTrackStopRetriesOffload;
5705 } else {
5706 track->mRetryCount = kMaxTrackRetriesOffload;
5707 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005708 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005709 mixerStatus = MIXER_TRACKS_READY;
5710 }
5711 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005712 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005713 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005714 if (--(track->mRetryCount) <= 0) {
5715 // Hardware buffer can hold a large amount of audio so we must
5716 // wait for all current track's data to drain before we say
5717 // that the track is stopped.
5718 if (mBytesRemaining == 0) {
5719 // Only start draining when all data in mixbuffer
5720 // has been written
5721 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5722 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5723 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5724 if (last && !mStandby) {
5725 // do not modify drain sequence if we are already draining. This happens
5726 // when resuming from pause after drain.
5727 if ((mDrainSequence & 1) == 0) {
5728 mSleepTimeUs = 0;
5729 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5730 mixerStatus = MIXER_DRAIN_TRACK;
5731 mDrainSequence += 2;
5732 }
5733 if (mHwPaused) {
5734 // It is possible to move from PAUSED to STOPPING_1 without
5735 // a resume so we must ensure hardware is running
5736 doHwResume = true;
5737 mHwPaused = false;
5738 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 }
5740 }
Eric Laurente93cc032016-05-05 10:15:10 -07005741 } else if (last) {
5742 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5743 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744 }
5745 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005746 // Drain has completed or we are in standby, signal presentation complete
5747 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005748 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005749 uint32_t latency = 0;
5750 status_t result = mOutput->stream->getLatency(&latency);
5751 ALOGE_IF(result != OK,
5752 "Error when retrieving output stream latency: %d", result);
5753 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005754 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005755 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005756 track->presentationComplete(framesWritten, audioHALFrames);
5757 track->reset();
5758 tracksToRemove->add(track);
5759 }
5760 } else {
5761 // No buffers for this track. Give it a few chances to
5762 // fill a buffer, then remove it from active list.
5763 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005764 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005765 uint64_t position = 0;
5766 struct timespec unused;
5767 // The running check restarts the retry counter at least once.
5768 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5769 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5770 running = true;
5771 mOffloadUnderrunPosition = position;
5772 }
5773 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005774 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5775 (long long)position, (long long)mOffloadUnderrunPosition);
5776 }
5777 if (running) { // still running, give us more time.
5778 track->mRetryCount = kMaxTrackRetriesOffload;
5779 } else {
5780 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5781 track->name());
5782 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005783 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005784 // it will then automatically call start() when data is available
5785 track->disable();
5786 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005787 } else if (last){
5788 mixerStatus = MIXER_TRACKS_ENABLED;
5789 }
5790 }
5791 }
5792 // compute volume for this track
5793 processVolume_l(track, last);
5794 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005795
Eric Laurentea0fade2013-10-04 16:23:48 -07005796 // make sure the pause/flush/resume sequence is executed in the right order.
5797 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5798 // before flush and then resume HW. This can happen in case of pause/flush/resume
5799 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005800 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005801 status_t result = mOutput->stream->pause();
5802 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005803 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005804 if (mFlushPending) {
5805 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005806 }
Eric Laurentfd477972013-10-25 18:10:40 -07005807 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005808 status_t result = mOutput->stream->resume();
5809 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005810 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005811
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 // remove all the tracks that need to be...
5813 removeTracks_l(*tracksToRemove);
5814
5815 return mixerStatus;
5816}
5817
Eric Laurentbfb1b832013-01-07 09:53:42 -08005818// must be called with thread mutex locked
5819bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5820{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005821 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5822 mWriteAckSequence, mDrainSequence);
5823 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005824 return true;
5825 }
5826 return false;
5827}
5828
Eric Laurentbfb1b832013-01-07 09:53:42 -08005829bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5830{
5831 Mutex::Autolock _l(mLock);
5832 return waitingAsyncCallback_l();
5833}
5834
5835void AudioFlinger::OffloadThread::flushHw_l()
5836{
Eric Laurente659ef42014-09-29 13:06:46 -07005837 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005838 // Flush anything still waiting in the mixbuffer
5839 mCurrentWriteLength = 0;
5840 mBytesRemaining = 0;
5841 mPausedWriteLength = 0;
5842 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005843 // reset bytes written count to reflect that DSP buffers are empty after flush.
5844 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005845 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005846
Eric Laurentbfb1b832013-01-07 09:53:42 -08005847 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005848 // discard any pending drain or write ack by incrementing sequence
5849 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5850 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005851 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005852 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5853 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005854 }
5855}
5856
Haynes Mathew George05317d22016-05-03 16:34:26 -07005857void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5858{
5859 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005860 if (PlaybackThread::invalidateTracks_l(streamType)) {
5861 mFlushPending = true;
5862 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005863}
5864
Eric Laurentbfb1b832013-01-07 09:53:42 -08005865// ----------------------------------------------------------------------------
5866
Eric Laurent81784c32012-11-19 14:55:58 -08005867AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005868 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005869 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005870 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005871 mWaitTimeMs(UINT_MAX)
5872{
5873 addOutputTrack(mainThread);
5874}
5875
5876AudioFlinger::DuplicatingThread::~DuplicatingThread()
5877{
5878 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5879 mOutputTracks[i]->destroy();
5880 }
5881}
5882
5883void AudioFlinger::DuplicatingThread::threadLoop_mix()
5884{
5885 // mix buffers...
5886 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005887 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005888 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005889 if (mMixerBufferValid) {
5890 memset(mMixerBuffer, 0, mMixerBufferSize);
5891 } else {
5892 memset(mSinkBuffer, 0, mSinkBufferSize);
5893 }
Eric Laurent81784c32012-11-19 14:55:58 -08005894 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005895 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005896 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005897 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005898 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005899}
5900
5901void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5902{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005903 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005904 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005905 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005906 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005907 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005908 }
5909 } else if (mBytesWritten != 0) {
5910 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5911 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005912 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005913 } else {
5914 // flush remaining overflow buffers in output tracks
5915 writeFrames = 0;
5916 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005917 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005918 }
5919}
5920
Eric Laurentbfb1b832013-01-07 09:53:42 -08005921ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005922{
5923 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005924 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005925 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005926 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005927 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005928}
5929
5930void AudioFlinger::DuplicatingThread::threadLoop_standby()
5931{
5932 // DuplicatingThread implements standby by stopping all tracks
5933 for (size_t i = 0; i < outputTracks.size(); i++) {
5934 outputTracks[i]->stop();
5935 }
5936}
5937
5938void AudioFlinger::DuplicatingThread::saveOutputTracks()
5939{
5940 outputTracks = mOutputTracks;
5941}
5942
5943void AudioFlinger::DuplicatingThread::clearOutputTracks()
5944{
5945 outputTracks.clear();
5946}
5947
5948void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5949{
5950 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005951 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5952 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5953 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5954 const size_t frameCount =
5955 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5956 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5957 // from different OutputTracks and their associated MixerThreads (e.g. one may
5958 // nearly empty and the other may be dropping data).
5959
5960 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005961 this,
5962 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005963 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005964 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005965 frameCount,
5966 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005967 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5968 if (status != NO_ERROR) {
5969 ALOGE("addOutputTrack() initCheck failed %d", status);
5970 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005971 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005972 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5973 mOutputTracks.add(outputTrack);
5974 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5975 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005976}
5977
5978void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5979{
5980 Mutex::Autolock _l(mLock);
5981 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5982 if (mOutputTracks[i]->thread() == thread) {
5983 mOutputTracks[i]->destroy();
5984 mOutputTracks.removeAt(i);
5985 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005986 if (thread->getOutput() == mOutput) {
5987 mOutput = NULL;
5988 }
Eric Laurent81784c32012-11-19 14:55:58 -08005989 return;
5990 }
5991 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005992 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005993}
5994
5995// caller must hold mLock
5996void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5997{
5998 mWaitTimeMs = UINT_MAX;
5999 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6000 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6001 if (strong != 0) {
6002 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6003 if (waitTimeMs < mWaitTimeMs) {
6004 mWaitTimeMs = waitTimeMs;
6005 }
6006 }
6007 }
6008}
6009
6010
6011bool AudioFlinger::DuplicatingThread::outputsReady(
6012 const SortedVector< sp<OutputTrack> > &outputTracks)
6013{
6014 for (size_t i = 0; i < outputTracks.size(); i++) {
6015 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6016 if (thread == 0) {
6017 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6018 outputTracks[i].get());
6019 return false;
6020 }
6021 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6022 // see note at standby() declaration
6023 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6024 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6025 thread.get());
6026 return false;
6027 }
6028 }
6029 return true;
6030}
6031
6032uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6033{
6034 return (mWaitTimeMs * 1000) / 2;
6035}
6036
6037void AudioFlinger::DuplicatingThread::cacheParameters_l()
6038{
6039 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6040 updateWaitTime_l();
6041
6042 MixerThread::cacheParameters_l();
6043}
6044
Eric Laurent6acd1d42017-01-04 14:23:29 -08006045
Eric Laurent81784c32012-11-19 14:55:58 -08006046// ----------------------------------------------------------------------------
6047// Record
6048// ----------------------------------------------------------------------------
6049
6050AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6051 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006052 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006053 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006054 audio_devices_t inDevice,
6055 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006056#ifdef TEE_SINK
6057 , const sp<NBAIO_Sink>& teeSink
6058#endif
6059 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006060 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006061 mInput(input),
6062 mActiveTracks(&this->mLocalLog),
6063 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006064 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006065 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006066#ifdef TEE_SINK
6067 , mTeeSink(teeSink)
6068#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006069 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6070 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006071 // mFastCapture below
6072 , mFastCaptureFutex(0)
6073 // mInputSource
6074 // mPipeSink
6075 // mPipeSource
6076 , mPipeFramesP2(0)
6077 // mPipeMemory
6078 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006079 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006080 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006081{
Glenn Kastend7dca052015-03-05 16:05:54 -08006082 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6083 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006084
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006085 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006086
6087 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006088 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006089 size_t numCounterOffers = 0;
6090 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006091#if !LOG_NDEBUG
6092 ssize_t index =
6093#else
6094 (void)
6095#endif
6096 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006097 ALOG_ASSERT(index == 0);
6098
6099 // initialize fast capture depending on configuration
6100 bool initFastCapture;
6101 switch (kUseFastCapture) {
6102 case FastCapture_Never:
6103 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006104 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006105 break;
6106 case FastCapture_Always:
6107 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006108 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006109 break;
6110 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006111 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006112 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6113 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6114 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006115 break;
6116 // case FastCapture_Dynamic:
6117 }
6118
6119 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006120 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006121 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006122 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6123 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006124 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006125 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006126 const sp<MemoryDealer> roHeap(readOnlyHeap());
6127 sp<IMemory> pipeMemory;
6128 if ((roHeap == 0) ||
6129 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006130 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6131 ALOGE("not enough memory for pipe buffer size=%zu; "
6132 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6133 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6134 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006135 goto failed;
6136 }
6137 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6138 memset(pipeBuffer, 0, pipeSize);
6139 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6140 const NBAIO_Format offers[1] = {format};
6141 size_t numCounterOffers = 0;
6142 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6143 ALOG_ASSERT(index == 0);
6144 mPipeSink = pipe;
6145 PipeReader *pipeReader = new PipeReader(*pipe);
6146 numCounterOffers = 0;
6147 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6148 ALOG_ASSERT(index == 0);
6149 mPipeSource = pipeReader;
6150 mPipeFramesP2 = pipeFramesP2;
6151 mPipeMemory = pipeMemory;
6152
6153 // create fast capture
6154 mFastCapture = new FastCapture();
6155 FastCaptureStateQueue *sq = mFastCapture->sq();
6156#ifdef STATE_QUEUE_DUMP
6157 // FIXME
6158#endif
6159 FastCaptureState *state = sq->begin();
6160 state->mCblk = NULL;
6161 state->mInputSource = mInputSource.get();
6162 state->mInputSourceGen++;
6163 state->mPipeSink = pipe;
6164 state->mPipeSinkGen++;
6165 state->mFrameCount = mFrameCount;
6166 state->mCommand = FastCaptureState::COLD_IDLE;
6167 // already done in constructor initialization list
6168 //mFastCaptureFutex = 0;
6169 state->mColdFutexAddr = &mFastCaptureFutex;
6170 state->mColdGen++;
6171 state->mDumpState = &mFastCaptureDumpState;
6172#ifdef TEE_SINK
6173 // FIXME
6174#endif
6175 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6176 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6177 sq->end();
6178 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6179
6180 // start the fast capture
6181 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6182 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006183 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006184 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006185#ifdef AUDIO_WATCHDOG
6186 // FIXME
6187#endif
6188
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006189 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006190 }
6191failed: ;
6192
6193 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006194}
6195
Eric Laurent81784c32012-11-19 14:55:58 -08006196AudioFlinger::RecordThread::~RecordThread()
6197{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006198 if (mFastCapture != 0) {
6199 FastCaptureStateQueue *sq = mFastCapture->sq();
6200 FastCaptureState *state = sq->begin();
6201 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6202 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6203 if (old == -1) {
6204 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6205 }
6206 }
6207 state->mCommand = FastCaptureState::EXIT;
6208 sq->end();
6209 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6210 mFastCapture->join();
6211 mFastCapture.clear();
6212 }
6213 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006214 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006215 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006216}
6217
6218void AudioFlinger::RecordThread::onFirstRef()
6219{
Glenn Kastend7dca052015-03-05 16:05:54 -08006220 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006221}
6222
Eric Laurent555530a2017-02-07 18:17:24 -08006223void AudioFlinger::RecordThread::preExit()
6224{
6225 ALOGV(" preExit()");
6226 Mutex::Autolock _l(mLock);
6227 for (size_t i = 0; i < mTracks.size(); i++) {
6228 sp<RecordTrack> track = mTracks[i];
6229 track->invalidate();
6230 }
6231 mActiveTracks.clear();
6232 mStartStopCond.broadcast();
6233}
6234
Eric Laurent81784c32012-11-19 14:55:58 -08006235bool AudioFlinger::RecordThread::threadLoop()
6236{
Eric Laurent81784c32012-11-19 14:55:58 -08006237 nsecs_t lastWarning = 0;
6238
6239 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006240
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006241reacquire_wakelock:
6242 sp<RecordTrack> activeTrack;
6243 {
6244 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006245 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006246 }
6247
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006248 // used to request a deferred sleep, to be executed later while mutex is unlocked
6249 uint32_t sleepUs = 0;
6250
6251 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006252 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006253 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 // activeTracks accumulates a copy of a subset of mActiveTracks
6256 Vector< sp<RecordTrack> > activeTracks;
6257
Glenn Kasten735f45f2014-08-18 15:51:59 -07006258 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006259 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006260
Glenn Kasten735f45f2014-08-18 15:51:59 -07006261 // reference to a fast track which is about to be removed
6262 sp<RecordTrack> fastTrackToRemove;
6263
Eric Laurent81784c32012-11-19 14:55:58 -08006264 { // scope for mLock
6265 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006266
Eric Laurent021cf962014-05-13 10:18:14 -07006267 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006268
Eric Laurent000a4192014-01-29 15:17:32 -08006269 // check exitPending here because checkForNewParameters_l() and
6270 // checkForNewParameters_l() can temporarily release mLock
6271 if (exitPending()) {
6272 break;
6273 }
6274
Eric Laurent5c25d562016-07-13 17:17:45 -07006275 // sleep with mutex unlocked
6276 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006277 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006278 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6279 ATRACE_END();
6280 sleepUs = 0;
6281 continue;
6282 }
6283
Glenn Kasten2b806402013-11-20 16:37:38 -08006284 // if no active track(s), then standby and release wakelock
6285 size_t size = mActiveTracks.size();
6286 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006287 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006288 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006289 releaseWakeLock_l();
6290 ALOGV("RecordThread: loop stopping");
6291 // go to sleep
6292 mWaitWorkCV.wait(mLock);
6293 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006294 goto reacquire_wakelock;
6295 }
6296
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006297 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006298 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006299 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006301 activeTrack = mActiveTracks[i];
6302 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006303 if (activeTrack->isFastTrack()) {
6304 ALOG_ASSERT(fastTrackToRemove == 0);
6305 fastTrackToRemove = activeTrack;
6306 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006308 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006309 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006310 continue;
6311 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006312
6313 TrackBase::track_state activeTrackState = activeTrack->mState;
6314 switch (activeTrackState) {
6315
6316 case TrackBase::PAUSING:
6317 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006318 doBroadcast = true;
6319 size--;
6320 continue;
6321
6322 case TrackBase::STARTING_1:
6323 sleepUs = 10000;
6324 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006325 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006326 continue;
6327
6328 case TrackBase::STARTING_2:
6329 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006330 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006331 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006332 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006333 break;
6334
6335 case 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::IDLE:
6340 i++;
6341 continue;
6342
6343 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006344 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006345 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006346
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006347 activeTracks.add(activeTrack);
6348 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006349
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006350 if (activeTrack->isFastTrack()) {
6351 ALOG_ASSERT(!mFastTrackAvail);
6352 ALOG_ASSERT(fastTrack == 0);
6353 fastTrack = activeTrack;
6354 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006355 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006356
Andy Hungdae27702016-10-31 14:01:16 -07006357 mActiveTracks.updatePowerState(this);
6358
Eric Laurent5c25d562016-07-13 17:17:45 -07006359 if (allStopped) {
6360 standbyIfNotAlreadyInStandby();
6361 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006362 if (doBroadcast) {
6363 mStartStopCond.broadcast();
6364 }
6365
6366 // sleep if there are no active tracks to process
6367 if (activeTracks.size() == 0) {
6368 if (sleepUs == 0) {
6369 sleepUs = kRecordThreadSleepUs;
6370 }
6371 continue;
6372 }
6373 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006374
Eric Laurent81784c32012-11-19 14:55:58 -08006375 lockEffectChains_l(effectChains);
6376 }
6377
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006378 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006379
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006380 size_t size = effectChains.size();
6381 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006382 // thread mutex is not locked, but effect chain is locked
6383 effectChains[i]->process_l();
6384 }
6385
Glenn Kasten735f45f2014-08-18 15:51:59 -07006386 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006387 if (mFastCapture != 0) {
6388 FastCaptureStateQueue *sq = mFastCapture->sq();
6389 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006390 bool didModify = false;
6391 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006392 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6393 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6394 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6395 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6396 if (old == -1) {
6397 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6398 }
6399 }
6400 state->mCommand = FastCaptureState::READ_WRITE;
6401#if 0 // FIXME
6402 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006403 FastThreadDumpState::kSamplingNforLowRamDevice :
6404 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006405#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006406 didModify = true;
6407 }
6408 audio_track_cblk_t *cblkOld = state->mCblk;
6409 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6410 if (cblkNew != cblkOld) {
6411 state->mCblk = cblkNew;
6412 // block until acked if removing a fast track
6413 if (cblkOld != NULL) {
6414 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6415 }
6416 didModify = true;
6417 }
6418 sq->end(didModify);
6419 if (didModify) {
6420 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006421#if 0
6422 if (kUseFastCapture == FastCapture_Dynamic) {
6423 mNormalSource = mPipeSource;
6424 }
6425#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006426 }
6427 }
6428
Glenn Kasten735f45f2014-08-18 15:51:59 -07006429 // now run the fast track destructor with thread mutex unlocked
6430 fastTrackToRemove.clear();
6431
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006432 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6433 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6434 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6435 // If destination is non-contiguous, first read past the nominal end of buffer, then
6436 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006437
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006439 ssize_t framesRead;
6440
6441 // If an NBAIO source is present, use it to read the normal capture's data
6442 if (mPipeSource != 0) {
6443 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006444 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006445 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006446 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006447 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6448 // buffer size or at least for 20ms.
6449 size_t sleepFrames = max(
6450 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6451 if (framesRead <= (ssize_t) sleepFrames) {
6452 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6453 }
6454 if (framesRead < 0) {
6455 status_t status = (status_t) framesRead;
6456 switch (status) {
6457 case OVERRUN:
6458 ALOGW("overrun on read from pipe");
6459 framesRead = 0;
6460 break;
6461 case NEGOTIATE:
6462 ALOGE("re-negotiation is needed");
6463 framesRead = -1; // Will cause an attempt to recover.
6464 break;
6465 default:
6466 ALOGE("unknown error %d on read from pipe", status);
6467 break;
6468 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006469 }
6470 // otherwise use the HAL / AudioStreamIn directly
6471 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006472 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006473 size_t bytesRead;
6474 status_t result = mInput->stream->read(
6475 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006476 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006477 if (result < 0) {
6478 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006479 } else {
6480 framesRead = bytesRead / mFrameSize;
6481 }
6482 }
6483
Andy Hung3f0c9022016-01-15 17:49:46 -08006484 // Update server timestamp with server stats
6485 // systemTime() is optional if the hardware supports timestamps.
6486 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6487 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6488
6489 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006490 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006491 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006492 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006493 if (ret == NO_ERROR) {
6494 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6495 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6496 // Note: In general record buffers should tend to be empty in
6497 // a properly running pipeline.
6498 //
6499 // Also, it is not advantageous to call get_presentation_position during the read
6500 // as the read obtains a lock, preventing the timestamp call from executing.
6501 }
6502 }
6503 // Use this to track timestamp information
6504 // ALOGD("%s", mTimestamp.toString().c_str());
6505
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006506 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006507 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006508 // Force input into standby so that it tries to recover at next read attempt
6509 inputStandBy();
6510 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006511 }
6512 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006513 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006514 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006515 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006516
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006517 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006518 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006519 }
6520 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006521 {
6522 size_t part1 = mRsmpInFramesP2 - rear;
6523 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006524 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006525 (framesRead - part1) * mFrameSize);
6526 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006527 }
6528 rear = mRsmpInRear += framesRead;
6529
6530 size = activeTracks.size();
6531 // loop over each active track
6532 for (size_t i = 0; i < size; i++) {
6533 activeTrack = activeTracks[i];
6534
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006535 // skip fast tracks, as those are handled directly by FastCapture
6536 if (activeTrack->isFastTrack()) {
6537 continue;
6538 }
6539
Andy Hung73c02e42015-03-29 01:13:58 -07006540 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006541 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6542
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006543 enum {
6544 OVERRUN_UNKNOWN,
6545 OVERRUN_TRUE,
6546 OVERRUN_FALSE
6547 } overrun = OVERRUN_UNKNOWN;
6548
6549 // loop over getNextBuffer to handle circular sink
6550 for (;;) {
6551
6552 activeTrack->mSink.frameCount = ~0;
6553 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6554 size_t framesOut = activeTrack->mSink.frameCount;
6555 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6556
Andy Hung73c02e42015-03-29 01:13:58 -07006557 // check available frames and handle overrun conditions
6558 // if the record track isn't draining fast enough.
6559 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006560 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006561 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6562 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006563 overrun = OVERRUN_TRUE;
6564 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006565 if (framesOut == 0 || framesIn == 0) {
6566 break;
6567 }
6568
Andy Hung6770c6f2015-04-07 13:43:36 -07006569 // Don't allow framesOut to be larger than what is possible with resampling
6570 // from framesIn.
6571 // This isn't strictly necessary but helps limit buffer resizing in
6572 // RecordBufferConverter. TODO: remove when no longer needed.
6573 framesOut = min(framesOut,
6574 destinationFramesPossible(
6575 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006576 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6577 framesOut = activeTrack->mRecordBufferConverter->convert(
6578 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006579
6580 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6581 overrun = OVERRUN_FALSE;
6582 }
6583
6584 if (activeTrack->mFramesToDrop == 0) {
6585 if (framesOut > 0) {
6586 activeTrack->mSink.frameCount = framesOut;
6587 activeTrack->releaseBuffer(&activeTrack->mSink);
6588 }
6589 } else {
6590 // FIXME could do a partial drop of framesOut
6591 if (activeTrack->mFramesToDrop > 0) {
6592 activeTrack->mFramesToDrop -= framesOut;
6593 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006594 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006595 }
6596 } else {
6597 activeTrack->mFramesToDrop += framesOut;
6598 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6599 activeTrack->mSyncStartEvent->isCancelled()) {
6600 ALOGW("Synced record %s, session %d, trigger session %d",
6601 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6602 activeTrack->sessionId(),
6603 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006604 activeTrack->mSyncStartEvent->triggerSession() :
6605 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006606 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006607 }
6608 }
6609 }
6610
6611 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006612 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006613 }
6614 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006615
6616 switch (overrun) {
6617 case OVERRUN_TRUE:
6618 // client isn't retrieving buffers fast enough
6619 if (!activeTrack->setOverflow()) {
6620 nsecs_t now = systemTime();
6621 // FIXME should lastWarning per track?
6622 if ((now - lastWarning) > kWarningThrottleNs) {
6623 ALOGW("RecordThread: buffer overflow");
6624 lastWarning = now;
6625 }
6626 }
6627 break;
6628 case OVERRUN_FALSE:
6629 activeTrack->clearOverflow();
6630 break;
6631 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006632 break;
6633 }
6634
Andy Hung3f0c9022016-01-15 17:49:46 -08006635 // update frame information and push timestamp out
6636 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006637 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006638 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6639 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006640 }
6641
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006642unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006643 // enable changes in effect chain
6644 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006645 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006646 }
6647
Glenn Kasten93e471f2013-08-19 08:40:07 -07006648 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006649
6650 {
6651 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006652 for (size_t i = 0; i < mTracks.size(); i++) {
6653 sp<RecordTrack> track = mTracks[i];
6654 track->invalidate();
6655 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006656 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006657 mStartStopCond.broadcast();
6658 }
6659
6660 releaseWakeLock();
6661
6662 ALOGV("RecordThread %p exiting", this);
6663 return false;
6664}
6665
Glenn Kasten93e471f2013-08-19 08:40:07 -07006666void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006667{
6668 if (!mStandby) {
6669 inputStandBy();
6670 mStandby = true;
6671 }
6672}
6673
6674void AudioFlinger::RecordThread::inputStandBy()
6675{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006676 // Idle the fast capture if it's currently running
6677 if (mFastCapture != 0) {
6678 FastCaptureStateQueue *sq = mFastCapture->sq();
6679 FastCaptureState *state = sq->begin();
6680 if (!(state->mCommand & FastCaptureState::IDLE)) {
6681 state->mCommand = FastCaptureState::COLD_IDLE;
6682 state->mColdFutexAddr = &mFastCaptureFutex;
6683 state->mColdGen++;
6684 mFastCaptureFutex = 0;
6685 sq->end();
6686 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6687 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6688#if 0
6689 if (kUseFastCapture == FastCapture_Dynamic) {
6690 // FIXME
6691 }
6692#endif
6693#ifdef AUDIO_WATCHDOG
6694 // FIXME
6695#endif
6696 } else {
6697 sq->end(false /*didModify*/);
6698 }
6699 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006700 status_t result = mInput->stream->standby();
6701 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006702
6703 // If going into standby, flush the pipe source.
6704 if (mPipeSource.get() != nullptr) {
6705 const ssize_t flushed = mPipeSource->flush();
6706 if (flushed > 0) {
6707 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6708 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6709 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6710 }
6711 }
Eric Laurent81784c32012-11-19 14:55:58 -08006712}
6713
Glenn Kasten05997e22014-03-13 15:08:33 -07006714// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006715sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006716 const sp<AudioFlinger::Client>& client,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006717 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006718 audio_format_t format,
6719 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006720 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006721 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006722 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006723 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006724 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006725 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006726 status_t *status,
6727 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006728{
Glenn Kasten74935e42013-12-19 08:56:45 -08006729 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006730 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006731 sp<RecordTrack> track;
6732 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006733 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006734 audio_input_flags_t requestedFlags = *flags;
6735 uint32_t sampleRate;
6736
6737 lStatus = initCheck();
6738 if (lStatus != NO_ERROR) {
6739 ALOGE("createRecordTrack_l() audio driver not initialized");
6740 goto Exit;
6741 }
6742
6743 if (*pSampleRate == 0) {
6744 *pSampleRate = mSampleRate;
6745 }
6746 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006747
6748 // special case for FAST flag considered OK if fast capture is present
6749 if (hasFastCapture()) {
6750 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6751 }
6752
Eric Laurentf14db3c2017-12-08 14:20:36 -08006753 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006754 if ((*flags & inputFlags) != *flags) {
6755 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6756 " input flags (%08x)",
6757 *flags, inputFlags);
6758 *flags = (audio_input_flags_t)(*flags & inputFlags);
6759 }
Eric Laurent81784c32012-11-19 14:55:58 -08006760
Glenn Kasten90e58b12013-07-31 16:16:02 -07006761 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006762 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006763 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006764 // we formerly checked for a callback handler (non-0 tid),
6765 // but that is no longer required for TRANSFER_OBTAIN mode
6766 //
Glenn Kasten74105912014-07-03 12:28:53 -07006767 // frame count is not specified, or is exactly the pipe depth
6768 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006769 // PCM data
6770 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006771 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006772 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006773 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006774 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006775 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006776 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006777 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006778 hasFastCapture() &&
6779 // there are sufficient fast track slots available
6780 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006781 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006782 // check compatibility with audio effects.
6783 Mutex::Autolock _l(mLock);
6784 // Do not accept FAST flag if the session has software effects
6785 sp<EffectChain> chain = getEffectChain_l(sessionId);
6786 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006787 audio_input_flags_t old = *flags;
6788 chain->checkInputFlagCompatibility(flags);
6789 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006790 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6791 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006792 }
6793 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006794 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006795 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6796 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006797 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006798 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6799 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006800 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006801 this, frameCount, mFrameCount, mPipeFramesP2,
6802 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006803 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006804 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006805 }
6806 }
6807
Eric Laurentf14db3c2017-12-08 14:20:36 -08006808 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
6809 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
6810 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
6811 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
6812 lStatus = BAD_TYPE;
6813 goto Exit;
6814 }
6815
Glenn Kasten74105912014-07-03 12:28:53 -07006816 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006817 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006818 // fast track: frame count is exactly the pipe depth
6819 frameCount = mPipeFramesP2;
6820 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08006821 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07006822 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006823 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6824 // or 20 ms if there is a fast capture
6825 // TODO This could be a roundupRatio inline, and const
6826 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6827 * sampleRate + mSampleRate - 1) / mSampleRate;
6828 // minimum number of notification periods is at least kMinNotifications,
6829 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6830 static const size_t kMinNotifications = 3;
6831 static const uint32_t kMinMs = 30;
6832 // TODO This could be a roundupRatio inline
6833 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6834 // TODO This could be a roundupRatio inline
6835 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6836 maxNotificationFrames;
6837 const size_t minFrameCount = maxNotificationFrames *
6838 max(kMinNotifications, minNotificationsByMs);
6839 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08006840 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
6841 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006842 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006843 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006844 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006845 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006846
6847 { // scope for mLock
6848 Mutex::Autolock _l(mLock);
6849
6850 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006851 format, channelMask, frameCount,
6852 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006853 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006854
Glenn Kasten03003332013-08-06 15:40:54 -07006855 lStatus = track->initCheck();
6856 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006857 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006858 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006859 goto Exit;
6860 }
6861 mTracks.add(track);
6862
Eric Laurent05067782016-06-01 18:27:28 -07006863 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006864 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6865 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6866 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006867 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006868 }
Eric Laurent81784c32012-11-19 14:55:58 -08006869 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006870
Eric Laurent81784c32012-11-19 14:55:58 -08006871 lStatus = NO_ERROR;
6872
6873Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006874 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006875 return track;
6876}
6877
6878status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6879 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006880 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006881{
6882 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6883 sp<ThreadBase> strongMe = this;
6884 status_t status = NO_ERROR;
6885
6886 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006887 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006888 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006889 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006890 triggerSession,
6891 recordTrack->sessionId(),
6892 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006893 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006894 // Sync event can be cancelled by the trigger session if the track is not in a
6895 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006896 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006897 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006898 } else {
6899 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08006900 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006901 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006902 }
6903 }
6904
6905 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006906 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006907 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006908 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6909 if (recordTrack->mState == TrackBase::PAUSING) {
6910 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006911 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006912 } else {
6913 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006914 }
6915 return status;
6916 }
6917
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006918 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6919 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6920 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006921 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006922 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006923 status_t status = NO_ERROR;
6924 if (recordTrack->isExternalTrack()) {
6925 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006926 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006927 mLock.lock();
6928 // FIXME should verify that recordTrack is still in mActiveTracks
6929 if (status != NO_ERROR) {
6930 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006931 recordTrack->clearSyncStartEvent();
6932 ALOGV("RecordThread::start error %d", status);
6933 return status;
6934 }
Eric Laurent81784c32012-11-19 14:55:58 -08006935 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006936 // Catch up with current buffer indices if thread is already running.
6937 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6938 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6939 // see previously buffered data before it called start(), but with greater risk of overrun.
6940
Andy Hung73c02e42015-03-29 01:13:58 -07006941 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006942 // clear any converter state as new data will be discontinuous
6943 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006944 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006945 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006946 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006947 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006948 ALOGV("Record failed to start");
6949 status = BAD_VALUE;
6950 goto startError;
6951 }
Eric Laurent81784c32012-11-19 14:55:58 -08006952 return status;
6953 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006954
Eric Laurent81784c32012-11-19 14:55:58 -08006955startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006956 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006957 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006958 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006959 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006960 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006961 return status;
6962}
6963
Eric Laurent81784c32012-11-19 14:55:58 -08006964void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6965{
6966 sp<SyncEvent> strongEvent = event.promote();
6967
6968 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006969 sp<RefBase> ptr = strongEvent->cookie().promote();
6970 if (ptr != 0) {
6971 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6972 recordTrack->handleSyncStartEvent(strongEvent);
6973 }
Eric Laurent81784c32012-11-19 14:55:58 -08006974 }
6975}
6976
Glenn Kastena8356f62013-07-25 14:37:52 -07006977bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006978 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006979 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006980 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006981 return false;
6982 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006983 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006984 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006985 // signal thread to stop
6986 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006987 // do not wait for mStartStopCond if exiting
6988 if (exitPending()) {
6989 return true;
6990 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006991 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006992 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006993 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006994 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006995 ALOGV("Record stopped OK");
6996 return true;
6997 }
6998 return false;
6999}
7000
Glenn Kasten0f11b512014-01-31 16:18:54 -08007001bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007002{
7003 return false;
7004}
7005
Glenn Kasten0f11b512014-01-31 16:18:54 -08007006status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007007{
7008#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7009 if (!isValidSyncEvent(event)) {
7010 return BAD_VALUE;
7011 }
7012
Glenn Kastend848eb42016-03-08 13:42:11 -08007013 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007014 status_t ret = NAME_NOT_FOUND;
7015
7016 Mutex::Autolock _l(mLock);
7017
7018 for (size_t i = 0; i < mTracks.size(); i++) {
7019 sp<RecordTrack> track = mTracks[i];
7020 if (eventSession == track->sessionId()) {
7021 (void) track->setSyncEvent(event);
7022 ret = NO_ERROR;
7023 }
7024 }
7025 return ret;
7026#else
7027 return BAD_VALUE;
7028#endif
7029}
7030
7031// destroyTrack_l() must be called with ThreadBase::mLock held
7032void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7033{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007034 track->terminate();
7035 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007036 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007037 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007038 removeTrack_l(track);
7039 }
7040}
7041
7042void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7043{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007044 String8 result;
7045 track->appendDump(result, false /* active */);
7046 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7047
Eric Laurent81784c32012-11-19 14:55:58 -08007048 mTracks.remove(track);
7049 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007050 if (track->isFastTrack()) {
7051 ALOG_ASSERT(!mFastTrackAvail);
7052 mFastTrackAvail = true;
7053 }
Eric Laurent81784c32012-11-19 14:55:58 -08007054}
7055
7056void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7057{
7058 dumpInternals(fd, args);
7059 dumpTracks(fd, args);
7060 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007061 dprintf(fd, " Local log:\n");
7062 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007063}
7064
7065void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7066{
Glenn Kasten44182c22015-03-05 17:12:23 -08007067 dumpBase(fd, args);
7068
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007069 AudioStreamIn *input = mInput;
7070 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7071 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7072 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007073 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007074 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007075 }
Andy Hungbfa64962017-06-12 14:43:19 -07007076
7077 if (input != nullptr) {
7078 dprintf(fd, " Hal stream dump:\n");
7079 (void)input->stream->dump(fd);
7080 }
7081
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007082 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007083 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007084
Glenn Kasten2f90c512015-12-02 11:40:09 -08007085 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7086 // while we are dumping it. It may be inconsistent, but it won't mutate!
7087 // This is a large object so we place it on the heap.
7088 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7089 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7090 copy->dump(fd);
7091 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007092}
7093
Glenn Kasten0f11b512014-01-31 16:18:54 -08007094void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007095{
Eric Laurent81784c32012-11-19 14:55:58 -08007096 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007097 size_t numtracks = mTracks.size();
7098 size_t numactive = mActiveTracks.size();
7099 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007100 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007101 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007102 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007103 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007104 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007105 RecordTrack::appendDumpHeader(result);
7106 for (size_t i = 0; i < numtracks ; ++i) {
7107 sp<RecordTrack> track = mTracks[i];
7108 if (track != 0) {
7109 bool active = mActiveTracks.indexOf(track) >= 0;
7110 if (active) {
7111 numactiveseen++;
7112 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007113 result.append(prefix);
7114 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007115 }
Eric Laurent81784c32012-11-19 14:55:58 -08007116 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007117 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007118 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007119 }
7120
Marco Nelissenb2208842014-02-07 14:00:50 -08007121 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007122 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007123 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007124 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007125 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007126 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007127 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007128 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007129 result.append(prefix);
7130 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007131 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007132 }
Eric Laurent81784c32012-11-19 14:55:58 -08007133
7134 }
7135 write(fd, result.string(), result.size());
7136}
7137
Andy Hung73c02e42015-03-29 01:13:58 -07007138
7139void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7140{
7141 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7142 RecordThread *recordThread = (RecordThread *) threadBase.get();
7143 mRsmpInFront = recordThread->mRsmpInRear;
7144 mRsmpInUnrel = 0;
7145}
7146
7147void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7148 size_t *framesAvailable, bool *hasOverrun)
7149{
7150 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7151 RecordThread *recordThread = (RecordThread *) threadBase.get();
7152 const int32_t rear = recordThread->mRsmpInRear;
7153 const int32_t front = mRsmpInFront;
7154 const ssize_t filled = rear - front;
7155
7156 size_t framesIn;
7157 bool overrun = false;
7158 if (filled < 0) {
7159 // should not happen, but treat like a massive overrun and re-sync
7160 framesIn = 0;
7161 mRsmpInFront = rear;
7162 overrun = true;
7163 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7164 framesIn = (size_t) filled;
7165 } else {
7166 // client is not keeping up with server, but give it latest data
7167 framesIn = recordThread->mRsmpInFrames;
7168 mRsmpInFront = /* front = */ rear - framesIn;
7169 overrun = true;
7170 }
7171 if (framesAvailable != NULL) {
7172 *framesAvailable = framesIn;
7173 }
7174 if (hasOverrun != NULL) {
7175 *hasOverrun = overrun;
7176 }
7177}
7178
Eric Laurent81784c32012-11-19 14:55:58 -08007179// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007180status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007181 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007182{
Andy Hung73c02e42015-03-29 01:13:58 -07007183 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007184 if (threadBase == 0) {
7185 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007186 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007187 return NOT_ENOUGH_DATA;
7188 }
7189 RecordThread *recordThread = (RecordThread *) threadBase.get();
7190 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007191 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007192 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007193 // FIXME should not be P2 (don't want to increase latency)
7194 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007195 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007196 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007197 front &= recordThread->mRsmpInFramesP2 - 1;
7198 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007199 if (part1 > (size_t) filled) {
7200 part1 = filled;
7201 }
7202 size_t ask = buffer->frameCount;
7203 ALOG_ASSERT(ask > 0);
7204 if (part1 > ask) {
7205 part1 = ask;
7206 }
7207 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007208 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007209 buffer->raw = NULL;
7210 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007211 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007212 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007213 }
7214
Andy Hung57446612015-04-19 23:56:46 -07007215 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007216 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007217 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007218 return NO_ERROR;
7219}
7220
7221// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007222void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7223 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007224{
Glenn Kasten85948432013-08-19 12:09:05 -07007225 size_t stepCount = buffer->frameCount;
7226 if (stepCount == 0) {
7227 return;
7228 }
Andy Hung73c02e42015-03-29 01:13:58 -07007229 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7230 mRsmpInUnrel -= stepCount;
7231 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007232 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007233 buffer->frameCount = 0;
7234}
7235
Eric Laurentd8365c52017-07-16 15:27:05 -07007236void AudioFlinger::RecordThread::checkBtNrec()
7237{
7238 Mutex::Autolock _l(mLock);
7239 checkBtNrec_l();
7240}
7241
7242void AudioFlinger::RecordThread::checkBtNrec_l()
7243{
7244 // disable AEC and NS if the device is a BT SCO headset supporting those
7245 // pre processings
7246 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7247 mAudioFlinger->btNrecIsOff();
7248 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7249 for (size_t i = 0; i < mEffectChains.size(); i++) {
7250 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7251 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7252 }
7253 }
7254}
7255
Andy Hung97a893e2015-03-29 01:03:07 -07007256
Eric Laurent10351942014-05-08 18:49:52 -07007257bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7258 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007259{
7260 bool reconfig = false;
7261
Eric Laurent10351942014-05-08 18:49:52 -07007262 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007263
Eric Laurent10351942014-05-08 18:49:52 -07007264 audio_format_t reqFormat = mFormat;
7265 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007266 // 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 -07007267 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7268
7269 AudioParameter param = AudioParameter(keyValuePair);
7270 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007271
7272 // scope for AutoPark extends to end of method
7273 AutoPark<FastCapture> park(mFastCapture);
7274
Eric Laurent10351942014-05-08 18:49:52 -07007275 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7276 // channel count change can be requested. Do we mandate the first client defines the
7277 // HAL sampling rate and channel count or do we allow changes on the fly?
7278 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7279 samplingRate = value;
7280 reconfig = true;
7281 }
7282 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007283 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007284 status = BAD_VALUE;
7285 } else {
7286 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007287 reconfig = true;
7288 }
Eric Laurent10351942014-05-08 18:49:52 -07007289 }
7290 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7291 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007292 if (!audio_is_input_channel(mask) ||
7293 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007294 status = BAD_VALUE;
7295 } else {
7296 channelMask = mask;
7297 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007298 }
Eric Laurent10351942014-05-08 18:49:52 -07007299 }
7300 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7301 // do not accept frame count changes if tracks are open as the track buffer
7302 // size depends on frame count and correct behavior would not be guaranteed
7303 // if frame count is changed after track creation
7304 if (mActiveTracks.size() > 0) {
7305 status = INVALID_OPERATION;
7306 } else {
7307 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007308 }
Eric Laurent10351942014-05-08 18:49:52 -07007309 }
7310 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7311 // forward device change to effects that have requested to be
7312 // aware of attached audio device.
7313 for (size_t i = 0; i < mEffectChains.size(); i++) {
7314 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007315 }
Eric Laurent81784c32012-11-19 14:55:58 -08007316
Eric Laurent10351942014-05-08 18:49:52 -07007317 // store input device and output device but do not forward output device to audio HAL.
7318 // Note that status is ignored by the caller for output device
7319 // (see AudioFlinger::setParameters()
7320 if (audio_is_output_devices(value)) {
7321 mOutDevice = value;
7322 status = BAD_VALUE;
7323 } else {
7324 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007325 if (value != AUDIO_DEVICE_NONE) {
7326 mPrevInDevice = value;
7327 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007328 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007329 }
Eric Laurent10351942014-05-08 18:49:52 -07007330 }
7331 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7332 mAudioSource != (audio_source_t)value) {
7333 // forward device change to effects that have requested to be
7334 // aware of attached audio device.
7335 for (size_t i = 0; i < mEffectChains.size(); i++) {
7336 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007337 }
Eric Laurent10351942014-05-08 18:49:52 -07007338 mAudioSource = (audio_source_t)value;
7339 }
Glenn Kastene198c362013-08-13 09:13:36 -07007340
Eric Laurent10351942014-05-08 18:49:52 -07007341 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007342 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007343 if (status == INVALID_OPERATION) {
7344 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007345 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007346 }
7347 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007348 if (status == BAD_VALUE) {
7349 uint32_t sRate;
7350 audio_channel_mask_t channelMask;
7351 audio_format_t format;
7352 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7353 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7354 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7355 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7356 status = NO_ERROR;
7357 }
Eric Laurent81784c32012-11-19 14:55:58 -08007358 }
Eric Laurent10351942014-05-08 18:49:52 -07007359 if (status == NO_ERROR) {
7360 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007361 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007362 }
7363 }
Eric Laurent81784c32012-11-19 14:55:58 -08007364 }
Eric Laurent10351942014-05-08 18:49:52 -07007365
Eric Laurent81784c32012-11-19 14:55:58 -08007366 return reconfig;
7367}
7368
7369String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7370{
Eric Laurent81784c32012-11-19 14:55:58 -08007371 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007372 if (initCheck() == NO_ERROR) {
7373 String8 out_s8;
7374 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7375 return out_s8;
7376 }
Eric Laurent81784c32012-11-19 14:55:58 -08007377 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007378 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007379}
7380
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007381void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007382 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7383
7384 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007385
7386 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007387 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007388 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007389 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007390 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007391 desc->mChannelMask = mChannelMask;
7392 desc->mSamplingRate = mSampleRate;
7393 desc->mFormat = mFormat;
7394 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007395 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007396 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007397 break;
7398
Eric Laurent73e26b62015-04-27 16:55:58 -07007399 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007400 default:
7401 break;
7402 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007403 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007404}
7405
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007406void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007407{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007408 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7409 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007410 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007411 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007412 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007413 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7414 result = mInput->stream->getFrameSize(&mFrameSize);
7415 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7416 result = mInput->stream->getBufferSize(&mBufferSize);
7417 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007418 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007419 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7420 "mBufferSize=%lld, mFrameCount=%lld",
7421 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7422 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007423 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007424 // 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 -07007425 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007426 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007427 // A larger value should allow more old data to be read after a track calls start(),
7428 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007429 //
7430 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007431 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007432 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007433 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007434 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007435
7436 // TODO optimize audio capture buffer sizes ...
7437 // Here we calculate the size of the sliding buffer used as a source
7438 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7439 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7440 // be better to have it derived from the pipe depth in the long term.
7441 // The current value is higher than necessary. However it should not add to latency.
7442
Glenn Kasten85948432013-08-19 12:09:05 -07007443 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007444 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7445 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007446 // if posix_memalign fails, will segv here.
7447 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007448
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007449 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7450 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007451}
7452
Glenn Kasten5f972c02014-01-13 09:59:31 -08007453uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007454{
7455 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007456 uint32_t result;
7457 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7458 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007459 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007460 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007461}
7462
Eric Laurent4c415062016-06-17 16:14:16 -07007463// hasAudioSession_l() must be called with ThreadBase::mLock held
7464uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007465{
Eric Laurent81784c32012-11-19 14:55:58 -08007466 uint32_t result = 0;
7467 if (getEffectChain_l(sessionId) != 0) {
7468 result = EFFECT_SESSION;
7469 }
7470
7471 for (size_t i = 0; i < mTracks.size(); ++i) {
7472 if (sessionId == mTracks[i]->sessionId()) {
7473 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007474 if (mTracks[i]->isFastTrack()) {
7475 result |= FAST_SESSION;
7476 }
Eric Laurent81784c32012-11-19 14:55:58 -08007477 break;
7478 }
7479 }
7480
7481 return result;
7482}
7483
Glenn Kastend848eb42016-03-08 13:42:11 -08007484KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007485{
Glenn Kastend848eb42016-03-08 13:42:11 -08007486 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007487 Mutex::Autolock _l(mLock);
7488 for (size_t j = 0; j < mTracks.size(); ++j) {
7489 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007490 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007491 if (ids.indexOfKey(sessionId) < 0) {
7492 ids.add(sessionId, true);
7493 }
7494 }
7495 return ids;
7496}
7497
7498AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7499{
7500 Mutex::Autolock _l(mLock);
7501 AudioStreamIn *input = mInput;
7502 mInput = NULL;
7503 return input;
7504}
7505
7506// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007507sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007508{
7509 if (mInput == NULL) {
7510 return NULL;
7511 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007512 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007513}
7514
7515status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7516{
7517 // only one chain per input thread
7518 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007519 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007520 return INVALID_OPERATION;
7521 }
7522 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007523 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007524 chain->setInBuffer(NULL);
7525 chain->setOutBuffer(NULL);
7526
7527 checkSuspendOnAddEffectChain_l(chain);
7528
Eric Laurent1b928682014-10-02 19:41:47 -07007529 // make sure enabled pre processing effects state is communicated to the HAL as we
7530 // just moved them to a new input stream.
7531 chain->syncHalEffectsState();
7532
Eric Laurent81784c32012-11-19 14:55:58 -08007533 mEffectChains.add(chain);
7534
7535 return NO_ERROR;
7536}
7537
7538size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7539{
7540 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7541 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007542 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007543 chain.get(), mEffectChains.size(), this);
7544 if (mEffectChains.size() == 1) {
7545 mEffectChains.removeAt(0);
7546 }
7547 return 0;
7548}
7549
Eric Laurent1c333e22014-05-20 10:48:17 -07007550status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7551 audio_patch_handle_t *handle)
7552{
7553 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007554
7555 // store new device and send to effects
7556 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007557 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007558 for (size_t i = 0; i < mEffectChains.size(); i++) {
7559 mEffectChains[i]->setDevice_l(mInDevice);
7560 }
7561
Eric Laurentd8365c52017-07-16 15:27:05 -07007562 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007563
7564 // store new source and send to effects
7565 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7566 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007567 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007568 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007569 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007570 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007571
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007572 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007573 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7574 status = hwDevice->createAudioPatch(patch->num_sources,
7575 patch->sources,
7576 patch->num_sinks,
7577 patch->sinks,
7578 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007579 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007580 char *address;
7581 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7582 address = audio_device_address_to_parameter(
7583 patch->sources[0].ext.device.type,
7584 patch->sources[0].ext.device.address);
7585 } else {
7586 address = (char *)calloc(1, 1);
7587 }
7588 AudioParameter param = AudioParameter(String8(address));
7589 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007590 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007591 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007592 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007593 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007594 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007595 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007596 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007597
Eric Laurente8726fe2015-06-26 09:39:24 -07007598 if (mInDevice != mPrevInDevice) {
7599 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7600 mPrevInDevice = mInDevice;
7601 }
Eric Laurent296fb132015-05-01 11:38:42 -07007602
Eric Laurent1c333e22014-05-20 10:48:17 -07007603 return status;
7604}
7605
7606status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7607{
7608 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007609
7610 mInDevice = AUDIO_DEVICE_NONE;
7611
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007612 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007613 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7614 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007615 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007616 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007617 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007618 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007619 }
7620 return status;
7621}
7622
Eric Laurent83b88082014-06-20 18:31:16 -07007623void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7624{
7625 Mutex::Autolock _l(mLock);
7626 mTracks.add(record);
7627}
7628
7629void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7630{
7631 Mutex::Autolock _l(mLock);
7632 destroyTrack_l(record);
7633}
7634
7635void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7636{
7637 ThreadBase::getAudioPortConfig(config);
7638 config->role = AUDIO_PORT_ROLE_SINK;
7639 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7640 config->ext.mix.usecase.source = mAudioSource;
7641}
Eric Laurent1c333e22014-05-20 10:48:17 -07007642
Eric Laurent6acd1d42017-01-04 14:23:29 -08007643// ----------------------------------------------------------------------------
7644// Mmap
7645// ----------------------------------------------------------------------------
7646
7647AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7648 : mThread(thread)
7649{
Phil Burk9fabbf82017-08-03 12:02:00 -07007650 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007651}
7652
7653AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7654{
Phil Burk9fabbf82017-08-03 12:02:00 -07007655 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007656}
7657
7658status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7659 struct audio_mmap_buffer_info *info)
7660{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007661 return mThread->createMmapBuffer(minSizeFrames, info);
7662}
7663
7664status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7665{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007666 return mThread->getMmapPosition(position);
7667}
7668
Eric Laurenta54f1282017-07-01 19:39:32 -07007669status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007670 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007671
7672{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007673 return mThread->start(client, handle);
7674}
7675
7676status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7677{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007678 return mThread->stop(handle);
7679}
7680
Eric Laurent18b57012017-02-13 16:23:52 -08007681status_t AudioFlinger::MmapThreadHandle::standby()
7682{
Eric Laurent18b57012017-02-13 16:23:52 -08007683 return mThread->standby();
7684}
7685
Eric Laurent6acd1d42017-01-04 14:23:29 -08007686
7687AudioFlinger::MmapThread::MmapThread(
7688 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7689 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7690 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7691 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007692 mSessionId(AUDIO_SESSION_NONE),
7693 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007694 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7695 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007696{
Eric Laurent18b57012017-02-13 16:23:52 -08007697 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007698 readHalParameters_l();
7699}
7700
7701AudioFlinger::MmapThread::~MmapThread()
7702{
Eric Laurent18b57012017-02-13 16:23:52 -08007703 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007704}
7705
7706void AudioFlinger::MmapThread::onFirstRef()
7707{
7708 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7709}
7710
7711void AudioFlinger::MmapThread::disconnect()
7712{
7713 for (const sp<MmapTrack> &t : mActiveTracks) {
7714 stop(t->portId());
7715 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007716 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007717 if (isOutput()) {
7718 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7719 } else {
7720 AudioSystem::releaseInput(mId, mSessionId);
7721 }
7722}
7723
7724
7725void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7726 audio_stream_type_t streamType __unused,
7727 audio_session_t sessionId,
7728 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007729 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007730 audio_port_handle_t portId)
7731{
7732 mAttr = *attr;
7733 mSessionId = sessionId;
7734 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007735 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007736 mPortId = portId;
7737}
7738
7739status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7740 struct audio_mmap_buffer_info *info)
7741{
7742 if (mHalStream == 0) {
7743 return NO_INIT;
7744 }
Eric Laurent18b57012017-02-13 16:23:52 -08007745 mStandby = true;
7746 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007747 return mHalStream->createMmapBuffer(minSizeFrames, info);
7748}
7749
7750status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7751{
7752 if (mHalStream == 0) {
7753 return NO_INIT;
7754 }
7755 return mHalStream->getMmapPosition(position);
7756}
7757
Eric Laurenta54f1282017-07-01 19:39:32 -07007758status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007759 audio_port_handle_t *handle)
7760{
Eric Laurenta54f1282017-07-01 19:39:32 -07007761 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7762 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007763 if (mHalStream == 0) {
7764 return NO_INIT;
7765 }
7766
7767 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007768
Eric Laurenta54f1282017-07-01 19:39:32 -07007769 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007770 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007771 ret = mHalStream->start();
7772 if (ret != NO_ERROR) {
7773 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7774 return ret;
7775 }
Eric Laurent18b57012017-02-13 16:23:52 -08007776 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007777 return NO_ERROR;
7778 }
7779
Phil Burk81ad5ec2017-09-01 10:45:41 -07007780 if (!isOutput() && !recordingAllowed(client.packageName, client.clientPid, client.clientUid)) {
7781 return PERMISSION_DENIED;
7782 }
7783
Eric Laurenta54f1282017-07-01 19:39:32 -07007784 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7785
7786 audio_io_handle_t io = mId;
7787 if (isOutput()) {
7788 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7789 config.sample_rate = mSampleRate;
7790 config.channel_mask = mChannelMask;
7791 config.format = mFormat;
7792 audio_stream_type_t stream = streamType();
7793 audio_output_flags_t flags =
7794 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007795 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007796 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7797 mSessionId,
7798 &stream,
7799 client.clientUid,
7800 &config,
7801 flags,
7802 &deviceId,
7803 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007804 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007805 audio_config_base_t config;
7806 config.sample_rate = mSampleRate;
7807 config.channel_mask = mChannelMask;
7808 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007809 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007810 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7811 mSessionId,
7812 client.clientPid,
7813 client.clientUid,
7814 &config,
7815 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7816 &deviceId,
7817 &portId);
7818 }
7819 // APM should not chose a different input or output stream for the same set of attributes
7820 // and audo configuration
7821 if (ret != NO_ERROR || io != mId) {
7822 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7823 __FUNCTION__, ret, io, mId);
7824 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007825 }
7826
7827 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007828 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007829 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007830 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007831 }
7832
7833 // abort if start is rejected by audio policy manager
7834 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007835 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007836 if (mActiveTracks.size() != 0) {
7837 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007838 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007839 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007840 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007841 }
Eric Laurent18b57012017-02-13 16:23:52 -08007842 } else {
7843 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007844 }
7845 return PERMISSION_DENIED;
7846 }
7847
Eric Laurenta54f1282017-07-01 19:39:32 -07007848 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7849 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007850
7851 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007852 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007853 if (chain != 0) {
7854 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7855 chain->incTrackCnt();
7856 chain->incActiveTrackCnt();
7857 }
7858
7859 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007860 broadcast_l();
7861
Eric Laurenta54f1282017-07-01 19:39:32 -07007862 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007863
7864 return NO_ERROR;
7865}
7866
7867status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7868{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007869 ALOGV("%s handle %d", __FUNCTION__, handle);
7870
7871 if (mHalStream == 0) {
7872 return NO_INIT;
7873 }
7874
Eric Laurenta54f1282017-07-01 19:39:32 -07007875 if (handle == mPortId) {
7876 mHalStream->stop();
7877 return NO_ERROR;
7878 }
7879
Eric Laurent6acd1d42017-01-04 14:23:29 -08007880 sp<MmapTrack> track;
7881 for (const sp<MmapTrack> &t : mActiveTracks) {
7882 if (handle == t->portId()) {
7883 track = t;
7884 break;
7885 }
7886 }
7887 if (track == 0) {
7888 return BAD_VALUE;
7889 }
7890
7891 mActiveTracks.remove(track);
7892
7893 if (isOutput()) {
7894 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007895 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007896 } else {
7897 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007898 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007899 }
7900
7901 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7902 if (chain != 0) {
7903 chain->decActiveTrackCnt();
7904 chain->decTrackCnt();
7905 }
7906
7907 broadcast_l();
7908
Eric Laurent6acd1d42017-01-04 14:23:29 -08007909 return NO_ERROR;
7910}
7911
Eric Laurent18b57012017-02-13 16:23:52 -08007912status_t AudioFlinger::MmapThread::standby()
7913{
7914 ALOGV("%s", __FUNCTION__);
7915
7916 if (mHalStream == 0) {
7917 return NO_INIT;
7918 }
7919 if (mActiveTracks.size() != 0) {
7920 return INVALID_OPERATION;
7921 }
7922 mHalStream->standby();
7923 mStandby = true;
7924 releaseWakeLock();
7925 return NO_ERROR;
7926}
7927
Eric Laurent6acd1d42017-01-04 14:23:29 -08007928
7929void AudioFlinger::MmapThread::readHalParameters_l()
7930{
7931 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7932 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7933 mFormat = mHALFormat;
7934 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7935 result = mHalStream->getFrameSize(&mFrameSize);
7936 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7937 result = mHalStream->getBufferSize(&mBufferSize);
7938 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7939 mFrameCount = mBufferSize / mFrameSize;
7940}
7941
7942bool AudioFlinger::MmapThread::threadLoop()
7943{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007944 checkSilentMode_l();
7945
7946 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7947
7948 while (!exitPending())
7949 {
7950 Mutex::Autolock _l(mLock);
7951 Vector< sp<EffectChain> > effectChains;
7952
7953 if (mSignalPending) {
7954 // A signal was raised while we were unlocked
7955 mSignalPending = false;
7956 } else {
7957 if (mConfigEvents.isEmpty()) {
7958 // we're about to wait, flush the binder command buffer
7959 IPCThreadState::self()->flushCommands();
7960
7961 if (exitPending()) {
7962 break;
7963 }
7964
Eric Laurent6acd1d42017-01-04 14:23:29 -08007965 // wait until we have something to do...
7966 ALOGV("%s going to sleep", myName.string());
7967 mWaitWorkCV.wait(mLock);
7968 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007969
7970 checkSilentMode_l();
7971
7972 continue;
7973 }
7974 }
7975
7976 processConfigEvents_l();
7977
7978 processVolume_l();
7979
7980 checkInvalidTracks_l();
7981
7982 mActiveTracks.updatePowerState(this);
7983
7984 lockEffectChains_l(effectChains);
7985 for (size_t i = 0; i < effectChains.size(); i ++) {
7986 effectChains[i]->process_l();
7987 }
7988 // enable changes in effect chain
7989 unlockEffectChains(effectChains);
7990 // Effect chains will be actually deleted here if they were removed from
7991 // mEffectChains list during mixing or effects processing
7992 }
7993
7994 threadLoop_exit();
7995
7996 if (!mStandby) {
7997 threadLoop_standby();
7998 mStandby = true;
7999 }
8000
Eric Laurent6acd1d42017-01-04 14:23:29 -08008001 ALOGV("Thread %p type %d exiting", this, mType);
8002 return false;
8003}
8004
8005// checkForNewParameter_l() must be called with ThreadBase::mLock held
8006bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8007 status_t& status)
8008{
8009 AudioParameter param = AudioParameter(keyValuePair);
8010 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008011 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008012 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008013 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008014 // forward device change to effects that have requested to be
8015 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008016 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008017 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008018 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008019 }
8020 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008021 if (audio_is_output_devices(device)) {
8022 mOutDevice = device;
8023 if (!isOutput()) {
8024 sendToHal = false;
8025 }
8026 } else {
8027 mInDevice = device;
8028 if (device != AUDIO_DEVICE_NONE) {
8029 mPrevInDevice = value;
8030 }
8031 // TODO: implement and call checkBtNrec_l();
8032 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008033 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008034 if (sendToHal) {
8035 status = mHalStream->setParameters(keyValuePair);
8036 } else {
8037 status = NO_ERROR;
8038 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008039
8040 return false;
8041}
8042
8043String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8044{
8045 Mutex::Autolock _l(mLock);
8046 String8 out_s8;
8047 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8048 return out_s8;
8049 }
8050 return String8();
8051}
8052
8053void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8054 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8055
8056 desc->mIoHandle = mId;
8057
8058 switch (event) {
8059 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008060 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008061 case AUDIO_INPUT_CONFIG_CHANGED:
8062 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008063 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008064 case AUDIO_OUTPUT_CONFIG_CHANGED:
8065 desc->mPatch = mPatch;
8066 desc->mChannelMask = mChannelMask;
8067 desc->mSamplingRate = mSampleRate;
8068 desc->mFormat = mFormat;
8069 desc->mFrameCount = mFrameCount;
8070 desc->mFrameCountHAL = mFrameCount;
8071 desc->mLatency = 0;
8072 break;
8073
8074 case AUDIO_INPUT_CLOSED:
8075 case AUDIO_OUTPUT_CLOSED:
8076 default:
8077 break;
8078 }
8079 mAudioFlinger->ioConfigChanged(event, desc, pid);
8080}
8081
8082status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8083 audio_patch_handle_t *handle)
8084{
8085 status_t status = NO_ERROR;
8086
8087 // store new device and send to effects
8088 audio_devices_t type = AUDIO_DEVICE_NONE;
8089 audio_port_handle_t deviceId;
8090 if (isOutput()) {
8091 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8092 type |= patch->sinks[i].ext.device.type;
8093 }
8094 deviceId = patch->sinks[0].id;
8095 } else {
8096 type = patch->sources[0].ext.device.type;
8097 deviceId = patch->sources[0].id;
8098 }
8099
8100 for (size_t i = 0; i < mEffectChains.size(); i++) {
8101 mEffectChains[i]->setDevice_l(type);
8102 }
8103
8104 if (isOutput()) {
8105 mOutDevice = type;
8106 } else {
8107 mInDevice = type;
8108 // store new source and send to effects
8109 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8110 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8111 for (size_t i = 0; i < mEffectChains.size(); i++) {
8112 mEffectChains[i]->setAudioSource_l(mAudioSource);
8113 }
8114 }
8115 }
8116
8117 if (mAudioHwDev->supportsAudioPatches()) {
8118 status = mHalDevice->createAudioPatch(patch->num_sources,
8119 patch->sources,
8120 patch->num_sinks,
8121 patch->sinks,
8122 handle);
8123 } else {
8124 char *address;
8125 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8126 //FIXME: we only support address on first sink with HAL version < 3.0
8127 address = audio_device_address_to_parameter(
8128 patch->sinks[0].ext.device.type,
8129 patch->sinks[0].ext.device.address);
8130 } else {
8131 address = (char *)calloc(1, 1);
8132 }
8133 AudioParameter param = AudioParameter(String8(address));
8134 free(address);
8135 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8136 if (!isOutput()) {
8137 param.addInt(String8(AudioParameter::keyInputSource),
8138 (int)patch->sinks[0].ext.mix.usecase.source);
8139 }
8140 status = mHalStream->setParameters(param.toString());
8141 *handle = AUDIO_PATCH_HANDLE_NONE;
8142 }
8143
8144 if (isOutput() && mPrevOutDevice != mOutDevice) {
8145 mPrevOutDevice = type;
8146 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008147 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008148 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008149 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008150 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008151 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008152 }
8153 if (!isOutput() && mPrevInDevice != mInDevice) {
8154 mPrevInDevice = type;
8155 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008156 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008157 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008158 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008159 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008160 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008161 }
8162 return status;
8163}
8164
8165status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8166{
8167 status_t status = NO_ERROR;
8168
8169 mInDevice = AUDIO_DEVICE_NONE;
8170
8171 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8172 supportsAudioPatches : false;
8173
8174 if (supportsAudioPatches) {
8175 status = mHalDevice->releaseAudioPatch(handle);
8176 } else {
8177 AudioParameter param;
8178 param.addInt(String8(AudioParameter::keyRouting), 0);
8179 status = mHalStream->setParameters(param.toString());
8180 }
8181 return status;
8182}
8183
8184void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8185{
8186 ThreadBase::getAudioPortConfig(config);
8187 if (isOutput()) {
8188 config->role = AUDIO_PORT_ROLE_SOURCE;
8189 config->ext.mix.hw_module = mAudioHwDev->handle();
8190 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8191 } else {
8192 config->role = AUDIO_PORT_ROLE_SINK;
8193 config->ext.mix.hw_module = mAudioHwDev->handle();
8194 config->ext.mix.usecase.source = mAudioSource;
8195 }
8196}
8197
8198status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8199{
8200 audio_session_t session = chain->sessionId();
8201
8202 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8203 // Attach all tracks with same session ID to this chain.
8204 // indicate all active tracks in the chain
8205 for (const sp<MmapTrack> &track : mActiveTracks) {
8206 if (session == track->sessionId()) {
8207 chain->incTrackCnt();
8208 chain->incActiveTrackCnt();
8209 }
8210 }
8211
8212 chain->setThread(this);
8213 chain->setInBuffer(nullptr);
8214 chain->setOutBuffer(nullptr);
8215 chain->syncHalEffectsState();
8216
8217 mEffectChains.add(chain);
8218 checkSuspendOnAddEffectChain_l(chain);
8219 return NO_ERROR;
8220}
8221
8222size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8223{
8224 audio_session_t session = chain->sessionId();
8225
8226 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8227
8228 for (size_t i = 0; i < mEffectChains.size(); i++) {
8229 if (chain == mEffectChains[i]) {
8230 mEffectChains.removeAt(i);
8231 // detach all active tracks from the chain
8232 // detach all tracks with same session ID from this chain
8233 for (const sp<MmapTrack> &track : mActiveTracks) {
8234 if (session == track->sessionId()) {
8235 chain->decActiveTrackCnt();
8236 chain->decTrackCnt();
8237 }
8238 }
8239 break;
8240 }
8241 }
8242 return mEffectChains.size();
8243}
8244
8245// hasAudioSession_l() must be called with ThreadBase::mLock held
8246uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8247{
8248 uint32_t result = 0;
8249 if (getEffectChain_l(sessionId) != 0) {
8250 result = EFFECT_SESSION;
8251 }
8252
8253 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8254 sp<MmapTrack> track = mActiveTracks[i];
8255 if (sessionId == track->sessionId()) {
8256 result |= TRACK_SESSION;
8257 if (track->isFastTrack()) {
8258 result |= FAST_SESSION;
8259 }
8260 break;
8261 }
8262 }
8263
8264 return result;
8265}
8266
8267void AudioFlinger::MmapThread::threadLoop_standby()
8268{
8269 mHalStream->standby();
8270}
8271
8272void AudioFlinger::MmapThread::threadLoop_exit()
8273{
Phil Burk7dce7282017-09-27 13:51:41 -07008274 // Do not call callback->onTearDown() because it is redundant for thread exit
8275 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008276}
8277
8278status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8279{
8280 return BAD_VALUE;
8281}
8282
8283bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8284{
8285 return false;
8286}
8287
8288status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8289 const effect_descriptor_t *desc, audio_session_t sessionId)
8290{
8291 // No global effect sessions on mmap threads
8292 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8293 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8294 desc->name, mThreadName);
8295 return BAD_VALUE;
8296 }
8297
8298 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8299 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8300 desc->name);
8301 return BAD_VALUE;
8302 }
8303 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008304 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8305 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008306 return BAD_VALUE;
8307 }
8308
8309 // Only allow effects without processing load or latency
8310 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8311 return BAD_VALUE;
8312 }
8313
8314 return NO_ERROR;
8315
8316}
8317
8318void AudioFlinger::MmapThread::checkInvalidTracks_l()
8319{
8320 for (const sp<MmapTrack> &track : mActiveTracks) {
8321 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008322 sp<MmapStreamCallback> callback = mCallback.promote();
8323 if (callback != 0) {
8324 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008325 }
8326 break;
8327 }
8328 }
8329}
8330
8331void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8332{
8333 dumpInternals(fd, args);
8334 dumpTracks(fd, args);
8335 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008336 dprintf(fd, " Local log:\n");
8337 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008338}
8339
8340void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8341{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 dumpBase(fd, args);
8343
8344 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8345 mAttr.content_type, mAttr.usage, mAttr.source);
8346 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8347 if (mActiveTracks.size() == 0) {
8348 dprintf(fd, " No active clients\n");
8349 }
8350}
8351
8352void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8353{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008354 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008355 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008356 dprintf(fd, " %zu Tracks\n", numtracks);
8357 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008358 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008359 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008360 MmapTrack::appendDumpHeader(result);
8361 for (size_t i = 0; i < numtracks ; ++i) {
8362 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008363 result.append(prefix);
8364 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008365 }
8366 } else {
8367 dprintf(fd, "\n");
8368 }
8369 write(fd, result.string(), result.size());
8370}
8371
8372AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8373 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8374 AudioHwDevice *hwDev, AudioStreamOut *output,
8375 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8376 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8377 mStreamType(AUDIO_STREAM_MUSIC),
8378 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8379{
8380 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8381 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8382 mMasterVolume = audioFlinger->masterVolume_l();
8383 mMasterMute = audioFlinger->masterMute_l();
8384 if (mAudioHwDev) {
8385 if (mAudioHwDev->canSetMasterVolume()) {
8386 mMasterVolume = 1.0;
8387 }
8388
8389 if (mAudioHwDev->canSetMasterMute()) {
8390 mMasterMute = false;
8391 }
8392 }
8393}
8394
8395void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8396 audio_stream_type_t streamType,
8397 audio_session_t sessionId,
8398 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008399 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008400 audio_port_handle_t portId)
8401{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008402 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008403 mStreamType = streamType;
8404}
8405
8406AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8407{
8408 Mutex::Autolock _l(mLock);
8409 AudioStreamOut *output = mOutput;
8410 mOutput = NULL;
8411 return output;
8412}
8413
8414void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8415{
8416 Mutex::Autolock _l(mLock);
8417 // Don't apply master volume in SW if our HAL can do it for us.
8418 if (mAudioHwDev &&
8419 mAudioHwDev->canSetMasterVolume()) {
8420 mMasterVolume = 1.0;
8421 } else {
8422 mMasterVolume = value;
8423 }
8424}
8425
8426void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8427{
8428 Mutex::Autolock _l(mLock);
8429 // Don't apply master mute in SW if our HAL can do it for us.
8430 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8431 mMasterMute = false;
8432 } else {
8433 mMasterMute = muted;
8434 }
8435}
8436
8437void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8438{
8439 Mutex::Autolock _l(mLock);
8440 if (stream == mStreamType) {
8441 mStreamVolume = value;
8442 broadcast_l();
8443 }
8444}
8445
8446float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8447{
8448 Mutex::Autolock _l(mLock);
8449 if (stream == mStreamType) {
8450 return mStreamVolume;
8451 }
8452 return 0.0f;
8453}
8454
8455void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8456{
8457 Mutex::Autolock _l(mLock);
8458 if (stream == mStreamType) {
8459 mStreamMute= muted;
8460 broadcast_l();
8461 }
8462}
8463
8464void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8465{
8466 Mutex::Autolock _l(mLock);
8467 if (streamType == mStreamType) {
8468 for (const sp<MmapTrack> &track : mActiveTracks) {
8469 track->invalidate();
8470 }
8471 broadcast_l();
8472 }
8473}
8474
8475void AudioFlinger::MmapPlaybackThread::processVolume_l()
8476{
8477 float volume;
8478
8479 if (mMasterMute || mStreamMute) {
8480 volume = 0;
8481 } else {
8482 volume = mMasterVolume * mStreamVolume;
8483 }
8484
8485 if (volume != mHalVolFloat) {
8486 mHalVolFloat = volume;
8487
8488 // Convert volumes from float to 8.24
8489 uint32_t vol = (uint32_t)(volume * (1 << 24));
8490
8491 // Delegate volume control to effect in track effect chain if needed
8492 // only one effect chain can be present on DirectOutputThread, so if
8493 // there is one, the track is connected to it
8494 if (!mEffectChains.isEmpty()) {
8495 mEffectChains[0]->setVolume_l(&vol, &vol);
8496 volume = (float)vol / (1 << 24);
8497 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008498 // Try to use HW volume control and fall back to SW control if not implemented
8499 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8500 sp<MmapStreamCallback> callback = mCallback.promote();
8501 if (callback != 0) {
8502 int channelCount;
8503 if (isOutput()) {
8504 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8505 } else {
8506 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8507 }
8508 Vector<float> values;
8509 for (int i = 0; i < channelCount; i++) {
8510 values.add(volume);
8511 }
8512 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008513 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008514 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008515 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008516 }
8517 }
8518}
8519
8520void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8521{
8522 if (!mMasterMute) {
8523 char value[PROPERTY_VALUE_MAX];
8524 if (property_get("ro.audio.silent", value, "0") > 0) {
8525 char *endptr;
8526 unsigned long ul = strtoul(value, &endptr, 0);
8527 if (*endptr == '\0' && ul != 0) {
8528 ALOGD("Silence is golden");
8529 // The setprop command will not allow a property to be changed after
8530 // the first time it is set, so we don't have to worry about un-muting.
8531 setMasterMute_l(true);
8532 }
8533 }
8534 }
8535}
8536
8537void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8538{
8539 MmapThread::dumpInternals(fd, args);
8540
Glenn Kastend3bb6452016-12-05 18:14:37 -08008541 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8542 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008543 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8544}
8545
8546AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8547 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8548 AudioHwDevice *hwDev, AudioStreamIn *input,
8549 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8550 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8551 mInput(input)
8552{
8553 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8554 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8555}
8556
8557AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8558{
8559 Mutex::Autolock _l(mLock);
8560 AudioStreamIn *input = mInput;
8561 mInput = NULL;
8562 return input;
8563}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008564} // namespace android