blob: 6329f208f2063dc9c6b3f74e046d96d1e15b8631 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800446 case MMAP:
447 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800534 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Mikhail Naganov83f04272017-02-07 10:45:09 -0800615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700616{
617 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
623 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700700 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
701 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700705 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 CreateAudioPatchConfigEventData *data =
707 (CreateAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t newDevice = getDevice();
710 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
711 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
712 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 } break;
714 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 ReleaseAudioPatchConfigEventData *data =
717 (ReleaseAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t newDevice = getDevice();
720 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
721 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
722 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 default:
Eric Laurent10351942014-05-08 18:49:52 -0700725 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
729 Mutex::Autolock _l(event->mLock);
730 if (event->mWaitStatus) {
731 event->mWaitStatus = false;
732 event->mCond.signal();
733 }
734 }
735 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
736 }
737
738 if (configChanged) {
739 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Marco Nelissenb2208842014-02-07 14:00:50 -0800743String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
744 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700745 const audio_channel_representation_t representation =
746 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700789 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800810 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
811 this, mThreadName, getTid(), type(), threadTypeToString(type()));
812
Eric Laurent81784c32012-11-19 14:55:58 -0800813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800815 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700823 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700828 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Andy Hung293558a2017-03-21 12:19:20 -0700840 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
842 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 if (locked) {
846 mLock.unlock();
847 }
848}
849
850void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000857 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800858 write(fd, buffer, strlen(buffer));
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800861 sp<EffectChain> chain = mEffectChains[i];
862 if (chain != 0) {
863 chain->dump(fd, args);
864 }
865 }
866}
867
Andy Hungdae27702016-10-31 14:01:16 -0700868void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800869{
870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700871 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872}
873
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874String16 AudioFlinger::ThreadBase::getWakeLockTag()
875{
876 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 case MIXER:
878 return String16("AudioMix");
879 case DIRECT:
880 return String16("AudioDirectOut");
881 case DUPLICATING:
882 return String16("AudioDup");
883 case RECORD:
884 return String16("AudioIn");
885 case OFFLOAD:
886 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800887 case MMAP:
888 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Andy Hungdae27702016-10-31 14:01:16 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700900 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
901 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700904 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (status == NO_ERROR) {
907 mWakeLockToken = binder;
908 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Wei Jia3f273d12015-11-24 09:06:49 -0800911
Andy Hung3f0c9022016-01-15 17:49:46 -0800912 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800913 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
914 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800915}
916
917void AudioFlinger::ThreadBase::releaseWakeLock()
918{
919 Mutex::Autolock _l(mLock);
920 releaseWakeLock_l();
921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock_l()
924{
Andy Hung3f0c9022016-01-15 17:49:46 -0800925 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800934}
935
936void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700937 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938 // use checkService() to avoid blocking if power service is not up yet
939 sp<IBinder> binder =
940 defaultServiceManager()->checkService(String16("power"));
941 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800942 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 } else {
944 mPowerManager = interface_cast<IPowerManager>(binder);
945 binder->linkToDeath(mDeathRecipient);
946 }
947 }
948}
949
Andy Hungd01b0f12016-11-07 16:10:30 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700952
953#if !LOG_NDEBUG
954 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800955 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700956 s << uid << " ";
957 }
958 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
959#endif
960
Andy Hung438e7572015-12-14 15:51:17 -0800961 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
962 if (mSystemReady) {
963 ALOGE("no wake lock to update, but system ready!");
964 } else {
965 ALOGW("no wake lock to update, system not ready yet");
966 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 return;
968 }
969 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800970 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
971 status_t status = mPowerManager->updateWakeLockUids(
972 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
973 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800974 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 }
976}
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978void AudioFlinger::ThreadBase::clearPowerManager()
979{
980 Mutex::Autolock _l(mLock);
981 releaseWakeLock_l();
982 mPowerManager.clear();
983}
984
Glenn Kasten0f11b512014-01-31 16:18:54 -0800985void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 sp<ThreadBase> thread = mThread.promote();
988 if (thread != 0) {
989 thread->clearPowerManager();
990 }
991 ALOGW("power manager service died !!!");
992}
993
994void AudioFlinger::ThreadBase::setEffectSuspended(
Glenn Kastend848eb42016-03-08 13:42:11 -0800995 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800996{
997 Mutex::Autolock _l(mLock);
998 setEffectSuspended_l(type, suspend, sessionId);
999}
1000
1001void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001002 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001003{
1004 sp<EffectChain> chain = getEffectChain_l(sessionId);
1005 if (chain != 0) {
1006 if (type != NULL) {
1007 chain->setEffectSuspended_l(type, suspend);
1008 } else {
1009 chain->setEffectSuspendedAll_l(suspend);
1010 }
1011 }
1012
1013 updateSuspendedSessions_l(type, suspend, sessionId);
1014}
1015
1016void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1017{
1018 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1019 if (index < 0) {
1020 return;
1021 }
1022
1023 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1024 mSuspendedSessions.valueAt(index);
1025
1026 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001027 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001028 for (int j = 0; j < desc->mRefCount; j++) {
1029 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1030 chain->setEffectSuspendedAll_l(true);
1031 } else {
1032 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1033 desc->mType.timeLow);
1034 chain->setEffectSuspended_l(&desc->mType, true);
1035 }
1036 }
1037 }
1038}
1039
1040void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1041 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001042 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001043{
1044 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1045
1046 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1047
1048 if (suspend) {
1049 if (index >= 0) {
1050 sessionEffects = mSuspendedSessions.valueAt(index);
1051 } else {
1052 mSuspendedSessions.add(sessionId, sessionEffects);
1053 }
1054 } else {
1055 if (index < 0) {
1056 return;
1057 }
1058 sessionEffects = mSuspendedSessions.valueAt(index);
1059 }
1060
1061
1062 int key = EffectChain::kKeyForSuspendAll;
1063 if (type != NULL) {
1064 key = type->timeLow;
1065 }
1066 index = sessionEffects.indexOfKey(key);
1067
1068 sp<SuspendedSessionDesc> desc;
1069 if (suspend) {
1070 if (index >= 0) {
1071 desc = sessionEffects.valueAt(index);
1072 } else {
1073 desc = new SuspendedSessionDesc();
1074 if (type != NULL) {
1075 desc->mType = *type;
1076 }
1077 sessionEffects.add(key, desc);
1078 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1079 }
1080 desc->mRefCount++;
1081 } else {
1082 if (index < 0) {
1083 return;
1084 }
1085 desc = sessionEffects.valueAt(index);
1086 if (--desc->mRefCount == 0) {
1087 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1088 sessionEffects.removeItemsAt(index);
1089 if (sessionEffects.isEmpty()) {
1090 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1091 sessionId);
1092 mSuspendedSessions.removeItem(sessionId);
1093 }
1094 }
1095 }
1096 if (!sessionEffects.isEmpty()) {
1097 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1098 }
1099}
1100
1101void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1102 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001103 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001104{
1105 Mutex::Autolock _l(mLock);
1106 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1107}
1108
1109void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1110 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001111 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001112{
1113 if (mType != RECORD) {
1114 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1115 // another session. This gives the priority to well behaved effect control panels
1116 // and applications not using global effects.
1117 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1118 // global effects
1119 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1120 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1121 }
1122 }
1123
1124 sp<EffectChain> chain = getEffectChain_l(sessionId);
1125 if (chain != 0) {
1126 chain->checkSuspendOnEffectEnabled(effect, enabled);
1127 }
1128}
1129
Eric Laurent4c415062016-06-17 16:14:16 -07001130// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1131status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1132 const effect_descriptor_t *desc, audio_session_t sessionId)
1133{
1134 // No global effect sessions on record threads
1135 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1136 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1137 desc->name, mThreadName);
1138 return BAD_VALUE;
1139 }
1140 // only pre processing effects on record thread
1141 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1142 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1143 desc->name, mThreadName);
1144 return BAD_VALUE;
1145 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001146
1147 // always allow effects without processing load or latency
1148 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1149 return NO_ERROR;
1150 }
1151
Eric Laurent4c415062016-06-17 16:14:16 -07001152 audio_input_flags_t flags = mInput->flags;
1153 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1154 if (flags & AUDIO_INPUT_FLAG_RAW) {
1155 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1156 desc->name, mThreadName);
1157 return BAD_VALUE;
1158 }
1159 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1160 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1161 desc->name, mThreadName);
1162 return BAD_VALUE;
1163 }
1164 }
1165 return NO_ERROR;
1166}
1167
1168// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1169status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1170 const effect_descriptor_t *desc, audio_session_t sessionId)
1171{
1172 // no preprocessing on playback threads
1173 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1174 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1175 " thread %s", desc->name, mThreadName);
1176 return BAD_VALUE;
1177 }
1178
1179 switch (mType) {
1180 case MIXER: {
1181 // Reject any effect on mixer multichannel sinks.
1182 // TODO: fix both format and multichannel issues with effects.
1183 if (mChannelCount != FCC_2) {
1184 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1185 " thread %s", desc->name, mChannelCount, mThreadName);
1186 return BAD_VALUE;
1187 }
1188 audio_output_flags_t flags = mOutput->flags;
1189 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1190 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1191 // global effects are applied only to non fast tracks if they are SW
1192 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1193 break;
1194 }
1195 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1196 // only post processing on output stage session
1197 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1198 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1199 " on output stage session", desc->name);
1200 return BAD_VALUE;
1201 }
1202 } else {
1203 // no restriction on effects applied on non fast tracks
1204 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1205 break;
1206 }
1207 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001208
1209 // always allow effects without processing load or latency
1210 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1211 break;
1212 }
Eric Laurent4c415062016-06-17 16:14:16 -07001213 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1214 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1215 desc->name);
1216 return BAD_VALUE;
1217 }
1218 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1219 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1220 " in fast mode", desc->name);
1221 return BAD_VALUE;
1222 }
1223 }
1224 } break;
1225 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001226 // nothing actionable on offload threads, if the effect:
1227 // - is offloadable: the effect can be created
1228 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1229 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001230 break;
1231 case DIRECT:
1232 // Reject any effect on Direct output threads for now, since the format of
1233 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1234 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1235 desc->name, mThreadName);
1236 return BAD_VALUE;
1237 case DUPLICATING:
1238 // Reject any effect on mixer multichannel sinks.
1239 // TODO: fix both format and multichannel issues with effects.
1240 if (mChannelCount != FCC_2) {
1241 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1242 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1243 return BAD_VALUE;
1244 }
1245 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1246 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1247 " thread %s", desc->name, mThreadName);
1248 return BAD_VALUE;
1249 }
1250 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1251 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1252 " DUPLICATING thread %s", desc->name, mThreadName);
1253 return BAD_VALUE;
1254 }
1255 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1256 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1257 " DUPLICATING thread %s", desc->name, mThreadName);
1258 return BAD_VALUE;
1259 }
1260 break;
1261 default:
1262 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1263 }
1264
1265 return NO_ERROR;
1266}
1267
Eric Laurent81784c32012-11-19 14:55:58 -08001268// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1269sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1270 const sp<AudioFlinger::Client>& client,
1271 const sp<IEffectClient>& effectClient,
1272 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001273 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001274 effect_descriptor_t *desc,
1275 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001276 status_t *status,
1277 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001278{
1279 sp<EffectModule> effect;
1280 sp<EffectHandle> handle;
1281 status_t lStatus;
1282 sp<EffectChain> chain;
1283 bool chainCreated = false;
1284 bool effectCreated = false;
1285 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001286 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001287
1288 lStatus = initCheck();
1289 if (lStatus != NO_ERROR) {
1290 ALOGW("createEffect_l() Audio driver not initialized.");
1291 goto Exit;
1292 }
1293
Eric Laurent81784c32012-11-19 14:55:58 -08001294 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1295
1296 { // scope for mLock
1297 Mutex::Autolock _l(mLock);
1298
Eric Laurent4c415062016-06-17 16:14:16 -07001299 lStatus = checkEffectCompatibility_l(desc, sessionId);
1300 if (lStatus != NO_ERROR) {
1301 goto Exit;
1302 }
1303
Eric Laurent81784c32012-11-19 14:55:58 -08001304 // check for existing effect chain with the requested audio session
1305 chain = getEffectChain_l(sessionId);
1306 if (chain == 0) {
1307 // create a new chain for this session
1308 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1309 chain = new EffectChain(this, sessionId);
1310 addEffectChain_l(chain);
1311 chain->setStrategy(getStrategyForSession_l(sessionId));
1312 chainCreated = true;
1313 } else {
1314 effect = chain->getEffectFromDesc_l(desc);
1315 }
1316
1317 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1318
1319 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001320 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001321 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001322 lStatus = AudioSystem::registerEffect(
1323 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectRegistered = true;
1328 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001329 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001330 if (lStatus != NO_ERROR) {
1331 goto Exit;
1332 }
1333 effectCreated = true;
1334
1335 effect->setDevice(mOutDevice);
1336 effect->setDevice(mInDevice);
1337 effect->setMode(mAudioFlinger->getMode());
1338 effect->setAudioSource(mAudioSource);
1339 }
1340 // create effect handle and connect it to effect module
1341 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001342 lStatus = handle->initCheck();
1343 if (lStatus == OK) {
1344 lStatus = effect->addHandle(handle.get());
1345 }
Eric Laurent81784c32012-11-19 14:55:58 -08001346 if (enabled != NULL) {
1347 *enabled = (int)effect->isEnabled();
1348 }
1349 }
1350
1351Exit:
1352 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1353 Mutex::Autolock _l(mLock);
1354 if (effectCreated) {
1355 chain->removeEffect_l(effect);
1356 }
1357 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001358 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001359 }
1360 if (chainCreated) {
1361 removeEffectChain_l(chain);
1362 }
1363 handle.clear();
1364 }
1365
Glenn Kasten9156ef32013-08-06 15:39:08 -07001366 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001367 return handle;
1368}
1369
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001370void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1371 bool unpinIfLast)
1372{
1373 bool remove = false;
1374 sp<EffectModule> effect;
1375 {
1376 Mutex::Autolock _l(mLock);
1377
1378 effect = handle->effect().promote();
1379 if (effect == 0) {
1380 return;
1381 }
1382 // restore suspended effects if the disconnected handle was enabled and the last one.
1383 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1384 if (remove) {
1385 removeEffect_l(effect, true);
1386 }
1387 }
1388 if (remove) {
1389 mAudioFlinger->updateOrphanEffectChains(effect);
1390 AudioSystem::unregisterEffect(effect->id());
1391 if (handle->enabled()) {
1392 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1393 }
1394 }
1395}
1396
Glenn Kastend848eb42016-03-08 13:42:11 -08001397sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1398 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001399{
1400 Mutex::Autolock _l(mLock);
1401 return getEffect_l(sessionId, effectId);
1402}
1403
Glenn Kastend848eb42016-03-08 13:42:11 -08001404sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1405 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001406{
1407 sp<EffectChain> chain = getEffectChain_l(sessionId);
1408 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1409}
1410
1411// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1412// PlaybackThread::mLock held
1413status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1414{
1415 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001416 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001417 sp<EffectChain> chain = getEffectChain_l(sessionId);
1418 bool chainCreated = false;
1419
Eric Laurent5baf2af2013-09-12 17:37:00 -07001420 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1421 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1422 this, effect->desc().name, effect->desc().flags);
1423
Eric Laurent81784c32012-11-19 14:55:58 -08001424 if (chain == 0) {
1425 // create a new chain for this session
1426 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1427 chain = new EffectChain(this, sessionId);
1428 addEffectChain_l(chain);
1429 chain->setStrategy(getStrategyForSession_l(sessionId));
1430 chainCreated = true;
1431 }
1432 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1433
1434 if (chain->getEffectFromId_l(effect->id()) != 0) {
1435 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1436 this, effect->desc().name, chain.get());
1437 return BAD_VALUE;
1438 }
1439
Eric Laurent5baf2af2013-09-12 17:37:00 -07001440 effect->setOffloaded(mType == OFFLOAD, mId);
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442 status_t status = chain->addEffect_l(effect);
1443 if (status != NO_ERROR) {
1444 if (chainCreated) {
1445 removeEffectChain_l(chain);
1446 }
1447 return status;
1448 }
1449
1450 effect->setDevice(mOutDevice);
1451 effect->setDevice(mInDevice);
1452 effect->setMode(mAudioFlinger->getMode());
1453 effect->setAudioSource(mAudioSource);
1454 return NO_ERROR;
1455}
1456
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001457void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001458
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001459 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001460 effect_descriptor_t desc = effect->desc();
1461 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1462 detachAuxEffect_l(effect->id());
1463 }
1464
1465 sp<EffectChain> chain = effect->chain().promote();
1466 if (chain != 0) {
1467 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001468 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001469 removeEffectChain_l(chain);
1470 }
1471 } else {
1472 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1473 }
1474}
1475
1476void AudioFlinger::ThreadBase::lockEffectChains_l(
1477 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1478{
1479 effectChains = mEffectChains;
1480 for (size_t i = 0; i < mEffectChains.size(); i++) {
1481 mEffectChains[i]->lock();
1482 }
1483}
1484
1485void AudioFlinger::ThreadBase::unlockEffectChains(
1486 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1487{
1488 for (size_t i = 0; i < effectChains.size(); i++) {
1489 effectChains[i]->unlock();
1490 }
1491}
1492
Glenn Kastend848eb42016-03-08 13:42:11 -08001493sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001494{
1495 Mutex::Autolock _l(mLock);
1496 return getEffectChain_l(sessionId);
1497}
1498
Glenn Kastend848eb42016-03-08 13:42:11 -08001499sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1500 const
Eric Laurent81784c32012-11-19 14:55:58 -08001501{
1502 size_t size = mEffectChains.size();
1503 for (size_t i = 0; i < size; i++) {
1504 if (mEffectChains[i]->sessionId() == sessionId) {
1505 return mEffectChains[i];
1506 }
1507 }
1508 return 0;
1509}
1510
1511void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1512{
1513 Mutex::Autolock _l(mLock);
1514 size_t size = mEffectChains.size();
1515 for (size_t i = 0; i < size; i++) {
1516 mEffectChains[i]->setMode_l(mode);
1517 }
1518}
1519
Eric Laurent83b88082014-06-20 18:31:16 -07001520void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1521{
1522 config->type = AUDIO_PORT_TYPE_MIX;
1523 config->ext.mix.handle = mId;
1524 config->sample_rate = mSampleRate;
1525 config->format = mFormat;
1526 config->channel_mask = mChannelMask;
1527 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1528 AUDIO_PORT_CONFIG_FORMAT;
1529}
1530
Eric Laurent72e3f392015-05-20 14:43:50 -07001531void AudioFlinger::ThreadBase::systemReady()
1532{
1533 Mutex::Autolock _l(mLock);
1534 if (mSystemReady) {
1535 return;
1536 }
1537 mSystemReady = true;
1538
1539 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1540 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1541 }
1542 mPendingConfigEvents.clear();
1543}
1544
Andy Hungdae27702016-10-31 14:01:16 -07001545template <typename T>
1546ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1547 ssize_t index = mActiveTracks.indexOf(track);
1548 if (index >= 0) {
1549 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1550 return index;
1551 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001552 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001553 mActiveTracksGeneration++;
1554 mLatestActiveTrack = track;
1555 ++mBatteryCounter[track->uid()].second;
1556 return mActiveTracks.add(track);
1557}
1558
1559template <typename T>
1560ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1561 ssize_t index = mActiveTracks.remove(track);
1562 if (index < 0) {
1563 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1564 return index;
1565 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001566 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001567 mActiveTracksGeneration++;
1568 --mBatteryCounter[track->uid()].second;
1569 // mLatestActiveTrack is not cleared even if is the same as track.
1570 return index;
1571}
1572
1573template <typename T>
1574void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1575 for (const sp<T> &track : mActiveTracks) {
1576 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001577 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001578 }
1579 mLastActiveTracksGeneration = mActiveTracksGeneration;
1580 mActiveTracks.clear();
1581 mLatestActiveTrack.clear();
1582 mBatteryCounter.clear();
1583}
1584
1585template <typename T>
1586void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1587 sp<ThreadBase> thread, bool force) {
1588 // Updates ActiveTracks client uids to the thread wakelock.
1589 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1590 thread->updateWakeLockUids_l(getWakeLockUids());
1591 mLastActiveTracksGeneration = mActiveTracksGeneration;
1592 }
1593
1594 // Updates BatteryNotifier uids
1595 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1596 const uid_t uid = it->first;
1597 ssize_t &previous = it->second.first;
1598 ssize_t &current = it->second.second;
1599 if (current > 0) {
1600 if (previous == 0) {
1601 BatteryNotifier::getInstance().noteStartAudio(uid);
1602 }
1603 previous = current;
1604 ++it;
1605 } else if (current == 0) {
1606 if (previous > 0) {
1607 BatteryNotifier::getInstance().noteStopAudio(uid);
1608 }
1609 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1610 } else /* (current < 0) */ {
1611 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1612 }
1613 }
1614}
Eric Laurent83b88082014-06-20 18:31:16 -07001615
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001616template <typename T>
1617void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1618 const char *funcName, const sp<T> &track) const {
1619 if (mLocalLog != nullptr) {
1620 String8 result;
1621 track->appendDump(result, false /* active */);
1622 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1623 }
1624}
1625
Eric Laurent6acd1d42017-01-04 14:23:29 -08001626void AudioFlinger::ThreadBase::broadcast_l()
1627{
1628 // Thread could be blocked waiting for async
1629 // so signal it to handle state changes immediately
1630 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1631 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1632 mSignalPending = true;
1633 mWaitWorkCV.broadcast();
1634}
1635
Eric Laurent81784c32012-11-19 14:55:58 -08001636// ----------------------------------------------------------------------------
1637// Playback
1638// ----------------------------------------------------------------------------
1639
1640AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1641 AudioStreamOut* output,
1642 audio_io_handle_t id,
1643 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001644 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001645 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001646 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001647 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001648 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001649 mMixerBuffer(NULL),
1650 mMixerBufferSize(0),
1651 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1652 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001653 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001654 mEffectBuffer(NULL),
1655 mEffectBufferSize(0),
1656 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1657 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001658 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001659 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001660 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001661 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001662 // mStreamTypes[] initialized in constructor body
1663 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001664 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001665 mMixerStatus(MIXER_IDLE),
1666 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001667 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001668 mBytesRemaining(0),
1669 mCurrentWriteLength(0),
1670 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001671 mWriteAckSequence(0),
1672 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001673 mScreenState(AudioFlinger::mScreenState),
1674 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001675 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001676 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001677{
Glenn Kastend7dca052015-03-05 16:05:54 -08001678 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1679 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001680
1681 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1682 // it would be safer to explicitly pass initial masterVolume/masterMute as
1683 // parameter.
1684 //
1685 // If the HAL we are using has support for master volume or master mute,
1686 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1687 // and the mute set to false).
1688 mMasterVolume = audioFlinger->masterVolume_l();
1689 mMasterMute = audioFlinger->masterMute_l();
1690 if (mOutput && mOutput->audioHwDev) {
1691 if (mOutput->audioHwDev->canSetMasterVolume()) {
1692 mMasterVolume = 1.0;
1693 }
1694
1695 if (mOutput->audioHwDev->canSetMasterMute()) {
1696 mMasterMute = false;
1697 }
1698 }
1699
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001700 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001701
Eric Laurent223fd5c2014-11-11 13:43:36 -08001702 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001703 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001704 stream = (audio_stream_type_t) (stream + 1)) {
1705 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1706 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1707 }
Eric Laurent81784c32012-11-19 14:55:58 -08001708}
1709
1710AudioFlinger::PlaybackThread::~PlaybackThread()
1711{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001712 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001713 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001714 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001715 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001716}
1717
1718void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1719{
1720 dumpInternals(fd, args);
1721 dumpTracks(fd, args);
1722 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001723 dprintf(fd, " Local log:\n");
1724 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
Glenn Kasten0f11b512014-01-31 16:18:54 -08001727void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001728{
Eric Laurent81784c32012-11-19 14:55:58 -08001729 String8 result;
1730
Marco Nelissenb2208842014-02-07 14:00:50 -08001731 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001732 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1733 const stream_type_t *st = &mStreamTypes[i];
1734 if (i > 0) {
1735 result.appendFormat(", ");
1736 }
1737 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1738 if (st->mute) {
1739 result.append("M");
1740 }
1741 }
1742 result.append("\n");
1743 write(fd, result.string(), result.length());
1744 result.clear();
1745
Eric Laurent81784c32012-11-19 14:55:58 -08001746 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1747 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001748 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001749 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001750
1751 size_t numtracks = mTracks.size();
1752 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001753 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001754 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001755 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001756 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001757 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001758 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001759 Track::appendDumpHeader(result);
1760 for (size_t i = 0; i < numtracks; ++i) {
1761 sp<Track> track = mTracks[i];
1762 if (track != 0) {
1763 bool active = mActiveTracks.indexOf(track) >= 0;
1764 if (active) {
1765 numactiveseen++;
1766 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001767 result.append(prefix);
1768 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001769 }
1770 }
1771 } else {
1772 result.append("\n");
1773 }
1774 if (numactiveseen != numactive) {
1775 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001776 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001777 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001778 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001779 Track::appendDumpHeader(result);
1780 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001781 sp<Track> track = mActiveTracks[i];
1782 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001783 result.append(prefix);
1784 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001785 }
1786 }
1787 }
1788
1789 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001790}
1791
1792void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1793{
Glenn Kasten44182c22015-03-05 17:12:23 -08001794 dumpBase(fd, args);
1795
Elliott Hughes87cebad2014-05-22 10:14:43 -07001796 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001797 dprintf(fd, " Last write occurred (msecs): %llu\n",
1798 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001799 dprintf(fd, " Total writes: %d\n", mNumWrites);
1800 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1801 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1802 dprintf(fd, " Suspend count: %d\n", mSuspended);
1803 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1804 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1805 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1806 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001807 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001808 AudioStreamOut *output = mOutput;
1809 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001810 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1811 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001812 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1813 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1814 if (mPipeSink.get() != nullptr) {
1815 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1816 }
1817 if (output != nullptr) {
1818 dprintf(fd, " Hal stream dump:\n");
1819 (void)output->stream->dump(fd);
1820 }
Eric Laurent81784c32012-11-19 14:55:58 -08001821}
1822
1823// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001824
1825void AudioFlinger::PlaybackThread::onFirstRef()
1826{
Glenn Kastend7dca052015-03-05 16:05:54 -08001827 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001828}
1829
1830// ThreadBase virtuals
1831void AudioFlinger::PlaybackThread::preExit()
1832{
1833 ALOGV(" preExit()");
1834 // FIXME this is using hard-coded strings but in the future, this functionality will be
1835 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001836 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1837 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001838}
1839
1840// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1841sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1842 const sp<AudioFlinger::Client>& client,
1843 audio_stream_type_t streamType,
1844 uint32_t sampleRate,
1845 audio_format_t format,
1846 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001847 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001848 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001849 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001850 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001851 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001852 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001853 status_t *status,
1854 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001855{
Glenn Kasten74935e42013-12-19 08:56:45 -08001856 size_t frameCount = *pFrameCount;
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;
1860
1861 // special case for FAST flag considered OK if fast mixer is present
1862 if (hasFastMixer()) {
1863 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1864 }
1865
1866 // Check if requested flags are compatible with output stream flags
1867 if ((*flags & outputFlags) != *flags) {
1868 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1869 *flags, outputFlags);
1870 *flags = (audio_output_flags_t)(*flags & outputFlags);
1871 }
Eric Laurent81784c32012-11-19 14:55:58 -08001872
Eric Laurent81784c32012-11-19 14:55:58 -08001873 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001874 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001875 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001876 // PCM data
1877 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001878 // TODO: extract as a data library function that checks that a computationally
1879 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001880 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001881 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1882 (channelMask == AUDIO_CHANNEL_OUT_MONO
1883 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001884 // hardware sample rate
1885 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001886 // normal mixer has an associated fast mixer
1887 hasFastMixer() &&
1888 // there are sufficient fast track slots available
1889 (mFastTrackAvailMask != 0)
1890 // FIXME test that MixerThread for this fast track has a capable output HAL
1891 // FIXME add a permission test also?
1892 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001893 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1894 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001895 // read the fast track multiplier property the first time it is needed
1896 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1897 if (ok != 0) {
1898 ALOGE("%s pthread_once failed: %d", __func__, ok);
1899 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001900 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001901 }
Eric Laurent4c415062016-06-17 16:14:16 -07001902
1903 // check compatibility with audio effects.
1904 { // scope for mLock
1905 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001906 for (audio_session_t session : {
1907 AUDIO_SESSION_OUTPUT_STAGE,
1908 AUDIO_SESSION_OUTPUT_MIX,
1909 sessionId,
1910 }) {
1911 sp<EffectChain> chain = getEffectChain_l(session);
1912 if (chain.get() != nullptr) {
1913 audio_output_flags_t old = *flags;
1914 chain->checkOutputFlagCompatibility(flags);
1915 if (old != *flags) {
1916 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1917 (int)session, (int)old, (int)*flags);
1918 }
Eric Laurent4c415062016-06-17 16:14:16 -07001919 }
1920 }
1921 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001922 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001923 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1924 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001925 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001926 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1927 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001928 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001929 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001930 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001931 audio_is_linear_pcm(format),
1932 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001933 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001934 }
1935 }
1936 // For normal PCM streaming tracks, update minimum frame count.
1937 // For compatibility with AudioTrack calculation, buffer depth is forced
1938 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1939 // This is probably too conservative, but legacy application code may depend on it.
1940 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001941 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001942 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001943 // this must match AudioTrack.cpp calculateMinFrameCount().
1944 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001945 uint32_t latencyMs = 0;
1946 lStatus = mOutput->stream->getLatency(&latencyMs);
1947 if (lStatus != OK) {
1948 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1949 goto Exit;
1950 }
Eric Laurent81784c32012-11-19 14:55:58 -08001951 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1952 if (minBufCount < 2) {
1953 minBufCount = 2;
1954 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001955 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1956 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001957 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001958 minBufCount * sourceFramesNeededWithTimestretch(
1959 sampleRate, mNormalFrameCount,
1960 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001961 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001962 frameCount = minFrameCount;
1963 }
Eric Laurent81784c32012-11-19 14:55:58 -08001964 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001965 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001966
Glenn Kastenc3df8382014-03-13 15:05:25 -07001967 switch (mType) {
1968
1969 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001970 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001971 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001972 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1973 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001974 sampleRate, format, channelMask, mOutput, mFormat);
1975 lStatus = BAD_VALUE;
1976 goto Exit;
1977 }
1978 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001979 break;
1980
1981 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001982 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001983 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1984 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001985 sampleRate, format, channelMask, mOutput, mFormat);
1986 lStatus = BAD_VALUE;
1987 goto Exit;
1988 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001989 break;
1990
1991 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001992 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001993 ALOGE("createTrack_l() Bad parameter: format %#x \""
1994 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001995 format, mOutput, mFormat);
1996 lStatus = BAD_VALUE;
1997 goto Exit;
1998 }
Andy Hungcd044842014-08-07 11:04:34 -07001999 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002000 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2001 lStatus = BAD_VALUE;
2002 goto Exit;
2003 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002004 break;
2005
Eric Laurent81784c32012-11-19 14:55:58 -08002006 }
2007
2008 lStatus = initCheck();
2009 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002010 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002011 goto Exit;
2012 }
2013
2014 { // scope for mLock
2015 Mutex::Autolock _l(mLock);
2016
2017 // all tracks in same audio session must share the same routing strategy otherwise
2018 // conflicts will happen when tracks are moved from one output to another by audio policy
2019 // manager
2020 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2021 for (size_t i = 0; i < mTracks.size(); ++i) {
2022 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002023 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002024 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2025 if (sessionId == t->sessionId() && strategy != actual) {
2026 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2027 strategy, actual);
2028 lStatus = BAD_VALUE;
2029 goto Exit;
2030 }
2031 }
2032 }
2033
Glenn Kastend79072e2016-01-06 08:41:20 -08002034 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002035 channelMask, frameCount,
2036 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002037 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002038
Glenn Kasten03003332013-08-06 15:40:54 -07002039 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2040 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002041 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002042 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002043 goto Exit;
2044 }
2045 mTracks.add(track);
2046
2047 sp<EffectChain> chain = getEffectChain_l(sessionId);
2048 if (chain != 0) {
2049 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2050 track->setMainBuffer(chain->inBuffer());
2051 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2052 chain->incTrackCnt();
2053 }
2054
Eric Laurent05067782016-06-01 18:27:28 -07002055 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002056 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2057 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2058 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002059 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002060 }
2061 }
2062
2063 lStatus = NO_ERROR;
2064
2065Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002066 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002067 return track;
2068}
2069
2070uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2071{
2072 return latency;
2073}
2074
2075uint32_t AudioFlinger::PlaybackThread::latency() const
2076{
2077 Mutex::Autolock _l(mLock);
2078 return latency_l();
2079}
2080uint32_t AudioFlinger::PlaybackThread::latency_l() const
2081{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002082 uint32_t latency;
2083 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2084 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002085 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002086 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002087}
2088
2089void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2090{
2091 Mutex::Autolock _l(mLock);
2092 // Don't apply master volume in SW if our HAL can do it for us.
2093 if (mOutput && mOutput->audioHwDev &&
2094 mOutput->audioHwDev->canSetMasterVolume()) {
2095 mMasterVolume = 1.0;
2096 } else {
2097 mMasterVolume = value;
2098 }
2099}
2100
2101void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2102{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002103 if (isDuplicating()) {
2104 return;
2105 }
Eric Laurent81784c32012-11-19 14:55:58 -08002106 Mutex::Autolock _l(mLock);
2107 // Don't apply master mute in SW if our HAL can do it for us.
2108 if (mOutput && mOutput->audioHwDev &&
2109 mOutput->audioHwDev->canSetMasterMute()) {
2110 mMasterMute = false;
2111 } else {
2112 mMasterMute = muted;
2113 }
2114}
2115
2116void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2117{
2118 Mutex::Autolock _l(mLock);
2119 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002120 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002121}
2122
2123void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2124{
2125 Mutex::Autolock _l(mLock);
2126 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002127 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002128}
2129
2130float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2131{
2132 Mutex::Autolock _l(mLock);
2133 return mStreamTypes[stream].volume;
2134}
2135
2136// addTrack_l() must be called with ThreadBase::mLock held
2137status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2138{
2139 status_t status = ALREADY_EXISTS;
2140
Eric Laurent81784c32012-11-19 14:55:58 -08002141 if (mActiveTracks.indexOf(track) < 0) {
2142 // the track is newly added, make sure it fills up all its
2143 // buffers before playing. This is to ensure the client will
2144 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002145 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002146 TrackBase::track_state state = track->mState;
2147 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002148 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002149 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002150 mLock.lock();
2151 // abort track was stopped/paused while we released the lock
2152 if (state != track->mState) {
2153 if (status == NO_ERROR) {
2154 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002155 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002156 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 mLock.lock();
2158 }
2159 return INVALID_OPERATION;
2160 }
2161 // abort if start is rejected by audio policy manager
2162 if (status != NO_ERROR) {
2163 return PERMISSION_DENIED;
2164 }
2165#ifdef ADD_BATTERY_DATA
2166 // to track the speaker usage
2167 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2168#endif
2169 }
2170
Eric Laurent51716182016-02-29 18:00:56 -08002171 // set retry count for buffer fill
2172 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002173 if (track->isStopping_1()) {
2174 track->mRetryCount = kMaxTrackStopRetriesOffload;
2175 } else {
2176 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2177 }
2178 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002179 } else {
2180 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002181 track->mFillingUpStatus =
2182 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002183 }
2184
Eric Laurent81784c32012-11-19 14:55:58 -08002185 track->mResetDone = false;
2186 track->mPresentationCompleteFrames = 0;
2187 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002188 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2189 if (chain != 0) {
2190 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2191 track->sessionId());
2192 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002193 }
2194
2195 status = NO_ERROR;
2196 }
2197
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002198 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002199 return status;
2200}
2201
Eric Laurentbfb1b832013-01-07 09:53:42 -08002202bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002203{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002204 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002205 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2207 track->mState = TrackBase::STOPPED;
2208 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002209 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002210 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002211 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002212 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213
2214 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002215}
2216
2217void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2218{
2219 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002220
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002221 String8 result;
2222 track->appendDump(result, false /* active */);
2223 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002224
Eric Laurent81784c32012-11-19 14:55:58 -08002225 mTracks.remove(track);
2226 deleteTrackName_l(track->name());
2227 // redundant as track is about to be destroyed, for dumpsys only
2228 track->mName = -1;
2229 if (track->isFastTrack()) {
2230 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002231 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002232 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2233 mFastTrackAvailMask |= 1 << index;
2234 // redundant as track is about to be destroyed, for dumpsys only
2235 track->mFastIndex = -1;
2236 }
2237 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2238 if (chain != 0) {
2239 chain->decTrackCnt();
2240 }
2241}
2242
2243String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2244{
Eric Laurent81784c32012-11-19 14:55:58 -08002245 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002246 String8 out_s8;
2247 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2248 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002249 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002250 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002251}
2252
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002253void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002254 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2255 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002256
Eric Laurent73e26b62015-04-27 16:55:58 -07002257 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002258
2259 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002260 case AUDIO_OUTPUT_OPENED:
2261 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002262 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002263 desc->mChannelMask = mChannelMask;
2264 desc->mSamplingRate = mSampleRate;
2265 desc->mFormat = mFormat;
2266 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002267 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002268 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002269 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002270 break;
2271
Eric Laurent73e26b62015-04-27 16:55:58 -07002272 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002273 default:
2274 break;
2275 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002276 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002277}
2278
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002279void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002280{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002281 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002282}
2283
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002284void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002285{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002286 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002287}
2288
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002289void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002290{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002291 mCallbackThread->setAsyncError();
2292}
2293
Eric Laurent3b4529e2013-09-05 18:09:19 -07002294void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002295{
2296 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002297 // reject out of sequence requests
2298 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2299 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002300 mWaitWorkCV.signal();
2301 }
2302}
2303
Eric Laurent3b4529e2013-09-05 18:09:19 -07002304void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002305{
2306 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002307 // reject out of sequence requests
2308 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2309 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 mWaitWorkCV.signal();
2311 }
2312}
2313
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002314void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002315{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002316 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002317 mSampleRate = mOutput->getSampleRate();
2318 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002319 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002320 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002321 }
Andy Hung9a592762014-07-21 21:56:01 -07002322 if ((mType == MIXER || mType == DUPLICATING)
2323 && !isValidPcmSinkChannelMask(mChannelMask)) {
2324 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2325 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002326 }
Andy Hunge5412692014-05-16 11:25:07 -07002327 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002328
2329 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002330 status_t result = mOutput->stream->getFormat(&mHALFormat);
2331 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002332 // Get format from the shim, which will be different than the HAL format
2333 // if playing compressed audio over HDMI passthrough.
2334 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002335 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002336 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002337 }
Andy Hung6146c082014-03-18 11:56:15 -07002338 if ((mType == MIXER || mType == DUPLICATING)
2339 && !isValidPcmSinkFormat(mFormat)) {
2340 LOG_FATAL("HAL format %#x not supported for mixed output",
2341 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002342 }
Phil Burk062e67a2015-02-11 13:40:50 -08002343 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002344 result = mOutput->stream->getBufferSize(&mBufferSize);
2345 LOG_ALWAYS_FATAL_IF(result != OK,
2346 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002347 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002348 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002349 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002350 mFrameCount);
2351 }
2352
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002353 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2354 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002356 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002357 }
2358 }
2359
Eric Laurentd1f69b02014-12-15 14:33:13 -08002360 mHwSupportsPause = false;
2361 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002362 bool supportsPause = false, supportsResume = false;
2363 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2364 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002365 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002366 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002367 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002368 } else if (supportsResume) {
2369 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002370 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002371 }
2372 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002373 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2374 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2375 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002376
Andy Hungfbfc3952015-01-15 13:33:51 -08002377 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2378 // For best precision, we use float instead of the associated output
2379 // device format (typically PCM 16 bit).
2380
2381 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2382 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2383 mBufferSize = mFrameSize * mFrameCount;
2384
2385 // TODO: We currently use the associated output device channel mask and sample rate.
2386 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2387 // (if a valid mask) to avoid premature downmix.
2388 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2389 // instead of the output device sample rate to avoid loss of high frequency information.
2390 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2391 }
2392
Andy Hung09a50072014-02-27 14:30:47 -08002393 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002394 double multiplier = 1.0;
2395 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2396 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002397 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2398 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002399
Eric Laurent81784c32012-11-19 14:55:58 -08002400 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2401 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2402 maxNormalFrameCount = maxNormalFrameCount & ~15;
2403 if (maxNormalFrameCount < minNormalFrameCount) {
2404 maxNormalFrameCount = minNormalFrameCount;
2405 }
2406 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2407 if (multiplier <= 1.0) {
2408 multiplier = 1.0;
2409 } else if (multiplier <= 2.0) {
2410 if (2 * mFrameCount <= maxNormalFrameCount) {
2411 multiplier = 2.0;
2412 } else {
2413 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2414 }
2415 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002416 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002417 }
2418 }
2419 mNormalFrameCount = multiplier * mFrameCount;
2420 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002421 if (mType == MIXER || mType == DUPLICATING) {
2422 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2423 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002424 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002425 mNormalFrameCount);
2426
Andy Hung08fb1742015-05-31 23:22:10 -07002427 // Check if we want to throttle the processing to no more than 2x normal rate
2428 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002429 mThreadThrottleTimeMs = 0;
2430 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002431 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2432
Andy Hung010a1a12014-03-13 13:57:33 -07002433 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2434 // Originally this was int16_t[] array, need to remove legacy implications.
2435 free(mSinkBuffer);
2436 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002437 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2438 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2439 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002440 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002441
Andy Hung69aed5f2014-02-25 17:24:40 -08002442 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2443 // drives the output.
2444 free(mMixerBuffer);
2445 mMixerBuffer = NULL;
2446 if (mMixerBufferEnabled) {
2447 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2448 mMixerBufferSize = mNormalFrameCount * mChannelCount
2449 * audio_bytes_per_sample(mMixerBufferFormat);
2450 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2451 }
Andy Hung98ef9782014-03-04 14:46:50 -08002452 free(mEffectBuffer);
2453 mEffectBuffer = NULL;
2454 if (mEffectBufferEnabled) {
2455 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2456 mEffectBufferSize = mNormalFrameCount * mChannelCount
2457 * audio_bytes_per_sample(mEffectBufferFormat);
2458 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2459 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002460
Eric Laurent81784c32012-11-19 14:55:58 -08002461 // force reconfiguration of effect chains and engines to take new buffer size and audio
2462 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002463 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002464 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2465 // matter.
2466 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2467 Vector< sp<EffectChain> > effectChains = mEffectChains;
2468 for (size_t i = 0; i < effectChains.size(); i ++) {
2469 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2470 }
2471}
2472
2473
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002474status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002475{
2476 if (halFrames == NULL || dspFrames == NULL) {
2477 return BAD_VALUE;
2478 }
2479 Mutex::Autolock _l(mLock);
2480 if (initCheck() != NO_ERROR) {
2481 return INVALID_OPERATION;
2482 }
Andy Hung818e7a32016-02-16 18:08:07 -08002483 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002484 *halFrames = framesWritten;
2485
2486 if (isSuspended()) {
2487 // return an estimation of rendered frames when the output is suspended
2488 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002489 *dspFrames = (uint32_t)
2490 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002491 return NO_ERROR;
2492 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002493 status_t status;
2494 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002495 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002496 *dspFrames = (size_t)frames;
2497 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002498 }
2499}
2500
Eric Laurent4c415062016-06-17 16:14:16 -07002501// hasAudioSession_l() must be called with ThreadBase::mLock held
2502uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002503{
Eric Laurent81784c32012-11-19 14:55:58 -08002504 uint32_t result = 0;
2505 if (getEffectChain_l(sessionId) != 0) {
2506 result = EFFECT_SESSION;
2507 }
2508
2509 for (size_t i = 0; i < mTracks.size(); ++i) {
2510 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002511 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002512 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002513 if (track->isFastTrack()) {
2514 result |= FAST_SESSION;
2515 }
Eric Laurent81784c32012-11-19 14:55:58 -08002516 break;
2517 }
2518 }
2519
2520 return result;
2521}
2522
Glenn Kastend848eb42016-03-08 13:42:11 -08002523uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002524{
2525 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2526 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2527 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2528 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2529 }
2530 for (size_t i = 0; i < mTracks.size(); i++) {
2531 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002532 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002533 return AudioSystem::getStrategyForStream(track->streamType());
2534 }
2535 }
2536 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2537}
2538
2539
Phil Burk062e67a2015-02-11 13:40:50 -08002540AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002541{
2542 Mutex::Autolock _l(mLock);
2543 return mOutput;
2544}
2545
Phil Burk062e67a2015-02-11 13:40:50 -08002546AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002547{
2548 Mutex::Autolock _l(mLock);
2549 AudioStreamOut *output = mOutput;
2550 mOutput = NULL;
2551 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2552 // must push a NULL and wait for ack
2553 mOutputSink.clear();
2554 mPipeSink.clear();
2555 mNormalSink.clear();
2556 return output;
2557}
2558
2559// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002560sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002561{
2562 if (mOutput == NULL) {
2563 return NULL;
2564 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002565 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002566}
2567
2568uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2569{
2570 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2571}
2572
2573status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2574{
2575 if (!isValidSyncEvent(event)) {
2576 return BAD_VALUE;
2577 }
2578
2579 Mutex::Autolock _l(mLock);
2580
2581 for (size_t i = 0; i < mTracks.size(); ++i) {
2582 sp<Track> track = mTracks[i];
2583 if (event->triggerSession() == track->sessionId()) {
2584 (void) track->setSyncEvent(event);
2585 return NO_ERROR;
2586 }
2587 }
2588
2589 return NAME_NOT_FOUND;
2590}
2591
2592bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2593{
2594 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2595}
2596
2597void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2598 const Vector< sp<Track> >& tracksToRemove)
2599{
2600 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002601 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002602 for (size_t i = 0 ; i < count ; i++) {
2603 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002604 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002605 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002606 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002607#ifdef ADD_BATTERY_DATA
2608 // to track the speaker usage
2609 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2610#endif
2611 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002612 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002613 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002614 }
Eric Laurent81784c32012-11-19 14:55:58 -08002615 }
2616 }
2617 }
Eric Laurent81784c32012-11-19 14:55:58 -08002618}
2619
2620void AudioFlinger::PlaybackThread::checkSilentMode_l()
2621{
2622 if (!mMasterMute) {
2623 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002624 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2625 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2626 return;
2627 }
Eric Laurent81784c32012-11-19 14:55:58 -08002628 if (property_get("ro.audio.silent", value, "0") > 0) {
2629 char *endptr;
2630 unsigned long ul = strtoul(value, &endptr, 0);
2631 if (*endptr == '\0' && ul != 0) {
2632 ALOGD("Silence is golden");
2633 // The setprop command will not allow a property to be changed after
2634 // the first time it is set, so we don't have to worry about un-muting.
2635 setMasterMute_l(true);
2636 }
2637 }
2638 }
2639}
2640
2641// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002642ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002643{
Eric Laurent81784c32012-11-19 14:55:58 -08002644 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002646 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002647
2648 // If an NBAIO sink is present, use it to write the normal mixer's submix
2649 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002650
Andy Hung010a1a12014-03-13 13:57:33 -07002651 const size_t count = mBytesRemaining / mFrameSize;
2652
Simon Wilson2d590962012-11-29 15:18:50 -08002653 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002654 // update the setpoint when AudioFlinger::mScreenState changes
2655 uint32_t screenState = AudioFlinger::mScreenState;
2656 if (screenState != mScreenState) {
2657 mScreenState = screenState;
2658 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2659 if (pipe != NULL) {
2660 pipe->setAvgFrames((mScreenState & 1) ?
2661 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2662 }
2663 }
Andy Hung010a1a12014-03-13 13:57:33 -07002664 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002665 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002666 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002667 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002668 } else {
2669 bytesWritten = framesWritten;
2670 }
2671 // otherwise use the HAL / AudioStreamOut directly
2672 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002674
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002676 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2677 mWriteAckSequence += 2;
2678 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002680 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002682 // FIXME We should have an implementation of timestamps for direct output threads.
2683 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002684 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002685
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 if (mUseAsyncWrite &&
2687 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2688 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002689 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002690 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002691 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 }
Eric Laurent81784c32012-11-19 14:55:58 -08002693 }
2694
Eric Laurent81784c32012-11-19 14:55:58 -08002695 mNumWrites++;
2696 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002697 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002698 return bytesWritten;
2699}
2700
2701void AudioFlinger::PlaybackThread::threadLoop_drain()
2702{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002703 bool supportsDrain = false;
2704 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002705 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2706 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002707 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2708 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002709 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002710 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002711 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002712 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002713 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002714 }
2715}
2716
2717void AudioFlinger::PlaybackThread::threadLoop_exit()
2718{
Eric Laurent275e8e92014-11-30 15:14:47 -08002719 {
2720 Mutex::Autolock _l(mLock);
2721 for (size_t i = 0; i < mTracks.size(); i++) {
2722 sp<Track> track = mTracks[i];
2723 track->invalidate();
2724 }
Andy Hungdae27702016-10-31 14:01:16 -07002725 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2726 // After we exit there are no more track changes sent to BatteryNotifier
2727 // because that requires an active threadLoop.
2728 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2729 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002730 }
Eric Laurent81784c32012-11-19 14:55:58 -08002731}
2732
2733/*
2734The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002735 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002736 - mActiveSleepTimeUs from activeSleepTimeUs()
2737 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002738 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2739 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002740 - maxPeriod from frame count and sample rate (MIXER only)
2741
2742The parameters that affect these derived values are:
2743 - frame count
2744 - frame size
2745 - sample rate
2746 - device type: A2DP or not
2747 - device latency
2748 - format: PCM or not
2749 - active sleep time
2750 - idle sleep time
2751*/
2752
2753void AudioFlinger::PlaybackThread::cacheParameters_l()
2754{
Andy Hung25c2dac2014-02-27 14:56:00 -08002755 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002756 mActiveSleepTimeUs = activeSleepTimeUs();
2757 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002758
2759 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2760 // truncating audio when going to standby.
2761 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2762 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2763 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2764 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2765 }
2766 }
Eric Laurent81784c32012-11-19 14:55:58 -08002767}
2768
Eric Laurent13084622016-05-17 10:51:49 -07002769bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002770{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002771 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002772 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002773 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002774 size_t size = mTracks.size();
2775 for (size_t i = 0; i < size; i++) {
2776 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002777 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002778 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002779 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002780 }
2781 }
Eric Laurent13084622016-05-17 10:51:49 -07002782 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002783}
2784
Haynes Mathew George05317d22016-05-03 16:34:26 -07002785void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2786{
2787 Mutex::Autolock _l(mLock);
2788 invalidateTracks_l(streamType);
2789}
2790
Eric Laurent81784c32012-11-19 14:55:58 -08002791status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2792{
Glenn Kastend848eb42016-03-08 13:42:11 -08002793 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002794 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2795 status_t result = EffectBufferHalInterface::mirror(
2796 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2797 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2798 &halInBuffer);
2799 if (result != OK) return result;
2800 halOutBuffer = halInBuffer;
2801 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002802
2803 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002804 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002805 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002806 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002807 if (mType != DIRECT) {
2808 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002809 status_t result = EffectBufferHalInterface::allocate(
2810 numSamples * sizeof(int16_t),
2811 &halInBuffer);
2812 if (result != OK) return result;
2813 buffer = halInBuffer->audioBuffer()->s16;
2814 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2815 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002816 }
2817
2818 // Attach all tracks with same session ID to this chain.
2819 for (size_t i = 0; i < mTracks.size(); ++i) {
2820 sp<Track> track = mTracks[i];
2821 if (session == track->sessionId()) {
2822 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2823 buffer);
2824 track->setMainBuffer(buffer);
2825 chain->incTrackCnt();
2826 }
2827 }
2828
2829 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002830 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002831 if (session == track->sessionId()) {
2832 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2833 chain->incActiveTrackCnt();
2834 }
2835 }
2836 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002837 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002838 chain->setInBuffer(halInBuffer);
2839 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002840 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002841 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002842 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2843 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002844 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002845 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002846 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002847 // Effect chain for other sessions are inserted at beginning of effect
2848 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002849 // sessions is not important.
2850 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2851 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2852 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002853 size_t size = mEffectChains.size();
2854 size_t i = 0;
2855 for (i = 0; i < size; i++) {
2856 if (mEffectChains[i]->sessionId() < session) {
2857 break;
2858 }
2859 }
2860 mEffectChains.insertAt(chain, i);
2861 checkSuspendOnAddEffectChain_l(chain);
2862
2863 return NO_ERROR;
2864}
2865
2866size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2867{
Glenn Kastend848eb42016-03-08 13:42:11 -08002868 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002869
2870 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2871
2872 for (size_t i = 0; i < mEffectChains.size(); i++) {
2873 if (chain == mEffectChains[i]) {
2874 mEffectChains.removeAt(i);
2875 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002876 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002877 if (session == track->sessionId()) {
2878 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2879 chain.get(), session);
2880 chain->decActiveTrackCnt();
2881 }
2882 }
2883
2884 // detach all tracks with same session ID from this chain
2885 for (size_t i = 0; i < mTracks.size(); ++i) {
2886 sp<Track> track = mTracks[i];
2887 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002888 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002889 chain->decTrackCnt();
2890 }
2891 }
2892 break;
2893 }
2894 }
2895 return mEffectChains.size();
2896}
2897
2898status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002899 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002900{
2901 Mutex::Autolock _l(mLock);
2902 return attachAuxEffect_l(track, EffectId);
2903}
2904
2905status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002906 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002907{
2908 status_t status = NO_ERROR;
2909
2910 if (EffectId == 0) {
2911 track->setAuxBuffer(0, NULL);
2912 } else {
2913 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2914 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2915 if (effect != 0) {
2916 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2917 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2918 } else {
2919 status = INVALID_OPERATION;
2920 }
2921 } else {
2922 status = BAD_VALUE;
2923 }
2924 }
2925 return status;
2926}
2927
2928void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2929{
2930 for (size_t i = 0; i < mTracks.size(); ++i) {
2931 sp<Track> track = mTracks[i];
2932 if (track->auxEffectId() == effectId) {
2933 attachAuxEffect_l(track, 0);
2934 }
2935 }
2936}
2937
2938bool AudioFlinger::PlaybackThread::threadLoop()
2939{
Glenn Kasten388d5712017-04-07 14:38:41 -07002940 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002941
Eric Laurent81784c32012-11-19 14:55:58 -08002942 Vector< sp<Track> > tracksToRemove;
2943
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002944 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002945 nsecs_t lastWriteFinished = -1; // time last server write completed
2946 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002947
2948 // MIXER
2949 nsecs_t lastWarning = 0;
2950
2951 // DUPLICATING
2952 // FIXME could this be made local to while loop?
2953 writeFrames = 0;
2954
2955 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002956 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002957
2958 if (mType == MIXER) {
2959 sleepTimeShift = 0;
2960 }
2961
2962 CpuStats cpuStats;
2963 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2964
2965 acquireWakeLock();
2966
Glenn Kasteneef598c2017-04-03 14:41:13 -07002967 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2968 // thread associated with this PlaybackThread.
2969 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2970 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002971 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2972 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002973 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002974 const char *logString = NULL;
2975
rago1bb90822017-05-02 18:31:48 -07002976 // Estimated time for next buffer to be written to hal. This is used only on
2977 // suspended mode (for now) to help schedule the wait time until next iteration.
2978 nsecs_t timeLoopNextNs = 0;
2979
Eric Laurent664539d2013-09-23 18:24:31 -07002980 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002981
Eric Laurent81784c32012-11-19 14:55:58 -08002982 while (!exitPending())
2983 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002984 // Log merge requests are performed during AudioFlinger binder transactions, but
2985 // that does not cover audio playback. It's requested here for that reason.
2986 mAudioFlinger->requestLogMerge();
2987
Eric Laurent81784c32012-11-19 14:55:58 -08002988 cpuStats.sample(myName);
2989
2990 Vector< sp<EffectChain> > effectChains;
2991
Eric Laurent81784c32012-11-19 14:55:58 -08002992 { // scope for mLock
2993
2994 Mutex::Autolock _l(mLock);
2995
Eric Laurent021cf962014-05-13 10:18:14 -07002996 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002997
Glenn Kasteneef598c2017-04-03 14:41:13 -07002998 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002999 if (logString != NULL) {
3000 mNBLogWriter->logTimestamp();
3001 mNBLogWriter->log(logString);
3002 logString = NULL;
3003 }
3004
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003005 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003006 // and associate with the sink frames written out. We need
3007 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003008 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003009 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003010 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003011 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003012 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003013 ExtendedTimestamp timestamp; // use private copy to fetch
3014 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003015
3016 // We keep track of the last valid kernel position in case we are in underrun
3017 // and the normal mixer period is the same as the fast mixer period, or there
3018 // is some error from the HAL.
3019 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3020 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3021 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3022 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3023 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3024
3025 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3026 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3027 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3028 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003029 }
3030
3031 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3032 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003033 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003034 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003035 }
3036
Andy Hung818e7a32016-02-16 18:08:07 -08003037 // copy over kernel info
3038 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003039 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3040 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003041 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3042 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003043 }
3044 // mFramesWritten for non-offloaded tracks are contiguous
3045 // even after standby() is called. This is useful for the track frame
3046 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003047 bool serverLocationUpdate = false;
3048 if (mFramesWritten != lastFramesWritten) {
3049 serverLocationUpdate = true;
3050 lastFramesWritten = mFramesWritten;
3051 }
3052 // Only update timestamps if there is a meaningful change.
3053 // Either the kernel timestamp must be valid or we have written something.
3054 if (kernelLocationUpdate || serverLocationUpdate) {
3055 if (serverLocationUpdate) {
3056 // use the time before we called the HAL write - it is a bit more accurate
3057 // to when the server last read data than the current time here.
3058 //
3059 // If we haven't written anything, mLastWriteTime will be -1
3060 // and we use systemTime().
3061 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3062 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3063 ? systemTime() : mLastWriteTime;
3064 }
Andy Hungdae27702016-10-31 14:01:16 -07003065
3066 for (const sp<Track> &t : mActiveTracks) {
3067 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003068 t->updateTrackFrameInfo(
3069 t->mAudioTrackServerProxy->framesReleased(),
3070 mFramesWritten,
3071 mTimestamp);
3072 }
Andy Hunge10393e2015-06-12 13:59:33 -07003073 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003074 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003075#if 0
3076 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003077 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003078 timespec ts;
3079 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003080 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003081 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003082 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003083 }
3084 ++z;
3085#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003086 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003087 if (mSignalPending) {
3088 // A signal was raised while we were unlocked
3089 mSignalPending = false;
3090 } else if (waitingAsyncCallback_l()) {
3091 if (exitPending()) {
3092 break;
3093 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003094 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003095 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003096 releaseWakeLock_l();
3097 released = true;
3098 }
Andy Hung10cbff12017-02-21 17:30:14 -08003099
3100 const int64_t waitNs = computeWaitTimeNs_l();
3101 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3102 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3103 if (status == TIMED_OUT) {
3104 mSignalPending = true; // if timeout recheck everything
3105 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003106 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003107 if (released) {
3108 acquireWakeLock_l();
3109 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003110 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3111 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003112
3113 continue;
3114 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003115 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003116 isSuspended()) {
3117 // put audio hardware into standby after short delay
3118 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003119
3120 threadLoop_standby();
3121
3122 mStandby = true;
3123 }
3124
3125 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3126 // we're about to wait, flush the binder command buffer
3127 IPCThreadState::self()->flushCommands();
3128
3129 clearOutputTracks();
3130
3131 if (exitPending()) {
3132 break;
3133 }
3134
3135 releaseWakeLock_l();
3136 // wait until we have something to do...
3137 ALOGV("%s going to sleep", myName.string());
3138 mWaitWorkCV.wait(mLock);
3139 ALOGV("%s waking up", myName.string());
3140 acquireWakeLock_l();
3141
3142 mMixerStatus = MIXER_IDLE;
3143 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3144 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003145 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003146 checkSilentMode_l();
3147
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003148 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3149 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003150 if (mType == MIXER) {
3151 sleepTimeShift = 0;
3152 }
3153
3154 continue;
3155 }
3156 }
Eric Laurent81784c32012-11-19 14:55:58 -08003157 // mMixerStatusIgnoringFastTracks is also updated internally
3158 mMixerStatus = prepareTracks_l(&tracksToRemove);
3159
Andy Hungdae27702016-10-31 14:01:16 -07003160 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003161
Eric Laurent81784c32012-11-19 14:55:58 -08003162 // prevent any changes in effect chain list and in each effect chain
3163 // during mixing and effect process as the audio buffers could be deleted
3164 // or modified if an effect is created or deleted
3165 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003166 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003167
Eric Laurentbfb1b832013-01-07 09:53:42 -08003168 if (mBytesRemaining == 0) {
3169 mCurrentWriteLength = 0;
3170 if (mMixerStatus == MIXER_TRACKS_READY) {
3171 // threadLoop_mix() sets mCurrentWriteLength
3172 threadLoop_mix();
3173 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3174 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003175 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176 // must be written to HAL
3177 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003178 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003179 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003180 }
3181 }
Andy Hung98ef9782014-03-04 14:46:50 -08003182 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003183 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003184 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3185 // or mSinkBuffer (if there are no effects).
3186 //
3187 // This is done pre-effects computation; if effects change to
3188 // support higher precision, this needs to move.
3189 //
3190 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003191 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003192 if (mMixerBufferValid) {
3193 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3194 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3195
Andy Hung2ddee192015-12-18 17:34:44 -08003196 // mono blend occurs for mixer threads only (not direct or offloaded)
3197 // and is handled here if we're going directly to the sink.
3198 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003199 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3200 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003201 }
3202
Andy Hung98ef9782014-03-04 14:46:50 -08003203 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3204 mNormalFrameCount * mChannelCount);
3205 }
3206
Eric Laurentbfb1b832013-01-07 09:53:42 -08003207 mBytesRemaining = mCurrentWriteLength;
3208 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003209 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3210 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3211 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3212 mBytesWritten += mBytesRemaining;
3213 mFramesWritten += framesRemaining;
3214 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003215 mBytesRemaining = 0;
3216 }
Eric Laurent81784c32012-11-19 14:55:58 -08003217
Eric Laurentbfb1b832013-01-07 09:53:42 -08003218 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003219 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003220 for (size_t i = 0; i < effectChains.size(); i ++) {
3221 effectChains[i]->process_l();
3222 }
Eric Laurent81784c32012-11-19 14:55:58 -08003223 }
3224 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003225 // Process effect chains for offloaded thread even if no audio
3226 // was read from audio track: process only updates effect state
3227 // and thus does have to be synchronized with audio writes but may have
3228 // to be called while waiting for async write callback
3229 if (mType == OFFLOAD) {
3230 for (size_t i = 0; i < effectChains.size(); i ++) {
3231 effectChains[i]->process_l();
3232 }
3233 }
Eric Laurent81784c32012-11-19 14:55:58 -08003234
Andy Hung98ef9782014-03-04 14:46:50 -08003235 // Only if the Effects buffer is enabled and there is data in the
3236 // Effects buffer (buffer valid), we need to
3237 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003238 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003239 if (mEffectBufferValid) {
3240 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003241
3242 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003243 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3244 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003245 }
3246
Andy Hung98ef9782014-03-04 14:46:50 -08003247 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3248 mNormalFrameCount * mChannelCount);
3249 }
3250
Eric Laurent81784c32012-11-19 14:55:58 -08003251 // enable changes in effect chain
3252 unlockEffectChains(effectChains);
3253
Eric Laurentbfb1b832013-01-07 09:53:42 -08003254 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003255 // mSleepTimeUs == 0 means we must write to audio hardware
3256 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003257 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003258 // We save lastWriteFinished here, as previousLastWriteFinished,
3259 // for throttling. On thread start, previousLastWriteFinished will be
3260 // set to -1, which properly results in no throttling after the first write.
3261 nsecs_t previousLastWriteFinished = lastWriteFinished;
3262 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003263 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003264 // FIXME rewrite to reduce number of system calls
3265 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003266 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003267 lastWriteFinished = systemTime();
3268 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 if (ret < 0) {
3270 mBytesRemaining = 0;
3271 } else {
3272 mBytesWritten += ret;
3273 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003274 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 }
3276 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3277 (mMixerStatus == MIXER_DRAIN_ALL)) {
3278 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003279 }
Andy Hung08fb1742015-05-31 23:22:10 -07003280 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003281 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003282 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003283 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003284 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003285 ATRACE_NAME("underrun");
3286 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003287 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003288 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003289 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 }
Andy Hung08fb1742015-05-31 23:22:10 -07003291
3292 if (mThreadThrottle
3293 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3294 && ret > 0) { // we wrote something
3295 // Limit MixerThread data processing to no more than twice the
3296 // expected processing rate.
3297 //
3298 // This helps prevent underruns with NuPlayer and other applications
3299 // which may set up buffers that are close to the minimum size, or use
3300 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3301 //
3302 // The throttle smooths out sudden large data drains from the device,
3303 // e.g. when it comes out of standby, which often causes problems with
3304 // (1) mixer threads without a fast mixer (which has its own warm-up)
3305 // (2) minimum buffer sized tracks (even if the track is full,
3306 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003307 //
3308 // Total time spent in last processing cycle equals time spent in
3309 // 1. threadLoop_write, as well as time spent in
3310 // 2. threadLoop_mix (significant for heavy mixing, especially
3311 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003312
Andy Hung69488c42016-05-16 18:43:33 -07003313 // it's OK if deltaMs is an overestimate.
3314 const int32_t deltaMs =
3315 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003316 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3317 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3318 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003319 // notify of throttle start on verbose log
3320 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3321 "mixer(%p) throttle begin:"
3322 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003323 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003324 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003325 // Throttle must be attributed to the previous mixer loop's write time
3326 // to allow back-to-back throttling.
3327 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003328 } else {
3329 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3330 if (diff > 0) {
3331 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003332 // but prevent spamming for bluetooth
3333 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3334 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003335 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3336 }
Andy Hung08fb1742015-05-31 23:22:10 -07003337 }
3338 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003339 }
Eric Laurent81784c32012-11-19 14:55:58 -08003340
Eric Laurentbfb1b832013-01-07 09:53:42 -08003341 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003342 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003343 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003344 // suspended requires accurate metering of sleep time.
3345 if (isSuspended()) {
3346 // advance by expected sleepTime
3347 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3348 const nsecs_t nowNs = systemTime();
3349
3350 // compute expected next time vs current time.
3351 // (negative deltas are treated as delays).
3352 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3353 if (deltaNs < -kMaxNextBufferDelayNs) {
3354 // Delays longer than the max allowed trigger a reset.
3355 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3356 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3357 timeLoopNextNs = nowNs + deltaNs;
3358 } else if (deltaNs < 0) {
3359 // Delays within the max delay allowed: zero the delta/sleepTime
3360 // to help the system catch up in the next iteration(s)
3361 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3362 deltaNs = 0;
3363 }
3364 // update sleep time (which is >= 0)
3365 mSleepTimeUs = deltaNs / 1000;
3366 }
Eric Laurente93cc032016-05-05 10:15:10 -07003367 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3368 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003369 }
Glenn Kastene7754022014-10-31 12:11:26 -07003370 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 }
Eric Laurent81784c32012-11-19 14:55:58 -08003372 }
3373
3374 // Finally let go of removed track(s), without the lock held
3375 // since we can't guarantee the destructors won't acquire that
3376 // same lock. This will also mutate and push a new fast mixer state.
3377 threadLoop_removeTracks(tracksToRemove);
3378 tracksToRemove.clear();
3379
3380 // FIXME I don't understand the need for this here;
3381 // it was in the original code but maybe the
3382 // assignment in saveOutputTracks() makes this unnecessary?
3383 clearOutputTracks();
3384
3385 // Effect chains will be actually deleted here if they were removed from
3386 // mEffectChains list during mixing or effects processing
3387 effectChains.clear();
3388
3389 // FIXME Note that the above .clear() is no longer necessary since effectChains
3390 // is now local to this block, but will keep it for now (at least until merge done).
3391 }
3392
Eric Laurentbfb1b832013-01-07 09:53:42 -08003393 threadLoop_exit();
3394
Eric Laurentcf817a22014-08-04 20:36:31 -07003395 if (!mStandby) {
3396 threadLoop_standby();
3397 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003398 }
3399
3400 releaseWakeLock();
3401
3402 ALOGV("Thread %p type %d exiting", this, mType);
3403 return false;
3404}
3405
Eric Laurentbfb1b832013-01-07 09:53:42 -08003406// removeTracks_l() must be called with ThreadBase::mLock held
3407void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3408{
3409 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003410 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003411 for (size_t i=0 ; i<count ; i++) {
3412 const sp<Track>& track = tracksToRemove.itemAt(i);
3413 mActiveTracks.remove(track);
3414 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3415 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3416 if (chain != 0) {
3417 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3418 track->sessionId());
3419 chain->decActiveTrackCnt();
3420 }
3421 if (track->isTerminated()) {
3422 removeTrack_l(track);
3423 }
3424 }
3425 }
3426
3427}
Eric Laurent81784c32012-11-19 14:55:58 -08003428
Eric Laurentaccc1472013-09-20 09:36:34 -07003429status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3430{
3431 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003432 ExtendedTimestamp ets;
3433 status_t status = mNormalSink->getTimestamp(ets);
3434 if (status == NO_ERROR) {
3435 status = ets.getBestTimestamp(&timestamp);
3436 }
3437 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003438 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003439 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003440 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003441 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003442 timestamp.mPosition = (uint32_t)position64;
3443 return NO_ERROR;
3444 }
3445 }
3446 return INVALID_OPERATION;
3447}
Eric Laurent1c333e22014-05-20 10:48:17 -07003448
Eric Laurent054d9d32015-04-24 08:48:48 -07003449status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3450 audio_patch_handle_t *handle)
3451{
Andy Hungf60abce2016-08-26 11:37:54 -07003452 status_t status;
3453 if (property_get_bool("af.patch_park", false /* default_value */)) {
3454 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3455 // or if HAL does not properly lock against access.
3456 AutoPark<FastMixer> park(mFastMixer);
3457 status = PlaybackThread::createAudioPatch_l(patch, handle);
3458 } else {
3459 status = PlaybackThread::createAudioPatch_l(patch, handle);
3460 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003461 return status;
3462}
3463
Eric Laurent1c333e22014-05-20 10:48:17 -07003464status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3465 audio_patch_handle_t *handle)
3466{
3467 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003468
3469 // store new device and send to effects
3470 audio_devices_t type = AUDIO_DEVICE_NONE;
3471 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3472 type |= patch->sinks[i].ext.device.type;
3473 }
3474
3475#ifdef ADD_BATTERY_DATA
3476 // when changing the audio output device, call addBatteryData to notify
3477 // the change
3478 if (mOutDevice != type) {
3479 uint32_t params = 0;
3480 // check whether speaker is on
3481 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3482 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003483 }
3484
Eric Laurent054d9d32015-04-24 08:48:48 -07003485 audio_devices_t deviceWithoutSpeaker
3486 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3487 // check if any other device (except speaker) is on
3488 if (type & deviceWithoutSpeaker) {
3489 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3490 }
3491
3492 if (params != 0) {
3493 addBatteryData(params);
3494 }
3495 }
3496#endif
3497
3498 for (size_t i = 0; i < mEffectChains.size(); i++) {
3499 mEffectChains[i]->setDevice_l(type);
3500 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003501
3502 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3503 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3504 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003505 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003506 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003507
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003508 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003509 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3510 status = hwDevice->createAudioPatch(patch->num_sources,
3511 patch->sources,
3512 patch->num_sinks,
3513 patch->sinks,
3514 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003515 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003516 char *address;
3517 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3518 //FIXME: we only support address on first sink with HAL version < 3.0
3519 address = audio_device_address_to_parameter(
3520 patch->sinks[0].ext.device.type,
3521 patch->sinks[0].ext.device.address);
3522 } else {
3523 address = (char *)calloc(1, 1);
3524 }
3525 AudioParameter param = AudioParameter(String8(address));
3526 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003527 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003528 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003529 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003530 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003531 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003532 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003533 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3534 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003535 return status;
3536}
3537
Eric Laurent054d9d32015-04-24 08:48:48 -07003538status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3539{
Andy Hungf60abce2016-08-26 11:37:54 -07003540 status_t status;
3541 if (property_get_bool("af.patch_park", false /* default_value */)) {
3542 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3543 // or if HAL does not properly lock against access.
3544 AutoPark<FastMixer> park(mFastMixer);
3545 status = PlaybackThread::releaseAudioPatch_l(handle);
3546 } else {
3547 status = PlaybackThread::releaseAudioPatch_l(handle);
3548 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003549 return status;
3550}
3551
Eric Laurent1c333e22014-05-20 10:48:17 -07003552status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3553{
3554 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003555
3556 mOutDevice = AUDIO_DEVICE_NONE;
3557
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003558 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003559 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3560 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003561 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003562 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003563 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003564 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003565 }
3566 return status;
3567}
3568
Eric Laurent83b88082014-06-20 18:31:16 -07003569void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3570{
3571 Mutex::Autolock _l(mLock);
3572 mTracks.add(track);
3573}
3574
3575void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3576{
3577 Mutex::Autolock _l(mLock);
3578 destroyTrack_l(track);
3579}
3580
3581void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3582{
3583 ThreadBase::getAudioPortConfig(config);
3584 config->role = AUDIO_PORT_ROLE_SOURCE;
3585 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3586 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3587}
3588
Eric Laurent81784c32012-11-19 14:55:58 -08003589// ----------------------------------------------------------------------------
3590
3591AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003592 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3593 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // mAudioMixer below
3595 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003596 mFastMixerFutex(0),
3597 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003598 // mOutputSink below
3599 // mPipeSink below
3600 // mNormalSink below
3601{
3602 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003603 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3604 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003605 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3606 mNormalFrameCount);
3607 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3608
Andy Hungfbfc3952015-01-15 13:33:51 -08003609 if (type == DUPLICATING) {
3610 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3611 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3612 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3613 return;
3614 }
Eric Laurent81784c32012-11-19 14:55:58 -08003615 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003616 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003617 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003618 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003619#if !LOG_NDEBUG
3620 ssize_t index =
3621#else
3622 (void)
3623#endif
3624 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003625 ALOG_ASSERT(index == 0);
3626
3627 // initialize fast mixer depending on configuration
3628 bool initFastMixer;
3629 switch (kUseFastMixer) {
3630 case FastMixer_Never:
3631 initFastMixer = false;
3632 break;
3633 case FastMixer_Always:
3634 initFastMixer = true;
3635 break;
3636 case FastMixer_Static:
3637 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003638 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3639 // where the period is less than an experimentally determined threshold that can be
3640 // scheduled reliably with CFS. However, the BT A2DP HAL is
3641 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3642 initFastMixer = mFrameCount < mNormalFrameCount
3643 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003644 break;
3645 }
Andy Hungfda69402017-02-15 14:33:12 -08003646 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3647 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3648 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003649 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003650 audio_format_t fastMixerFormat;
3651 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3652 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3653 } else {
3654 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3655 }
3656 if (mFormat != fastMixerFormat) {
3657 // change our Sink format to accept our intermediate precision
3658 mFormat = fastMixerFormat;
3659 free(mSinkBuffer);
3660 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3661 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3662 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3663 }
Eric Laurent81784c32012-11-19 14:55:58 -08003664
3665 // create a MonoPipe to connect our submix to FastMixer
3666 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003667#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003668 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003669#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003670 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003671 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003672 format.mFormat = fastMixerFormat;
3673 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3674
Eric Laurent81784c32012-11-19 14:55:58 -08003675 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3676 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3677 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3678 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3679 const NBAIO_Format offers[1] = {format};
3680 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003681#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003682 ssize_t index =
3683#else
3684 (void)
3685#endif
3686 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003687 ALOG_ASSERT(index == 0);
3688 monoPipe->setAvgFrames((mScreenState & 1) ?
3689 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3690 mPipeSink = monoPipe;
3691
Glenn Kasten46909e72013-02-26 09:20:22 -08003692#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003693 if (mTeeSinkOutputEnabled) {
3694 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003695 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3696 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003697 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003698 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003699 ALOG_ASSERT(index == 0);
3700 mTeeSink = teeSink;
3701 PipeReader *teeSource = new PipeReader(*teeSink);
3702 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003703 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003704 ALOG_ASSERT(index == 0);
3705 mTeeSource = teeSource;
3706 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003707#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003708
3709 // create fast mixer and configure it initially with just one fast track for our submix
3710 mFastMixer = new FastMixer();
3711 FastMixerStateQueue *sq = mFastMixer->sq();
3712#ifdef STATE_QUEUE_DUMP
3713 sq->setObserverDump(&mStateQueueObserverDump);
3714 sq->setMutatorDump(&mStateQueueMutatorDump);
3715#endif
3716 FastMixerState *state = sq->begin();
3717 FastTrack *fastTrack = &state->mFastTracks[0];
3718 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3719 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3720 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003721 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3722 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003723 fastTrack->mGeneration++;
3724 state->mFastTracksGen++;
3725 state->mTrackMask = 1;
3726 // fast mixer will use the HAL output sink
3727 state->mOutputSink = mOutputSink.get();
3728 state->mOutputSinkGen++;
3729 state->mFrameCount = mFrameCount;
3730 state->mCommand = FastMixerState::COLD_IDLE;
3731 // already done in constructor initialization list
3732 //mFastMixerFutex = 0;
3733 state->mColdFutexAddr = &mFastMixerFutex;
3734 state->mColdGen++;
3735 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003736#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003737 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003738#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003739 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3740 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003741 sq->end();
3742 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3743
3744 // start the fast mixer
3745 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3746 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003747 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003748 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003749
3750#ifdef AUDIO_WATCHDOG
3751 // create and start the watchdog
3752 mAudioWatchdog = new AudioWatchdog();
3753 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3754 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3755 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003756 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003757#endif
3758
Eric Laurent81784c32012-11-19 14:55:58 -08003759 }
3760
3761 switch (kUseFastMixer) {
3762 case FastMixer_Never:
3763 case FastMixer_Dynamic:
3764 mNormalSink = mOutputSink;
3765 break;
3766 case FastMixer_Always:
3767 mNormalSink = mPipeSink;
3768 break;
3769 case FastMixer_Static:
3770 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3771 break;
3772 }
3773}
3774
3775AudioFlinger::MixerThread::~MixerThread()
3776{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003777 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003778 FastMixerStateQueue *sq = mFastMixer->sq();
3779 FastMixerState *state = sq->begin();
3780 if (state->mCommand == FastMixerState::COLD_IDLE) {
3781 int32_t old = android_atomic_inc(&mFastMixerFutex);
3782 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003783 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003784 }
3785 }
3786 state->mCommand = FastMixerState::EXIT;
3787 sq->end();
3788 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3789 mFastMixer->join();
3790 // Though the fast mixer thread has exited, it's state queue is still valid.
3791 // We'll use that extract the final state which contains one remaining fast track
3792 // corresponding to our sub-mix.
3793 state = sq->begin();
3794 ALOG_ASSERT(state->mTrackMask == 1);
3795 FastTrack *fastTrack = &state->mFastTracks[0];
3796 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3797 delete fastTrack->mBufferProvider;
3798 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003799 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003800#ifdef AUDIO_WATCHDOG
3801 if (mAudioWatchdog != 0) {
3802 mAudioWatchdog->requestExit();
3803 mAudioWatchdog->requestExitAndWait();
3804 mAudioWatchdog.clear();
3805 }
3806#endif
3807 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003808 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003809 delete mAudioMixer;
3810}
3811
3812
3813uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3814{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003815 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003816 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3817 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3818 }
3819 return latency;
3820}
3821
3822
3823void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3824{
3825 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3826}
3827
Eric Laurentbfb1b832013-01-07 09:53:42 -08003828ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003829{
3830 // FIXME we should only do one push per cycle; confirm this is true
3831 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003832 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003833 FastMixerStateQueue *sq = mFastMixer->sq();
3834 FastMixerState *state = sq->begin();
3835 if (state->mCommand != FastMixerState::MIX_WRITE &&
3836 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3837 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003838
3839 // FIXME workaround for first HAL write being CPU bound on some devices
3840 ATRACE_BEGIN("write");
3841 mOutput->write((char *)mSinkBuffer, 0);
3842 ATRACE_END();
3843
Eric Laurent81784c32012-11-19 14:55:58 -08003844 int32_t old = android_atomic_inc(&mFastMixerFutex);
3845 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003846 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003847 }
3848#ifdef AUDIO_WATCHDOG
3849 if (mAudioWatchdog != 0) {
3850 mAudioWatchdog->resume();
3851 }
3852#endif
3853 }
3854 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003855#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003856 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003857 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003858#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003859 sq->end();
3860 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3861 if (kUseFastMixer == FastMixer_Dynamic) {
3862 mNormalSink = mPipeSink;
3863 }
3864 } else {
3865 sq->end(false /*didModify*/);
3866 }
3867 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003868 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003869}
3870
3871void AudioFlinger::MixerThread::threadLoop_standby()
3872{
3873 // Idle the fast mixer if it's currently running
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::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003878 // Report any frames trapped in the Monopipe
3879 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3880 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3881 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3882 "monoPipeWritten:%lld monoPipeLeft:%lld",
3883 (long long)mFramesWritten, (long long)mSuspendedFrames,
3884 (long long)mPipeSink->framesWritten(), pipeFrames);
3885 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3886
Eric Laurent81784c32012-11-19 14:55:58 -08003887 state->mCommand = FastMixerState::COLD_IDLE;
3888 state->mColdFutexAddr = &mFastMixerFutex;
3889 state->mColdGen++;
3890 mFastMixerFutex = 0;
3891 sq->end();
3892 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3893 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3894 if (kUseFastMixer == FastMixer_Dynamic) {
3895 mNormalSink = mOutputSink;
3896 }
3897#ifdef AUDIO_WATCHDOG
3898 if (mAudioWatchdog != 0) {
3899 mAudioWatchdog->pause();
3900 }
3901#endif
3902 } else {
3903 sq->end(false /*didModify*/);
3904 }
3905 }
3906 PlaybackThread::threadLoop_standby();
3907}
3908
Eric Laurentbfb1b832013-01-07 09:53:42 -08003909bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3910{
3911 return false;
3912}
3913
3914bool AudioFlinger::PlaybackThread::shouldStandby_l()
3915{
3916 return !mStandby;
3917}
3918
3919bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3920{
3921 Mutex::Autolock _l(mLock);
3922 return waitingAsyncCallback_l();
3923}
3924
Eric Laurent81784c32012-11-19 14:55:58 -08003925// shared by MIXER and DIRECT, overridden by DUPLICATING
3926void AudioFlinger::PlaybackThread::threadLoop_standby()
3927{
3928 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003929 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003931 // discard any pending drain or write ack by incrementing sequence
3932 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3933 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003934 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003935 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3936 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003937 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003938 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003939}
3940
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003941void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3942{
3943 ALOGV("signal playback thread");
3944 broadcast_l();
3945}
3946
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003947void AudioFlinger::PlaybackThread::onAsyncError()
3948{
3949 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3950 invalidateTracks((audio_stream_type_t)i);
3951 }
3952}
3953
Eric Laurent81784c32012-11-19 14:55:58 -08003954void AudioFlinger::MixerThread::threadLoop_mix()
3955{
Eric Laurent81784c32012-11-19 14:55:58 -08003956 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003957 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003958 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003959 // increase sleep time progressively when application underrun condition clears.
3960 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3961 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3962 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003963 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003964 sleepTimeShift--;
3965 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003966 mSleepTimeUs = 0;
3967 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003968 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003969
Eric Laurent81784c32012-11-19 14:55:58 -08003970}
3971
3972void AudioFlinger::MixerThread::threadLoop_sleepTime()
3973{
3974 // If no tracks are ready, sleep once for the duration of an output
3975 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003976 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003977 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003978 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3979 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3980 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003981 }
3982 // reduce sleep time in case of consecutive application underruns to avoid
3983 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3984 // duration we would end up writing less data than needed by the audio HAL if
3985 // the condition persists.
3986 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3987 sleepTimeShift++;
3988 }
3989 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003990 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003991 }
3992 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003993 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3994 // before effects processing or output.
3995 if (mMixerBufferValid) {
3996 memset(mMixerBuffer, 0, mMixerBufferSize);
3997 } else {
3998 memset(mSinkBuffer, 0, mSinkBufferSize);
3999 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004000 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004001 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4002 "anticipated start");
4003 }
4004 // TODO add standby time extension fct of effect tail
4005}
4006
4007// prepareTracks_l() must be called with ThreadBase::mLock held
4008AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4009 Vector< sp<Track> > *tracksToRemove)
4010{
4011
4012 mixer_state mixerStatus = MIXER_IDLE;
4013 // find out which tracks need to be processed
4014 size_t count = mActiveTracks.size();
4015 size_t mixedTracks = 0;
4016 size_t tracksWithEffect = 0;
4017 // counts only _active_ fast tracks
4018 size_t fastTracks = 0;
4019 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4020
4021 float masterVolume = mMasterVolume;
4022 bool masterMute = mMasterMute;
4023
4024 if (masterMute) {
4025 masterVolume = 0;
4026 }
4027 // Delegate master volume control to effect in output mix effect chain if needed
4028 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4029 if (chain != 0) {
4030 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4031 chain->setVolume_l(&v, &v);
4032 masterVolume = (float)((v + (1 << 23)) >> 24);
4033 chain.clear();
4034 }
4035
4036 // prepare a new state to push
4037 FastMixerStateQueue *sq = NULL;
4038 FastMixerState *state = NULL;
4039 bool didModify = false;
4040 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004041 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004042 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004043 sq = mFastMixer->sq();
4044 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004045 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004046 }
4047
Andy Hung69aed5f2014-02-25 17:24:40 -08004048 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004049 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004050
Eric Laurent81784c32012-11-19 14:55:58 -08004051 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004052 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004053
4054 // this const just means the local variable doesn't change
4055 Track* const track = t.get();
4056
4057 // process fast tracks
4058 if (track->isFastTrack()) {
4059
4060 // It's theoretically possible (though unlikely) for a fast track to be created
4061 // and then removed within the same normal mix cycle. This is not a problem, as
4062 // the track never becomes active so it's fast mixer slot is never touched.
4063 // The converse, of removing an (active) track and then creating a new track
4064 // at the identical fast mixer slot within the same normal mix cycle,
4065 // is impossible because the slot isn't marked available until the end of each cycle.
4066 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004067 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004068 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4069 FastTrack *fastTrack = &state->mFastTracks[j];
4070
4071 // Determine whether the track is currently in underrun condition,
4072 // and whether it had a recent underrun.
4073 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4074 FastTrackUnderruns underruns = ftDump->mUnderruns;
4075 uint32_t recentFull = (underruns.mBitFields.mFull -
4076 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4077 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4078 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4079 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4080 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4081 uint32_t recentUnderruns = recentPartial + recentEmpty;
4082 track->mObservedUnderruns = underruns;
4083 // don't count underruns that occur while stopping or pausing
4084 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004085 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4086 recentUnderruns > 0) {
4087 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4088 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004089 } else {
4090 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004091 }
4092
4093 // This is similar to the state machine for normal tracks,
4094 // with a few modifications for fast tracks.
4095 bool isActive = true;
4096 switch (track->mState) {
4097 case TrackBase::STOPPING_1:
4098 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004099 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004100 track->mState = TrackBase::STOPPING_2;
4101 }
4102 break;
4103 case TrackBase::PAUSING:
4104 // ramp down is not yet implemented
4105 track->setPaused();
4106 break;
4107 case TrackBase::RESUMING:
4108 // ramp up is not yet implemented
4109 track->mState = TrackBase::ACTIVE;
4110 break;
4111 case TrackBase::ACTIVE:
4112 if (recentFull > 0 || recentPartial > 0) {
4113 // track has provided at least some frames recently: reset retry count
4114 track->mRetryCount = kMaxTrackRetries;
4115 }
4116 if (recentUnderruns == 0) {
4117 // no recent underruns: stay active
4118 break;
4119 }
4120 // there has recently been an underrun of some kind
4121 if (track->sharedBuffer() == 0) {
4122 // were any of the recent underruns "empty" (no frames available)?
4123 if (recentEmpty == 0) {
4124 // no, then ignore the partial underruns as they are allowed indefinitely
4125 break;
4126 }
4127 // there has recently been an "empty" underrun: decrement the retry counter
4128 if (--(track->mRetryCount) > 0) {
4129 break;
4130 }
4131 // indicate to client process that the track was disabled because of underrun;
4132 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004133 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004134 // remove from active list, but state remains ACTIVE [confusing but true]
4135 isActive = false;
4136 break;
4137 }
4138 // fall through
4139 case TrackBase::STOPPING_2:
4140 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004141 case TrackBase::STOPPED:
4142 case TrackBase::FLUSHED: // flush() while active
4143 // Check for presentation complete if track is inactive
4144 // We have consumed all the buffers of this track.
4145 // This would be incomplete if we auto-paused on underrun
4146 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004147 uint32_t latency = 0;
4148 status_t result = mOutput->stream->getLatency(&latency);
4149 ALOGE_IF(result != OK,
4150 "Error when retrieving output stream latency: %d", result);
4151 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004152 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004153 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4154 // track stays in active list until presentation is complete
4155 break;
4156 }
4157 }
4158 if (track->isStopping_2()) {
4159 track->mState = TrackBase::STOPPED;
4160 }
4161 if (track->isStopped()) {
4162 // Can't reset directly, as fast mixer is still polling this track
4163 // track->reset();
4164 // So instead mark this track as needing to be reset after push with ack
4165 resetMask |= 1 << i;
4166 }
4167 isActive = false;
4168 break;
4169 case TrackBase::IDLE:
4170 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004171 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004172 }
4173
4174 if (isActive) {
4175 // was it previously inactive?
4176 if (!(state->mTrackMask & (1 << j))) {
4177 ExtendedAudioBufferProvider *eabp = track;
4178 VolumeProvider *vp = track;
4179 fastTrack->mBufferProvider = eabp;
4180 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004181 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004182 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004183 fastTrack->mGeneration++;
4184 state->mTrackMask |= 1 << j;
4185 didModify = true;
4186 // no acknowledgement required for newly active tracks
4187 }
4188 // cache the combined master volume and stream type volume for fast mixer; this
4189 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004190 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004191 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004192 track->mCachedVolume = masterVolume
4193 * mStreamTypes[track->streamType()].volume
4194 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004195 ++fastTracks;
4196 } else {
4197 // was it previously active?
4198 if (state->mTrackMask & (1 << j)) {
4199 fastTrack->mBufferProvider = NULL;
4200 fastTrack->mGeneration++;
4201 state->mTrackMask &= ~(1 << j);
4202 didModify = true;
4203 // If any fast tracks were removed, we must wait for acknowledgement
4204 // because we're about to decrement the last sp<> on those tracks.
4205 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4206 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004207 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4208 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4209 j, track->mState, state->mTrackMask, recentUnderruns,
4210 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004211 }
4212 tracksToRemove->add(track);
4213 // Avoids a misleading display in dumpsys
4214 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4215 }
4216 continue;
4217 }
4218
4219 { // local variable scope to avoid goto warning
4220
4221 audio_track_cblk_t* cblk = track->cblk();
4222
4223 // The first time a track is added we wait
4224 // for all its buffers to be filled before processing it
4225 int name = track->name();
4226 // make sure that we have enough frames to mix one full buffer.
4227 // enforce this condition only once to enable draining the buffer in case the client
4228 // app does not call stop() and relies on underrun to stop:
4229 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4230 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004231 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004232 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004233 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004234
4235 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004236 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004237 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4238 // add frames already consumed but not yet released by the resampler
4239 // because mAudioTrackServerProxy->framesReady() will include these frames
4240 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4241
Eric Laurent81784c32012-11-19 14:55:58 -08004242 uint32_t minFrames = 1;
4243 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4244 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004245 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004246 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004247
4248 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004249 if (ATRACE_ENABLED()) {
4250 // I wish we had formatted trace names
4251 char traceName[16];
4252 strcpy(traceName, "nRdy");
4253 int name = track->name();
4254 if (AudioMixer::TRACK0 <= name &&
4255 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4256 name -= AudioMixer::TRACK0;
4257 traceName[4] = (name / 10) + '0';
4258 traceName[5] = (name % 10) + '0';
4259 } else {
4260 traceName[4] = '?';
4261 traceName[5] = '?';
4262 }
4263 traceName[6] = '\0';
4264 ATRACE_INT(traceName, framesReady);
4265 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004266 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004267 !track->isPaused() && !track->isTerminated())
4268 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004269 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004270
4271 mixedTracks++;
4272
Andy Hung69aed5f2014-02-25 17:24:40 -08004273 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4274 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004275 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004276 if (track->mainBuffer() != mSinkBuffer &&
4277 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004278 if (mEffectBufferEnabled) {
4279 mEffectBufferValid = true; // Later can set directly.
4280 }
Eric Laurent81784c32012-11-19 14:55:58 -08004281 chain = getEffectChain_l(track->sessionId());
4282 // Delegate volume control to effect in track effect chain if needed
4283 if (chain != 0) {
4284 tracksWithEffect++;
4285 } else {
4286 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4287 "session %d",
4288 name, track->sessionId());
4289 }
4290 }
4291
4292
4293 int param = AudioMixer::VOLUME;
4294 if (track->mFillingUpStatus == Track::FS_FILLED) {
4295 // no ramp for the first volume setting
4296 track->mFillingUpStatus = Track::FS_ACTIVE;
4297 if (track->mState == TrackBase::RESUMING) {
4298 track->mState = TrackBase::ACTIVE;
4299 param = AudioMixer::RAMP_VOLUME;
4300 }
4301 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004302 // FIXME should not make a decision based on mServer
4303 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004304 // If the track is stopped before the first frame was mixed,
4305 // do not apply ramp
4306 param = AudioMixer::RAMP_VOLUME;
4307 }
4308
4309 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004310 uint32_t vl, vr; // in U8.24 integer format
4311 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004312 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004313 vl = vr = 0;
4314 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004315 if (track->isPausing()) {
4316 track->setPaused();
4317 }
4318 } else {
4319
4320 // read original volumes with volume control
4321 float typeVolume = mStreamTypes[track->streamType()].volume;
4322 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004323 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004324 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004325 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4326 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004327 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004328 if (vlf > GAIN_FLOAT_UNITY) {
4329 ALOGV("Track left volume out of range: %.3g", vlf);
4330 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004331 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004332 if (vrf > GAIN_FLOAT_UNITY) {
4333 ALOGV("Track right volume out of range: %.3g", vrf);
4334 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004335 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004336 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004337 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004338 // now apply the master volume and stream type volume and shaper volume
4339 vlf *= v * vh;
4340 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004341 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004342 // then derive vl and vr as U8.24 versions for the effect chain
4343 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4344 vl = (uint32_t) (scaleto8_24 * vlf);
4345 vr = (uint32_t) (scaleto8_24 * vrf);
4346 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004347 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004348 // send level comes from shared memory and so may be corrupt
4349 if (sendLevel > MAX_GAIN_INT) {
4350 ALOGV("Track send level out of range: %04X", sendLevel);
4351 sendLevel = MAX_GAIN_INT;
4352 }
Andy Hung6be49402014-05-30 10:42:03 -07004353 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4354 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004355 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356
Eric Laurent81784c32012-11-19 14:55:58 -08004357 // Delegate volume control to effect in track effect chain if needed
4358 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4359 // Do not ramp volume if volume is controlled by effect
4360 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004361 // Update remaining floating point volume levels
4362 vlf = (float)vl / (1 << 24);
4363 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004364 track->mHasVolumeController = true;
4365 } else {
4366 // force no volume ramp when volume controller was just disabled or removed
4367 // from effect chain to avoid volume spike
4368 if (track->mHasVolumeController) {
4369 param = AudioMixer::VOLUME;
4370 }
4371 track->mHasVolumeController = false;
4372 }
4373
Eric Laurent81784c32012-11-19 14:55:58 -08004374 // XXX: these things DON'T need to be done each time
4375 mAudioMixer->setBufferProvider(name, track);
4376 mAudioMixer->enable(name);
4377
Andy Hung6be49402014-05-30 10:42:03 -07004378 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4379 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4380 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004381 mAudioMixer->setParameter(
4382 name,
4383 AudioMixer::TRACK,
4384 AudioMixer::FORMAT, (void *)track->format());
4385 mAudioMixer->setParameter(
4386 name,
4387 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004388 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004389 mAudioMixer->setParameter(
4390 name,
4391 AudioMixer::TRACK,
4392 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004393 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004394 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004395 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004396 if (reqSampleRate == 0) {
4397 reqSampleRate = mSampleRate;
4398 } else if (reqSampleRate > maxSampleRate) {
4399 reqSampleRate = maxSampleRate;
4400 }
Eric Laurent81784c32012-11-19 14:55:58 -08004401 mAudioMixer->setParameter(
4402 name,
4403 AudioMixer::RESAMPLE,
4404 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004405 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004406
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004407 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004408 mAudioMixer->setParameter(
4409 name,
4410 AudioMixer::TIMESTRETCH,
4411 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004412 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004413
Andy Hung69aed5f2014-02-25 17:24:40 -08004414 /*
4415 * Select the appropriate output buffer for the track.
4416 *
Andy Hung98ef9782014-03-04 14:46:50 -08004417 * Tracks with effects go into their own effects chain buffer
4418 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004419 *
4420 * Other tracks can use mMixerBuffer for higher precision
4421 * channel accumulation. If this buffer is enabled
4422 * (mMixerBufferEnabled true), then selected tracks will accumulate
4423 * into it.
4424 *
4425 */
4426 if (mMixerBufferEnabled
4427 && (track->mainBuffer() == mSinkBuffer
4428 || track->mainBuffer() == mMixerBuffer)) {
4429 mAudioMixer->setParameter(
4430 name,
4431 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004432 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004433 mAudioMixer->setParameter(
4434 name,
4435 AudioMixer::TRACK,
4436 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4437 // TODO: override track->mainBuffer()?
4438 mMixerBufferValid = true;
4439 } else {
4440 mAudioMixer->setParameter(
4441 name,
4442 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004443 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004444 mAudioMixer->setParameter(
4445 name,
4446 AudioMixer::TRACK,
4447 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4448 }
Eric Laurent81784c32012-11-19 14:55:58 -08004449 mAudioMixer->setParameter(
4450 name,
4451 AudioMixer::TRACK,
4452 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4453
4454 // reset retry count
4455 track->mRetryCount = kMaxTrackRetries;
4456
4457 // If one track is ready, set the mixer ready if:
4458 // - the mixer was not ready during previous round OR
4459 // - no other track is not ready
4460 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4461 mixerStatus != MIXER_TRACKS_ENABLED) {
4462 mixerStatus = MIXER_TRACKS_READY;
4463 }
4464 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004465 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004466 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4467 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004468 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004469 } else {
4470 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004471 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004472
Eric Laurent81784c32012-11-19 14:55:58 -08004473 // clear effect chain input buffer if an active track underruns to avoid sending
4474 // previous audio buffer again to effects
4475 chain = getEffectChain_l(track->sessionId());
4476 if (chain != 0) {
4477 chain->clearInputBuffer();
4478 }
4479
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004480 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004481 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4482 track->isStopped() || track->isPaused()) {
4483 // We have consumed all the buffers of this track.
4484 // Remove it from the list of active tracks.
4485 // TODO: use actual buffer filling status instead of latency when available from
4486 // audio HAL
4487 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004488 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004489 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4490 if (track->isStopped()) {
4491 track->reset();
4492 }
4493 tracksToRemove->add(track);
4494 }
4495 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004496 // No buffers for this track. Give it a few chances to
4497 // fill a buffer, then remove it from active list.
4498 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004499 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004500 tracksToRemove->add(track);
4501 // indicate to client process that the track was disabled because of underrun;
4502 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004503 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004504 // If one track is not ready, mark the mixer also not ready if:
4505 // - the mixer was ready during previous round OR
4506 // - no other track is ready
4507 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4508 mixerStatus != MIXER_TRACKS_READY) {
4509 mixerStatus = MIXER_TRACKS_ENABLED;
4510 }
4511 }
4512 mAudioMixer->disable(name);
4513 }
4514
4515 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004516
4517 }
4518
4519 // Push the new FastMixer state if necessary
4520 bool pauseAudioWatchdog = false;
4521 if (didModify) {
4522 state->mFastTracksGen++;
4523 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4524 if (kUseFastMixer == FastMixer_Dynamic &&
4525 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4526 state->mCommand = FastMixerState::COLD_IDLE;
4527 state->mColdFutexAddr = &mFastMixerFutex;
4528 state->mColdGen++;
4529 mFastMixerFutex = 0;
4530 if (kUseFastMixer == FastMixer_Dynamic) {
4531 mNormalSink = mOutputSink;
4532 }
4533 // If we go into cold idle, need to wait for acknowledgement
4534 // so that fast mixer stops doing I/O.
4535 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4536 pauseAudioWatchdog = true;
4537 }
Eric Laurent81784c32012-11-19 14:55:58 -08004538 }
4539 if (sq != NULL) {
4540 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004541 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4542 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4543 // when bringing the output sink into standby.)
4544 //
4545 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4546 //
4547 // This occurs with BT suspend when we idle the FastMixer with
4548 // active tracks, which may be added or removed.
4549 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004550 }
4551#ifdef AUDIO_WATCHDOG
4552 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4553 mAudioWatchdog->pause();
4554 }
4555#endif
4556
4557 // Now perform the deferred reset on fast tracks that have stopped
4558 while (resetMask != 0) {
4559 size_t i = __builtin_ctz(resetMask);
4560 ALOG_ASSERT(i < count);
4561 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004562 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004563 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4564 track->reset();
4565 }
4566
4567 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004568 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004569
Eric Laurent97d547d2014-09-02 14:45:53 -07004570 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4571 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004572 }
4573
4574 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004575 // as long as there are effects we should clear the effects buffer, to avoid
4576 // passing a non-clean buffer to the effect chain
4577 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004578 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004579 // sink or mix buffer must be cleared if all tracks are connected to an
4580 // effect chain as in this case the mixer will not write to the sink or mix buffer
4581 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004582 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4583 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004584 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004585 if (mMixerBufferValid) {
4586 memset(mMixerBuffer, 0, mMixerBufferSize);
4587 // TODO: In testing, mSinkBuffer below need not be cleared because
4588 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4589 // after mixing.
4590 //
4591 // To enforce this guarantee:
4592 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4593 // (mixedTracks == 0 && fastTracks > 0))
4594 // must imply MIXER_TRACKS_READY.
4595 // Later, we may clear buffers regardless, and skip much of this logic.
4596 }
Andy Hung98ef9782014-03-04 14:46:50 -08004597 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004598 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004599 }
4600
4601 // if any fast tracks, then status is ready
4602 mMixerStatusIgnoringFastTracks = mixerStatus;
4603 if (fastTracks > 0) {
4604 mixerStatus = MIXER_TRACKS_READY;
4605 }
4606 return mixerStatus;
4607}
4608
Eric Laurentad7dd962016-09-22 12:38:37 -07004609// trackCountForUid_l() must be called with ThreadBase::mLock held
4610uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4611{
4612 uint32_t trackCount = 0;
4613 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004614 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004615 trackCount++;
4616 }
4617 }
4618 return trackCount;
4619}
4620
Eric Laurent81784c32012-11-19 14:55:58 -08004621// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004622int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004623 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004624{
Eric Laurentad7dd962016-09-22 12:38:37 -07004625 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4626 return -1;
4627 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004628 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004629}
4630
4631// deleteTrackName_l() must be called with ThreadBase::mLock held
4632void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4633{
4634 ALOGV("remove track (%d) and delete from mixer", name);
4635 mAudioMixer->deleteTrackName(name);
4636}
4637
Eric Laurent10351942014-05-08 18:49:52 -07004638// checkForNewParameter_l() must be called with ThreadBase::mLock held
4639bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4640 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004641{
Eric Laurent81784c32012-11-19 14:55:58 -08004642 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004643 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004644
Eric Laurent10351942014-05-08 18:49:52 -07004645 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004646
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004647 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004648
Eric Laurent10351942014-05-08 18:49:52 -07004649 AudioParameter param = AudioParameter(keyValuePair);
4650 int value;
4651 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4652 reconfig = true;
4653 }
4654 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004655 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004656 status = BAD_VALUE;
4657 } else {
4658 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004659 reconfig = true;
4660 }
Eric Laurent10351942014-05-08 18:49:52 -07004661 }
4662 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004663 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004664 status = BAD_VALUE;
4665 } else {
4666 // no need to save value, since it's constant
4667 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004668 }
Eric Laurent10351942014-05-08 18:49:52 -07004669 }
4670 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4671 // do not accept frame count changes if tracks are open as the track buffer
4672 // size depends on frame count and correct behavior would not be guaranteed
4673 // if frame count is changed after track creation
4674 if (!mTracks.isEmpty()) {
4675 status = INVALID_OPERATION;
4676 } else {
4677 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004678 }
Eric Laurent10351942014-05-08 18:49:52 -07004679 }
4680 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004681#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004682 // when changing the audio output device, call addBatteryData to notify
4683 // the change
4684 if (mOutDevice != value) {
4685 uint32_t params = 0;
4686 // check whether speaker is on
4687 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4688 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004689 }
Eric Laurent10351942014-05-08 18:49:52 -07004690
4691 audio_devices_t deviceWithoutSpeaker
4692 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4693 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004694 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004695 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4696 }
4697
4698 if (params != 0) {
4699 addBatteryData(params);
4700 }
4701 }
Eric Laurent81784c32012-11-19 14:55:58 -08004702#endif
4703
Eric Laurent10351942014-05-08 18:49:52 -07004704 // forward device change to effects that have requested to be
4705 // aware of attached audio device.
4706 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004707 a2dpDeviceChanged =
4708 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004709 mOutDevice = value;
4710 for (size_t i = 0; i < mEffectChains.size(); i++) {
4711 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004712 }
4713 }
Eric Laurent10351942014-05-08 18:49:52 -07004714 }
Eric Laurent81784c32012-11-19 14:55:58 -08004715
Eric Laurent10351942014-05-08 18:49:52 -07004716 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004717 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004718 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004719 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004720 mStandby = true;
4721 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004722 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004723 }
Eric Laurent10351942014-05-08 18:49:52 -07004724 if (status == NO_ERROR && reconfig) {
4725 readOutputParameters_l();
4726 delete mAudioMixer;
4727 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4728 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004729 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004730 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004731 if (name < 0) {
4732 break;
4733 }
4734 mTracks[i]->mName = name;
4735 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004736 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004737 }
Eric Laurent81784c32012-11-19 14:55:58 -08004738 }
4739
Eric Laurent42537be2016-01-08 17:16:42 -08004740 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004741}
4742
4743
4744void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4745{
Eric Laurent81784c32012-11-19 14:55:58 -08004746 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004747 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004748 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004749 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004750
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004751 if (hasFastMixer()) {
4752 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4753
4754 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4755 // while we are dumping it. It may be inconsistent, but it won't mutate!
4756 // This is a large object so we place it on the heap.
4757 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4758 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4759 copy->dump(fd);
4760 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004761
4762#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004763 // Similar for state queue
4764 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4765 observerCopy.dump(fd);
4766 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4767 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004768#endif
4769
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004770#ifdef AUDIO_WATCHDOG
4771 if (mAudioWatchdog != 0) {
4772 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4773 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4774 wdCopy.dump(fd);
4775 }
4776#endif
4777
4778 } else {
4779 dprintf(fd, " No FastMixer\n");
4780 }
4781
Glenn Kasten46909e72013-02-26 09:20:22 -08004782#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004783 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004784 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004785#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004786
Eric Laurent81784c32012-11-19 14:55:58 -08004787}
4788
4789uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4790{
4791 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4792}
4793
4794uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4795{
4796 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4797}
4798
4799void AudioFlinger::MixerThread::cacheParameters_l()
4800{
4801 PlaybackThread::cacheParameters_l();
4802
4803 // FIXME: Relaxed timing because of a certain device that can't meet latency
4804 // Should be reduced to 2x after the vendor fixes the driver issue
4805 // increase threshold again due to low power audio mode. The way this warning
4806 // threshold is calculated and its usefulness should be reconsidered anyway.
4807 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4808}
4809
4810// ----------------------------------------------------------------------------
4811
4812AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004813 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4814 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004815 // mLeftVolFloat, mRightVolFloat
4816{
4817}
4818
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4820 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004821 ThreadBase::type_t type, bool systemReady)
4822 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004823 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004824 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004825{
4826}
4827
Eric Laurent81784c32012-11-19 14:55:58 -08004828AudioFlinger::DirectOutputThread::~DirectOutputThread()
4829{
4830}
4831
Eric Laurent5850c4c2016-11-10 13:04:31 -08004832void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004833{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004834 float left, right;
4835
4836 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4837 left = right = 0;
4838 } else {
4839 float typeVolume = mStreamTypes[track->streamType()].volume;
4840 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004841 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004842
Andy Hung10cbff12017-02-21 17:30:14 -08004843 // Get volumeshaper scaling
4844 std::pair<float /* volume */, bool /* active */>
4845 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004846 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004847 v *= vh.first;
4848 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004849
Glenn Kastenc56f3422014-03-21 17:53:17 -07004850 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4851 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4852 if (left > GAIN_FLOAT_UNITY) {
4853 left = GAIN_FLOAT_UNITY;
4854 }
4855 left *= v;
4856 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4857 if (right > GAIN_FLOAT_UNITY) {
4858 right = GAIN_FLOAT_UNITY;
4859 }
4860 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004861 }
4862
4863 if (lastTrack) {
4864 if (left != mLeftVolFloat || right != mRightVolFloat) {
4865 mLeftVolFloat = left;
4866 mRightVolFloat = right;
4867
4868 // Convert volumes from float to 8.24
4869 uint32_t vl = (uint32_t)(left * (1 << 24));
4870 uint32_t vr = (uint32_t)(right * (1 << 24));
4871
4872 // Delegate volume control to effect in track effect chain if needed
4873 // only one effect chain can be present on DirectOutputThread, so if
4874 // there is one, the track is connected to it
4875 if (!mEffectChains.isEmpty()) {
4876 mEffectChains[0]->setVolume_l(&vl, &vr);
4877 left = (float)vl / (1 << 24);
4878 right = (float)vr / (1 << 24);
4879 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004880 status_t result = mOutput->stream->setVolume(left, right);
4881 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004882 }
4883 }
4884}
4885
Phil Burk43b4dcc2015-06-09 16:53:44 -07004886void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4887{
4888 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004889 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004890
Eric Laurent0f0631e2015-07-06 18:01:25 -07004891 if (previousTrack != 0 && latestTrack != 0) {
4892 if (mType == DIRECT) {
4893 if (previousTrack.get() != latestTrack.get()) {
4894 mFlushPending = true;
4895 }
4896 } else /* mType == OFFLOAD */ {
4897 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4898 mFlushPending = true;
4899 }
4900 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004901 }
4902 PlaybackThread::onAddNewTrack_l();
4903}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004904
Eric Laurent81784c32012-11-19 14:55:58 -08004905AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4906 Vector< sp<Track> > *tracksToRemove
4907)
4908{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004909 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004910 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004911 bool doHwPause = false;
4912 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004913
4914 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004915 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004916 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004917 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004918 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004919 continue;
4920 }
4921
Eric Laurent5850c4c2016-11-10 13:04:31 -08004922 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004923#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004924 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004925#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004926 // Only consider last track started for volume and mixer state control.
4927 // In theory an older track could underrun and restart after the new one starts
4928 // but as we only care about the transition phase between two tracks on a
4929 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004930 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004931 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004932
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004933 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004934 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004935 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004936 doHwPause = true;
4937 mHwPaused = true;
4938 }
4939 tracksToRemove->add(track);
4940 } else if (track->isFlushPending()) {
4941 track->flushAck();
4942 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004943 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004944 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004945 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004946 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004947 if (last) {
4948 mLeftVolFloat = mRightVolFloat = -1.0;
4949 if (mHwPaused) {
4950 doHwResume = true;
4951 mHwPaused = false;
4952 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004953 }
4954 }
4955
Eric Laurent81784c32012-11-19 14:55:58 -08004956 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004957 // for all its buffers to be filled before processing it.
4958 // Allow draining the buffer in case the client
4959 // app does not call stop() and relies on underrun to stop:
4960 // hence the test on (track->mRetryCount > 1).
4961 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004962 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004963 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004964 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004965 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004966 minFrames = mNormalFrameCount;
4967 } else {
4968 minFrames = 1;
4969 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004970
Eric Laurentab5cdba2014-06-09 17:22:27 -07004971 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4972 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004973 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004974 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004975
4976 if (track->mFillingUpStatus == Track::FS_FILLED) {
4977 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004978 if (last) {
4979 // make sure processVolume_l() will apply new volume even if 0
4980 mLeftVolFloat = mRightVolFloat = -1.0;
4981 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004982 if (!mHwSupportsPause) {
4983 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004984 }
4985 }
4986
4987 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004988 processVolume_l(track, last);
4989 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004990 sp<Track> previousTrack = mPreviousTrack.promote();
4991 if (previousTrack != 0) {
4992 if (track != previousTrack.get()) {
4993 // Flush any data still being written from last track
4994 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004995 // Invalidate previous track to force a seek when resuming.
4996 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004997 }
4998 }
4999 mPreviousTrack = track;
5000
Eric Laurentd595b7c2013-04-03 17:27:56 -07005001 // reset retry count
5002 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005003 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005004 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005005 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005006 doHwResume = true;
5007 mHwPaused = false;
5008 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005009 }
Eric Laurent81784c32012-11-19 14:55:58 -08005010 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005011 // clear effect chain input buffer if the last active track started underruns
5012 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005013 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005014 mEffectChains[0]->clearInputBuffer();
5015 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005016 if (track->isStopping_1()) {
5017 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005018 if (last && mHwPaused) {
5019 doHwResume = true;
5020 mHwPaused = false;
5021 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005022 }
5023 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5024 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005025 // We have consumed all the buffers of this track.
5026 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005027 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005028 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005029 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5030 } else {
5031 audioHALFrames = 0;
5032 }
5033
Andy Hung818e7a32016-02-16 18:08:07 -08005034 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005035 if (mStandby || !last ||
5036 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005037 if (track->isStopping_2()) {
5038 track->mState = TrackBase::STOPPED;
5039 }
Eric Laurent81784c32012-11-19 14:55:58 -08005040 if (track->isStopped()) {
5041 track->reset();
5042 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005043 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005044 }
5045 } else {
5046 // No buffers for this track. Give it a few chances to
5047 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005048 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005049 if (--(track->mRetryCount) <= 0) {
5050 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005051 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005052 // indicate to client process that the track was disabled because of underrun;
5053 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005054 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005055 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005056 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5057 "minFrames = %u, mFormat = %#x",
5058 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005059 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005060 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005061 doHwPause = true;
5062 mHwPaused = true;
5063 }
Eric Laurent81784c32012-11-19 14:55:58 -08005064 }
5065 }
5066 }
5067 }
5068
Eric Laurentd1f69b02014-12-15 14:33:13 -08005069 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005070 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005071 for (size_t i = 0; i < mTracks.size(); i++) {
5072 if (mTracks[i]->isFlushPending()) {
5073 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005074 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005075 }
5076 }
5077 }
5078
5079 // make sure the pause/flush/resume sequence is executed in the right order.
5080 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5081 // before flush and then resume HW. This can happen in case of pause/flush/resume
5082 // if resume is received before pause is executed.
5083 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005084 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005085 status_t result = mOutput->stream->pause();
5086 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005087 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005088 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005089 flushHw_l();
5090 }
5091 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005092 status_t result = mOutput->stream->resume();
5093 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005094 }
Eric Laurent81784c32012-11-19 14:55:58 -08005095 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005096 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005097
5098 return mixerStatus;
5099}
5100
5101void AudioFlinger::DirectOutputThread::threadLoop_mix()
5102{
Eric Laurent81784c32012-11-19 14:55:58 -08005103 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005104 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005105 // output audio to hardware
5106 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005107 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005108 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005109 status_t status = mActiveTrack->getNextBuffer(&buffer);
5110 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005111 // no need to pad with 0 for compressed audio
5112 if (audio_has_proportional_frames(mFormat)) {
5113 memset(curBuf, 0, frameCount * mFrameSize);
5114 }
Eric Laurent81784c32012-11-19 14:55:58 -08005115 break;
5116 }
5117 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5118 frameCount -= buffer.frameCount;
5119 curBuf += buffer.frameCount * mFrameSize;
5120 mActiveTrack->releaseBuffer(&buffer);
5121 }
Andy Hung2098f272014-02-27 14:00:06 -08005122 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005123 mSleepTimeUs = 0;
5124 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005125 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005126}
5127
5128void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5129{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005130 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005131 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005132 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005133 return;
5134 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005135 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005136 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005137 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005138 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005139 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005140 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005141 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005142 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005143 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005144 }
5145}
5146
Eric Laurentd1f69b02014-12-15 14:33:13 -08005147void AudioFlinger::DirectOutputThread::threadLoop_exit()
5148{
5149 {
5150 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005151 for (size_t i = 0; i < mTracks.size(); i++) {
5152 if (mTracks[i]->isFlushPending()) {
5153 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005154 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005155 }
5156 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005157 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005158 flushHw_l();
5159 }
5160 }
5161 PlaybackThread::threadLoop_exit();
5162}
5163
5164// must be called with thread mutex locked
5165bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5166{
5167 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005168 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005169
vivek mehta9cd7ad12016-03-17 00:18:29 -07005170 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5171 return !mStandby;
5172 }
5173
Eric Laurentd1f69b02014-12-15 14:33:13 -08005174 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5175 // after a timeout and we will enter standby then.
5176 if (mTracks.size() > 0) {
5177 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005178 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5179 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005180 }
5181
Eric Laurent5cff4032015-05-26 13:49:58 -07005182 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005183}
5184
Eric Laurent81784c32012-11-19 14:55:58 -08005185// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005186int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005187 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005188{
Eric Laurentad7dd962016-09-22 12:38:37 -07005189 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5190 return -1;
5191 }
Eric Laurent81784c32012-11-19 14:55:58 -08005192 return 0;
5193}
5194
5195// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005196void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005197{
5198}
5199
Eric Laurent10351942014-05-08 18:49:52 -07005200// checkForNewParameter_l() must be called with ThreadBase::mLock held
5201bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5202 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005203{
5204 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005205 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005206
Eric Laurent10351942014-05-08 18:49:52 -07005207 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005208
Eric Laurent10351942014-05-08 18:49:52 -07005209 AudioParameter param = AudioParameter(keyValuePair);
5210 int value;
5211 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5212 // forward device change to effects that have requested to be
5213 // aware of attached audio device.
5214 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005215 a2dpDeviceChanged =
5216 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005217 mOutDevice = value;
5218 for (size_t i = 0; i < mEffectChains.size(); i++) {
5219 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005220 }
5221 }
Eric Laurent81784c32012-11-19 14:55:58 -08005222 }
Eric Laurent10351942014-05-08 18:49:52 -07005223 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5224 // do not accept frame count changes if tracks are open as the track buffer
5225 // size depends on frame count and correct behavior would not be garantied
5226 // if frame count is changed after track creation
5227 if (!mTracks.isEmpty()) {
5228 status = INVALID_OPERATION;
5229 } else {
5230 reconfig = true;
5231 }
5232 }
5233 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005234 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005235 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005236 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005237 mStandby = true;
5238 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005239 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005240 }
5241 if (status == NO_ERROR && reconfig) {
5242 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005243 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005244 }
5245 }
5246
Eric Laurent42537be2016-01-08 17:16:42 -08005247 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005248}
5249
5250uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5251{
5252 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005253 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005254 time = PlaybackThread::activeSleepTimeUs();
5255 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005256 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005257 }
5258 return time;
5259}
5260
5261uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5262{
5263 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005264 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005265 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5266 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005267 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005268 }
5269 return time;
5270}
5271
5272uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5273{
5274 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005275 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005276 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5277 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005278 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005279 }
5280 return time;
5281}
5282
5283void AudioFlinger::DirectOutputThread::cacheParameters_l()
5284{
5285 PlaybackThread::cacheParameters_l();
5286
5287 // use shorter standby delay as on normal output to release
5288 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005289 // no delay on outputs with HW A/V sync
5290 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005291 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005292 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005293 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005294 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005295 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005296 }
Eric Laurent81784c32012-11-19 14:55:58 -08005297}
5298
Eric Laurente659ef42014-09-29 13:06:46 -07005299void AudioFlinger::DirectOutputThread::flushHw_l()
5300{
Phil Burk062e67a2015-02-11 13:40:50 -08005301 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005302 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005303 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005304}
5305
Andy Hung10cbff12017-02-21 17:30:14 -08005306int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5307 // If a VolumeShaper is active, we must wake up periodically to update volume.
5308 const int64_t NS_PER_MS = 1000000;
5309 return mVolumeShaperActive ?
5310 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5311}
5312
Eric Laurent81784c32012-11-19 14:55:58 -08005313// ----------------------------------------------------------------------------
5314
Eric Laurentbfb1b832013-01-07 09:53:42 -08005315AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005316 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005317 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005318 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005319 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005320 mDrainSequence(0),
5321 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322{
5323}
5324
5325AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5326{
5327}
5328
5329void AudioFlinger::AsyncCallbackThread::onFirstRef()
5330{
5331 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5332}
5333
5334bool AudioFlinger::AsyncCallbackThread::threadLoop()
5335{
5336 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005337 uint32_t writeAckSequence;
5338 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005339 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340
5341 {
5342 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005343 while (!((mWriteAckSequence & 1) ||
5344 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005345 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005346 exitPending())) {
5347 mWaitWorkCV.wait(mLock);
5348 }
5349
Eric Laurentbfb1b832013-01-07 09:53:42 -08005350 if (exitPending()) {
5351 break;
5352 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005353 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5354 mWriteAckSequence, mDrainSequence);
5355 writeAckSequence = mWriteAckSequence;
5356 mWriteAckSequence &= ~1;
5357 drainSequence = mDrainSequence;
5358 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005359 asyncError = mAsyncError;
5360 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361 }
5362 {
Eric Laurent4de95592013-09-26 15:28:21 -07005363 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5364 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005365 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005366 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005367 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005368 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005369 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005370 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005371 if (asyncError) {
5372 playbackThread->onAsyncError();
5373 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005374 }
5375 }
5376 }
5377 return false;
5378}
5379
5380void AudioFlinger::AsyncCallbackThread::exit()
5381{
5382 ALOGV("AsyncCallbackThread::exit");
5383 Mutex::Autolock _l(mLock);
5384 requestExit();
5385 mWaitWorkCV.broadcast();
5386}
5387
Eric Laurent3b4529e2013-09-05 18:09:19 -07005388void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005389{
5390 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005391 // bit 0 is cleared
5392 mWriteAckSequence = sequence << 1;
5393}
5394
5395void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5396{
5397 Mutex::Autolock _l(mLock);
5398 // ignore unexpected callbacks
5399 if (mWriteAckSequence & 2) {
5400 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005401 mWaitWorkCV.signal();
5402 }
5403}
5404
Eric Laurent3b4529e2013-09-05 18:09:19 -07005405void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406{
5407 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005408 // bit 0 is cleared
5409 mDrainSequence = sequence << 1;
5410}
5411
5412void AudioFlinger::AsyncCallbackThread::resetDraining()
5413{
5414 Mutex::Autolock _l(mLock);
5415 // ignore unexpected callbacks
5416 if (mDrainSequence & 2) {
5417 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005418 mWaitWorkCV.signal();
5419 }
5420}
5421
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005422void AudioFlinger::AsyncCallbackThread::setAsyncError()
5423{
5424 Mutex::Autolock _l(mLock);
5425 mAsyncError = true;
5426 mWaitWorkCV.signal();
5427}
5428
Eric Laurentbfb1b832013-01-07 09:53:42 -08005429
5430// ----------------------------------------------------------------------------
5431AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005432 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5433 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005434 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5435 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436{
Eric Laurentfd477972013-10-25 18:10:40 -07005437 //FIXME: mStandby should be set to true by ThreadBase constructor
5438 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005439 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005440}
5441
Eric Laurentbfb1b832013-01-07 09:53:42 -08005442void AudioFlinger::OffloadThread::threadLoop_exit()
5443{
5444 if (mFlushPending || mHwPaused) {
5445 // If a flush is pending or track was paused, just discard buffered data
5446 flushHw_l();
5447 } else {
5448 mMixerStatus = MIXER_DRAIN_ALL;
5449 threadLoop_drain();
5450 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005451 if (mUseAsyncWrite) {
5452 ALOG_ASSERT(mCallbackThread != 0);
5453 mCallbackThread->exit();
5454 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005455 PlaybackThread::threadLoop_exit();
5456}
5457
5458AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5459 Vector< sp<Track> > *tracksToRemove
5460)
5461{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005462 size_t count = mActiveTracks.size();
5463
5464 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005465 bool doHwPause = false;
5466 bool doHwResume = false;
5467
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005468 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005469
Eric Laurentbfb1b832013-01-07 09:53:42 -08005470 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005471 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005472 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005473#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005474 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005475#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005476 // Only consider last track started for volume and mixer state control.
5477 // In theory an older track could underrun and restart after the new one starts
5478 // but as we only care about the transition phase between two tracks on a
5479 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005480 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005481 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005482
Haynes Mathew George7844f672014-01-15 12:32:55 -08005483 if (track->isInvalid()) {
5484 ALOGW("An invalidated track shouldn't be in active list");
5485 tracksToRemove->add(track);
5486 continue;
5487 }
5488
5489 if (track->mState == TrackBase::IDLE) {
5490 ALOGW("An idle track shouldn't be in active list");
5491 continue;
5492 }
5493
Eric Laurentbfb1b832013-01-07 09:53:42 -08005494 if (track->isPausing()) {
5495 track->setPaused();
5496 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005497 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005498 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005499 mHwPaused = true;
5500 }
5501 // If we were part way through writing the mixbuffer to
5502 // the HAL we must save this until we resume
5503 // BUG - this will be wrong if a different track is made active,
5504 // in that case we want to discard the pending data in the
5505 // mixbuffer and tell the client to present it again when the
5506 // track is resumed
5507 mPausedWriteLength = mCurrentWriteLength;
5508 mPausedBytesRemaining = mBytesRemaining;
5509 mBytesRemaining = 0; // stop writing
5510 }
5511 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005512 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005513 if (track->isStopping_1()) {
5514 track->mRetryCount = kMaxTrackStopRetriesOffload;
5515 } else {
5516 track->mRetryCount = kMaxTrackRetriesOffload;
5517 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005518 track->flushAck();
5519 if (last) {
5520 mFlushPending = true;
5521 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005522 } else if (track->isResumePending()){
5523 track->resumeAck();
5524 if (last) {
5525 if (mPausedBytesRemaining) {
5526 // Need to continue write that was interrupted
5527 mCurrentWriteLength = mPausedWriteLength;
5528 mBytesRemaining = mPausedBytesRemaining;
5529 mPausedBytesRemaining = 0;
5530 }
5531 if (mHwPaused) {
5532 doHwResume = true;
5533 mHwPaused = false;
5534 // threadLoop_mix() will handle the case that we need to
5535 // resume an interrupted write
5536 }
5537 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005538 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005539
Eric Laurent3df841a2016-07-15 15:15:40 -07005540 mLeftVolFloat = mRightVolFloat = -1.0;
5541
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005542 // Do not handle new data in this iteration even if track->framesReady()
5543 mixerStatus = MIXER_TRACKS_ENABLED;
5544 }
5545 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005546 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005547 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005548 if (track->mFillingUpStatus == Track::FS_FILLED) {
5549 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005550 if (last) {
5551 // make sure processVolume_l() will apply new volume even if 0
5552 mLeftVolFloat = mRightVolFloat = -1.0;
5553 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005554 }
5555
5556 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005557 sp<Track> previousTrack = mPreviousTrack.promote();
5558 if (previousTrack != 0) {
5559 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005560 // Flush any data still being written from last track
5561 mBytesRemaining = 0;
5562 if (mPausedBytesRemaining) {
5563 // Last track was paused so we also need to flush saved
5564 // mixbuffer state and invalidate track so that it will
5565 // re-submit that unwritten data when it is next resumed
5566 mPausedBytesRemaining = 0;
5567 // Invalidate is a bit drastic - would be more efficient
5568 // to have a flag to tell client that some of the
5569 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005570 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005571 }
5572 // flush data already sent to the DSP if changing audio session as audio
5573 // comes from a different source. Also invalidate previous track to force a
5574 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005575 if (previousTrack->sessionId() != track->sessionId()) {
5576 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005577 }
5578 }
5579 }
5580 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005582 if (track->isStopping_1()) {
5583 track->mRetryCount = kMaxTrackStopRetriesOffload;
5584 } else {
5585 track->mRetryCount = kMaxTrackRetriesOffload;
5586 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005587 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005588 mixerStatus = MIXER_TRACKS_READY;
5589 }
5590 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005591 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005592 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005593 if (--(track->mRetryCount) <= 0) {
5594 // Hardware buffer can hold a large amount of audio so we must
5595 // wait for all current track's data to drain before we say
5596 // that the track is stopped.
5597 if (mBytesRemaining == 0) {
5598 // Only start draining when all data in mixbuffer
5599 // has been written
5600 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5601 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5602 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5603 if (last && !mStandby) {
5604 // do not modify drain sequence if we are already draining. This happens
5605 // when resuming from pause after drain.
5606 if ((mDrainSequence & 1) == 0) {
5607 mSleepTimeUs = 0;
5608 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5609 mixerStatus = MIXER_DRAIN_TRACK;
5610 mDrainSequence += 2;
5611 }
5612 if (mHwPaused) {
5613 // It is possible to move from PAUSED to STOPPING_1 without
5614 // a resume so we must ensure hardware is running
5615 doHwResume = true;
5616 mHwPaused = false;
5617 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005618 }
5619 }
Eric Laurente93cc032016-05-05 10:15:10 -07005620 } else if (last) {
5621 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5622 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005623 }
5624 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005625 // Drain has completed or we are in standby, signal presentation complete
5626 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005627 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005628 uint32_t latency = 0;
5629 status_t result = mOutput->stream->getLatency(&latency);
5630 ALOGE_IF(result != OK,
5631 "Error when retrieving output stream latency: %d", result);
5632 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005633 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005634 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005635 track->presentationComplete(framesWritten, audioHALFrames);
5636 track->reset();
5637 tracksToRemove->add(track);
5638 }
5639 } else {
5640 // No buffers for this track. Give it a few chances to
5641 // fill a buffer, then remove it from active list.
5642 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005643 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005644 uint64_t position = 0;
5645 struct timespec unused;
5646 // The running check restarts the retry counter at least once.
5647 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5648 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5649 running = true;
5650 mOffloadUnderrunPosition = position;
5651 }
5652 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005653 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5654 (long long)position, (long long)mOffloadUnderrunPosition);
5655 }
5656 if (running) { // still running, give us more time.
5657 track->mRetryCount = kMaxTrackRetriesOffload;
5658 } else {
5659 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5660 track->name());
5661 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005662 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005663 // it will then automatically call start() when data is available
5664 track->disable();
5665 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005666 } else if (last){
5667 mixerStatus = MIXER_TRACKS_ENABLED;
5668 }
5669 }
5670 }
5671 // compute volume for this track
5672 processVolume_l(track, last);
5673 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005674
Eric Laurentea0fade2013-10-04 16:23:48 -07005675 // make sure the pause/flush/resume sequence is executed in the right order.
5676 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5677 // before flush and then resume HW. This can happen in case of pause/flush/resume
5678 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005679 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005680 status_t result = mOutput->stream->pause();
5681 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005682 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005683 if (mFlushPending) {
5684 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005685 }
Eric Laurentfd477972013-10-25 18:10:40 -07005686 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005687 status_t result = mOutput->stream->resume();
5688 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005689 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005690
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691 // remove all the tracks that need to be...
5692 removeTracks_l(*tracksToRemove);
5693
5694 return mixerStatus;
5695}
5696
Eric Laurentbfb1b832013-01-07 09:53:42 -08005697// must be called with thread mutex locked
5698bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5699{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005700 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5701 mWriteAckSequence, mDrainSequence);
5702 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703 return true;
5704 }
5705 return false;
5706}
5707
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5709{
5710 Mutex::Autolock _l(mLock);
5711 return waitingAsyncCallback_l();
5712}
5713
5714void AudioFlinger::OffloadThread::flushHw_l()
5715{
Eric Laurente659ef42014-09-29 13:06:46 -07005716 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005717 // Flush anything still waiting in the mixbuffer
5718 mCurrentWriteLength = 0;
5719 mBytesRemaining = 0;
5720 mPausedWriteLength = 0;
5721 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005722 // reset bytes written count to reflect that DSP buffers are empty after flush.
5723 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005724 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005725
Eric Laurentbfb1b832013-01-07 09:53:42 -08005726 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005727 // discard any pending drain or write ack by incrementing sequence
5728 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5729 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005730 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005731 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5732 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005733 }
5734}
5735
Haynes Mathew George05317d22016-05-03 16:34:26 -07005736void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5737{
5738 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005739 if (PlaybackThread::invalidateTracks_l(streamType)) {
5740 mFlushPending = true;
5741 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005742}
5743
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744// ----------------------------------------------------------------------------
5745
Eric Laurent81784c32012-11-19 14:55:58 -08005746AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005747 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005748 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005749 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005750 mWaitTimeMs(UINT_MAX)
5751{
5752 addOutputTrack(mainThread);
5753}
5754
5755AudioFlinger::DuplicatingThread::~DuplicatingThread()
5756{
5757 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5758 mOutputTracks[i]->destroy();
5759 }
5760}
5761
5762void AudioFlinger::DuplicatingThread::threadLoop_mix()
5763{
5764 // mix buffers...
5765 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005766 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005767 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005768 if (mMixerBufferValid) {
5769 memset(mMixerBuffer, 0, mMixerBufferSize);
5770 } else {
5771 memset(mSinkBuffer, 0, mSinkBufferSize);
5772 }
Eric Laurent81784c32012-11-19 14:55:58 -08005773 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005774 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005775 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005776 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005777 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005778}
5779
5780void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5781{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005782 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005783 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005784 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005785 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005786 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005787 }
5788 } else if (mBytesWritten != 0) {
5789 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5790 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005791 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005792 } else {
5793 // flush remaining overflow buffers in output tracks
5794 writeFrames = 0;
5795 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005796 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
5798}
5799
Eric Laurentbfb1b832013-01-07 09:53:42 -08005800ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005801{
5802 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005803 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005804 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005805 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005806 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005807}
5808
5809void AudioFlinger::DuplicatingThread::threadLoop_standby()
5810{
5811 // DuplicatingThread implements standby by stopping all tracks
5812 for (size_t i = 0; i < outputTracks.size(); i++) {
5813 outputTracks[i]->stop();
5814 }
5815}
5816
5817void AudioFlinger::DuplicatingThread::saveOutputTracks()
5818{
5819 outputTracks = mOutputTracks;
5820}
5821
5822void AudioFlinger::DuplicatingThread::clearOutputTracks()
5823{
5824 outputTracks.clear();
5825}
5826
5827void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5828{
5829 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005830 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5831 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5832 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5833 const size_t frameCount =
5834 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5835 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5836 // from different OutputTracks and their associated MixerThreads (e.g. one may
5837 // nearly empty and the other may be dropping data).
5838
5839 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005840 this,
5841 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005842 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005843 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005844 frameCount,
5845 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005846 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5847 if (status != NO_ERROR) {
5848 ALOGE("addOutputTrack() initCheck failed %d", status);
5849 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005850 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005851 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5852 mOutputTracks.add(outputTrack);
5853 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5854 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005855}
5856
5857void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5858{
5859 Mutex::Autolock _l(mLock);
5860 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5861 if (mOutputTracks[i]->thread() == thread) {
5862 mOutputTracks[i]->destroy();
5863 mOutputTracks.removeAt(i);
5864 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005865 if (thread->getOutput() == mOutput) {
5866 mOutput = NULL;
5867 }
Eric Laurent81784c32012-11-19 14:55:58 -08005868 return;
5869 }
5870 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005871 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005872}
5873
5874// caller must hold mLock
5875void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5876{
5877 mWaitTimeMs = UINT_MAX;
5878 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5879 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5880 if (strong != 0) {
5881 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5882 if (waitTimeMs < mWaitTimeMs) {
5883 mWaitTimeMs = waitTimeMs;
5884 }
5885 }
5886 }
5887}
5888
5889
5890bool AudioFlinger::DuplicatingThread::outputsReady(
5891 const SortedVector< sp<OutputTrack> > &outputTracks)
5892{
5893 for (size_t i = 0; i < outputTracks.size(); i++) {
5894 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5895 if (thread == 0) {
5896 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5897 outputTracks[i].get());
5898 return false;
5899 }
5900 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5901 // see note at standby() declaration
5902 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5903 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5904 thread.get());
5905 return false;
5906 }
5907 }
5908 return true;
5909}
5910
5911uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5912{
5913 return (mWaitTimeMs * 1000) / 2;
5914}
5915
5916void AudioFlinger::DuplicatingThread::cacheParameters_l()
5917{
5918 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5919 updateWaitTime_l();
5920
5921 MixerThread::cacheParameters_l();
5922}
5923
Eric Laurent6acd1d42017-01-04 14:23:29 -08005924
Eric Laurent81784c32012-11-19 14:55:58 -08005925// ----------------------------------------------------------------------------
5926// Record
5927// ----------------------------------------------------------------------------
5928
5929AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5930 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005931 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005932 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005933 audio_devices_t inDevice,
5934 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005935#ifdef TEE_SINK
5936 , const sp<NBAIO_Sink>& teeSink
5937#endif
5938 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005939 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07005940 mInput(input),
5941 mActiveTracks(&this->mLocalLog),
5942 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005943 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005944 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005945#ifdef TEE_SINK
5946 , mTeeSink(teeSink)
5947#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005948 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5949 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005950 // mFastCapture below
5951 , mFastCaptureFutex(0)
5952 // mInputSource
5953 // mPipeSink
5954 // mPipeSource
5955 , mPipeFramesP2(0)
5956 // mPipeMemory
5957 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005958 , mFastTrackAvail(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005959{
Glenn Kastend7dca052015-03-05 16:05:54 -08005960 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5961 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005962
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005963 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005964
5965 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005966 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005967 size_t numCounterOffers = 0;
5968 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005969#if !LOG_NDEBUG
5970 ssize_t index =
5971#else
5972 (void)
5973#endif
5974 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005975 ALOG_ASSERT(index == 0);
5976
5977 // initialize fast capture depending on configuration
5978 bool initFastCapture;
5979 switch (kUseFastCapture) {
5980 case FastCapture_Never:
5981 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005982 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005983 break;
5984 case FastCapture_Always:
5985 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005986 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005987 break;
5988 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005989 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005990 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
5991 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
5992 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005993 break;
5994 // case FastCapture_Dynamic:
5995 }
5996
5997 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005998 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005999 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006000 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6001 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006002 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006003 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006004 const sp<MemoryDealer> roHeap(readOnlyHeap());
6005 sp<IMemory> pipeMemory;
6006 if ((roHeap == 0) ||
6007 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006008 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6009 ALOGE("not enough memory for pipe buffer size=%zu; "
6010 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6011 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6012 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006013 goto failed;
6014 }
6015 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6016 memset(pipeBuffer, 0, pipeSize);
6017 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6018 const NBAIO_Format offers[1] = {format};
6019 size_t numCounterOffers = 0;
6020 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6021 ALOG_ASSERT(index == 0);
6022 mPipeSink = pipe;
6023 PipeReader *pipeReader = new PipeReader(*pipe);
6024 numCounterOffers = 0;
6025 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6026 ALOG_ASSERT(index == 0);
6027 mPipeSource = pipeReader;
6028 mPipeFramesP2 = pipeFramesP2;
6029 mPipeMemory = pipeMemory;
6030
6031 // create fast capture
6032 mFastCapture = new FastCapture();
6033 FastCaptureStateQueue *sq = mFastCapture->sq();
6034#ifdef STATE_QUEUE_DUMP
6035 // FIXME
6036#endif
6037 FastCaptureState *state = sq->begin();
6038 state->mCblk = NULL;
6039 state->mInputSource = mInputSource.get();
6040 state->mInputSourceGen++;
6041 state->mPipeSink = pipe;
6042 state->mPipeSinkGen++;
6043 state->mFrameCount = mFrameCount;
6044 state->mCommand = FastCaptureState::COLD_IDLE;
6045 // already done in constructor initialization list
6046 //mFastCaptureFutex = 0;
6047 state->mColdFutexAddr = &mFastCaptureFutex;
6048 state->mColdGen++;
6049 state->mDumpState = &mFastCaptureDumpState;
6050#ifdef TEE_SINK
6051 // FIXME
6052#endif
6053 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6054 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6055 sq->end();
6056 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6057
6058 // start the fast capture
6059 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6060 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006061 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006062 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006063#ifdef AUDIO_WATCHDOG
6064 // FIXME
6065#endif
6066
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006067 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006068 }
6069failed: ;
6070
6071 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006072}
6073
Eric Laurent81784c32012-11-19 14:55:58 -08006074AudioFlinger::RecordThread::~RecordThread()
6075{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006076 if (mFastCapture != 0) {
6077 FastCaptureStateQueue *sq = mFastCapture->sq();
6078 FastCaptureState *state = sq->begin();
6079 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6080 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6081 if (old == -1) {
6082 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6083 }
6084 }
6085 state->mCommand = FastCaptureState::EXIT;
6086 sq->end();
6087 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6088 mFastCapture->join();
6089 mFastCapture.clear();
6090 }
6091 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006092 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006093 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006094}
6095
6096void AudioFlinger::RecordThread::onFirstRef()
6097{
Glenn Kastend7dca052015-03-05 16:05:54 -08006098 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006099}
6100
Eric Laurent555530a2017-02-07 18:17:24 -08006101void AudioFlinger::RecordThread::preExit()
6102{
6103 ALOGV(" preExit()");
6104 Mutex::Autolock _l(mLock);
6105 for (size_t i = 0; i < mTracks.size(); i++) {
6106 sp<RecordTrack> track = mTracks[i];
6107 track->invalidate();
6108 }
6109 mActiveTracks.clear();
6110 mStartStopCond.broadcast();
6111}
6112
Eric Laurent81784c32012-11-19 14:55:58 -08006113bool AudioFlinger::RecordThread::threadLoop()
6114{
Eric Laurent81784c32012-11-19 14:55:58 -08006115 nsecs_t lastWarning = 0;
6116
6117 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006118
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006119reacquire_wakelock:
6120 sp<RecordTrack> activeTrack;
6121 {
6122 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006123 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006124 }
6125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006126 // used to request a deferred sleep, to be executed later while mutex is unlocked
6127 uint32_t sleepUs = 0;
6128
6129 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006130 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006131 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006132
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006133 // activeTracks accumulates a copy of a subset of mActiveTracks
6134 Vector< sp<RecordTrack> > activeTracks;
6135
Glenn Kasten735f45f2014-08-18 15:51:59 -07006136 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006137 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006138
Glenn Kasten735f45f2014-08-18 15:51:59 -07006139 // reference to a fast track which is about to be removed
6140 sp<RecordTrack> fastTrackToRemove;
6141
Eric Laurent81784c32012-11-19 14:55:58 -08006142 { // scope for mLock
6143 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006144
Eric Laurent021cf962014-05-13 10:18:14 -07006145 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006146
Eric Laurent000a4192014-01-29 15:17:32 -08006147 // check exitPending here because checkForNewParameters_l() and
6148 // checkForNewParameters_l() can temporarily release mLock
6149 if (exitPending()) {
6150 break;
6151 }
6152
Eric Laurent5c25d562016-07-13 17:17:45 -07006153 // sleep with mutex unlocked
6154 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006155 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006156 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6157 ATRACE_END();
6158 sleepUs = 0;
6159 continue;
6160 }
6161
Glenn Kasten2b806402013-11-20 16:37:38 -08006162 // if no active track(s), then standby and release wakelock
6163 size_t size = mActiveTracks.size();
6164 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006165 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006166 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006167 releaseWakeLock_l();
6168 ALOGV("RecordThread: loop stopping");
6169 // go to sleep
6170 mWaitWorkCV.wait(mLock);
6171 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006172 goto reacquire_wakelock;
6173 }
6174
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006175 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006176 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006177 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006178
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006179 activeTrack = mActiveTracks[i];
6180 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006181 if (activeTrack->isFastTrack()) {
6182 ALOG_ASSERT(fastTrackToRemove == 0);
6183 fastTrackToRemove = activeTrack;
6184 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006186 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006187 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006188 continue;
6189 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006190
6191 TrackBase::track_state activeTrackState = activeTrack->mState;
6192 switch (activeTrackState) {
6193
6194 case TrackBase::PAUSING:
6195 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006196 doBroadcast = true;
6197 size--;
6198 continue;
6199
6200 case TrackBase::STARTING_1:
6201 sleepUs = 10000;
6202 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006203 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006204 continue;
6205
6206 case TrackBase::STARTING_2:
6207 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006208 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006209 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006210 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006211 break;
6212
6213 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006214 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006215 break;
6216
6217 case TrackBase::IDLE:
6218 i++;
6219 continue;
6220
6221 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006222 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006223 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006224
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006225 activeTracks.add(activeTrack);
6226 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006227
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006228 if (activeTrack->isFastTrack()) {
6229 ALOG_ASSERT(!mFastTrackAvail);
6230 ALOG_ASSERT(fastTrack == 0);
6231 fastTrack = activeTrack;
6232 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006233 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006234
Andy Hungdae27702016-10-31 14:01:16 -07006235 mActiveTracks.updatePowerState(this);
6236
Eric Laurent5c25d562016-07-13 17:17:45 -07006237 if (allStopped) {
6238 standbyIfNotAlreadyInStandby();
6239 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006240 if (doBroadcast) {
6241 mStartStopCond.broadcast();
6242 }
6243
6244 // sleep if there are no active tracks to process
6245 if (activeTracks.size() == 0) {
6246 if (sleepUs == 0) {
6247 sleepUs = kRecordThreadSleepUs;
6248 }
6249 continue;
6250 }
6251 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006252
Eric Laurent81784c32012-11-19 14:55:58 -08006253 lockEffectChains_l(effectChains);
6254 }
6255
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006256 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006257
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006258 size_t size = effectChains.size();
6259 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006260 // thread mutex is not locked, but effect chain is locked
6261 effectChains[i]->process_l();
6262 }
6263
Glenn Kasten735f45f2014-08-18 15:51:59 -07006264 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 if (mFastCapture != 0) {
6266 FastCaptureStateQueue *sq = mFastCapture->sq();
6267 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006268 bool didModify = false;
6269 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006270 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6271 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6272 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6273 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6274 if (old == -1) {
6275 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6276 }
6277 }
6278 state->mCommand = FastCaptureState::READ_WRITE;
6279#if 0 // FIXME
6280 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006281 FastThreadDumpState::kSamplingNforLowRamDevice :
6282 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006283#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006284 didModify = true;
6285 }
6286 audio_track_cblk_t *cblkOld = state->mCblk;
6287 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6288 if (cblkNew != cblkOld) {
6289 state->mCblk = cblkNew;
6290 // block until acked if removing a fast track
6291 if (cblkOld != NULL) {
6292 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6293 }
6294 didModify = true;
6295 }
6296 sq->end(didModify);
6297 if (didModify) {
6298 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006299#if 0
6300 if (kUseFastCapture == FastCapture_Dynamic) {
6301 mNormalSource = mPipeSource;
6302 }
6303#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006304 }
6305 }
6306
Glenn Kasten735f45f2014-08-18 15:51:59 -07006307 // now run the fast track destructor with thread mutex unlocked
6308 fastTrackToRemove.clear();
6309
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006310 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6311 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6312 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6313 // If destination is non-contiguous, first read past the nominal end of buffer, then
6314 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006315
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006316 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006317 ssize_t framesRead;
6318
6319 // If an NBAIO source is present, use it to read the normal capture's data
6320 if (mPipeSource != 0) {
6321 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006322 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006323 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006324 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006325 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6326 // buffer size or at least for 20ms.
6327 size_t sleepFrames = max(
6328 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6329 if (framesRead <= (ssize_t) sleepFrames) {
6330 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6331 }
6332 if (framesRead < 0) {
6333 status_t status = (status_t) framesRead;
6334 switch (status) {
6335 case OVERRUN:
6336 ALOGW("overrun on read from pipe");
6337 framesRead = 0;
6338 break;
6339 case NEGOTIATE:
6340 ALOGE("re-negotiation is needed");
6341 framesRead = -1; // Will cause an attempt to recover.
6342 break;
6343 default:
6344 ALOGE("unknown error %d on read from pipe", status);
6345 break;
6346 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006347 }
6348 // otherwise use the HAL / AudioStreamIn directly
6349 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006350 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006351 size_t bytesRead;
6352 status_t result = mInput->stream->read(
6353 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006354 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006355 if (result < 0) {
6356 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006357 } else {
6358 framesRead = bytesRead / mFrameSize;
6359 }
6360 }
6361
Andy Hung3f0c9022016-01-15 17:49:46 -08006362 // Update server timestamp with server stats
6363 // systemTime() is optional if the hardware supports timestamps.
6364 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6365 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6366
6367 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006368 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006369 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006370 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006371 if (ret == NO_ERROR) {
6372 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6373 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6374 // Note: In general record buffers should tend to be empty in
6375 // a properly running pipeline.
6376 //
6377 // Also, it is not advantageous to call get_presentation_position during the read
6378 // as the read obtains a lock, preventing the timestamp call from executing.
6379 }
6380 }
6381 // Use this to track timestamp information
6382 // ALOGD("%s", mTimestamp.toString().c_str());
6383
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006384 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006385 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006386 // Force input into standby so that it tries to recover at next read attempt
6387 inputStandBy();
6388 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006389 }
6390 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006391 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006392 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006393 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006394
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006395 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006396 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006397 }
6398 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006399 {
6400 size_t part1 = mRsmpInFramesP2 - rear;
6401 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006402 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006403 (framesRead - part1) * mFrameSize);
6404 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006405 }
6406 rear = mRsmpInRear += framesRead;
6407
6408 size = activeTracks.size();
6409 // loop over each active track
6410 for (size_t i = 0; i < size; i++) {
6411 activeTrack = activeTracks[i];
6412
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006413 // skip fast tracks, as those are handled directly by FastCapture
6414 if (activeTrack->isFastTrack()) {
6415 continue;
6416 }
6417
Andy Hung73c02e42015-03-29 01:13:58 -07006418 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006419 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6420
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006421 enum {
6422 OVERRUN_UNKNOWN,
6423 OVERRUN_TRUE,
6424 OVERRUN_FALSE
6425 } overrun = OVERRUN_UNKNOWN;
6426
6427 // loop over getNextBuffer to handle circular sink
6428 for (;;) {
6429
6430 activeTrack->mSink.frameCount = ~0;
6431 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6432 size_t framesOut = activeTrack->mSink.frameCount;
6433 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6434
Andy Hung73c02e42015-03-29 01:13:58 -07006435 // check available frames and handle overrun conditions
6436 // if the record track isn't draining fast enough.
6437 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006439 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6440 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441 overrun = OVERRUN_TRUE;
6442 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006443 if (framesOut == 0 || framesIn == 0) {
6444 break;
6445 }
6446
Andy Hung6770c6f2015-04-07 13:43:36 -07006447 // Don't allow framesOut to be larger than what is possible with resampling
6448 // from framesIn.
6449 // This isn't strictly necessary but helps limit buffer resizing in
6450 // RecordBufferConverter. TODO: remove when no longer needed.
6451 framesOut = min(framesOut,
6452 destinationFramesPossible(
6453 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006454 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6455 framesOut = activeTrack->mRecordBufferConverter->convert(
6456 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006457
6458 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6459 overrun = OVERRUN_FALSE;
6460 }
6461
6462 if (activeTrack->mFramesToDrop == 0) {
6463 if (framesOut > 0) {
6464 activeTrack->mSink.frameCount = framesOut;
6465 activeTrack->releaseBuffer(&activeTrack->mSink);
6466 }
6467 } else {
6468 // FIXME could do a partial drop of framesOut
6469 if (activeTrack->mFramesToDrop > 0) {
6470 activeTrack->mFramesToDrop -= framesOut;
6471 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006472 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006473 }
6474 } else {
6475 activeTrack->mFramesToDrop += framesOut;
6476 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6477 activeTrack->mSyncStartEvent->isCancelled()) {
6478 ALOGW("Synced record %s, session %d, trigger session %d",
6479 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6480 activeTrack->sessionId(),
6481 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006482 activeTrack->mSyncStartEvent->triggerSession() :
6483 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006484 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006485 }
6486 }
6487 }
6488
6489 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006490 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006491 }
6492 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006493
6494 switch (overrun) {
6495 case OVERRUN_TRUE:
6496 // client isn't retrieving buffers fast enough
6497 if (!activeTrack->setOverflow()) {
6498 nsecs_t now = systemTime();
6499 // FIXME should lastWarning per track?
6500 if ((now - lastWarning) > kWarningThrottleNs) {
6501 ALOGW("RecordThread: buffer overflow");
6502 lastWarning = now;
6503 }
6504 }
6505 break;
6506 case OVERRUN_FALSE:
6507 activeTrack->clearOverflow();
6508 break;
6509 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006510 break;
6511 }
6512
Andy Hung3f0c9022016-01-15 17:49:46 -08006513 // update frame information and push timestamp out
6514 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006515 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006516 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6517 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006518 }
6519
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006520unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006521 // enable changes in effect chain
6522 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006523 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006524 }
6525
Glenn Kasten93e471f2013-08-19 08:40:07 -07006526 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006527
6528 {
6529 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006530 for (size_t i = 0; i < mTracks.size(); i++) {
6531 sp<RecordTrack> track = mTracks[i];
6532 track->invalidate();
6533 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006534 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006535 mStartStopCond.broadcast();
6536 }
6537
6538 releaseWakeLock();
6539
6540 ALOGV("RecordThread %p exiting", this);
6541 return false;
6542}
6543
Glenn Kasten93e471f2013-08-19 08:40:07 -07006544void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006545{
6546 if (!mStandby) {
6547 inputStandBy();
6548 mStandby = true;
6549 }
6550}
6551
6552void AudioFlinger::RecordThread::inputStandBy()
6553{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006554 // Idle the fast capture if it's currently running
6555 if (mFastCapture != 0) {
6556 FastCaptureStateQueue *sq = mFastCapture->sq();
6557 FastCaptureState *state = sq->begin();
6558 if (!(state->mCommand & FastCaptureState::IDLE)) {
6559 state->mCommand = FastCaptureState::COLD_IDLE;
6560 state->mColdFutexAddr = &mFastCaptureFutex;
6561 state->mColdGen++;
6562 mFastCaptureFutex = 0;
6563 sq->end();
6564 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6565 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6566#if 0
6567 if (kUseFastCapture == FastCapture_Dynamic) {
6568 // FIXME
6569 }
6570#endif
6571#ifdef AUDIO_WATCHDOG
6572 // FIXME
6573#endif
6574 } else {
6575 sq->end(false /*didModify*/);
6576 }
6577 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006578 status_t result = mInput->stream->standby();
6579 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006580
6581 // If going into standby, flush the pipe source.
6582 if (mPipeSource.get() != nullptr) {
6583 const ssize_t flushed = mPipeSource->flush();
6584 if (flushed > 0) {
6585 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6586 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6587 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6588 }
6589 }
Eric Laurent81784c32012-11-19 14:55:58 -08006590}
6591
Glenn Kasten05997e22014-03-13 15:08:33 -07006592// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006593sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006594 const sp<AudioFlinger::Client>& client,
6595 uint32_t sampleRate,
6596 audio_format_t format,
6597 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006598 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006599 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006600 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006601 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006602 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006603 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006604 status_t *status,
6605 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006606{
Glenn Kasten74935e42013-12-19 08:56:45 -08006607 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006608 sp<RecordTrack> track;
6609 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006610 audio_input_flags_t inputFlags = mInput->flags;
6611
6612 // special case for FAST flag considered OK if fast capture is present
6613 if (hasFastCapture()) {
6614 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6615 }
6616
6617 // Check if requested flags are compatible with output stream flags
6618 if ((*flags & inputFlags) != *flags) {
6619 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6620 " input flags (%08x)",
6621 *flags, inputFlags);
6622 *flags = (audio_input_flags_t)(*flags & inputFlags);
6623 }
Eric Laurent81784c32012-11-19 14:55:58 -08006624
Glenn Kasten90e58b12013-07-31 16:16:02 -07006625 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006626 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006627 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006628 // we formerly checked for a callback handler (non-0 tid),
6629 // but that is no longer required for TRANSFER_OBTAIN mode
6630 //
Glenn Kasten74105912014-07-03 12:28:53 -07006631 // frame count is not specified, or is exactly the pipe depth
6632 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006633 // PCM data
6634 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006635 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006636 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006637 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006638 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006639 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006640 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006641 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006642 hasFastCapture() &&
6643 // there are sufficient fast track slots available
6644 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006645 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006646 // check compatibility with audio effects.
6647 Mutex::Autolock _l(mLock);
6648 // Do not accept FAST flag if the session has software effects
6649 sp<EffectChain> chain = getEffectChain_l(sessionId);
6650 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006651 audio_input_flags_t old = *flags;
6652 chain->checkInputFlagCompatibility(flags);
6653 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006654 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6655 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006656 }
6657 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006658 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006659 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6660 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006661 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006662 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6663 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006664 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006665 this, frameCount, mFrameCount, mPipeFramesP2,
6666 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006667 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006668 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006669 }
6670 }
6671
6672 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006673 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006674 // fast track: frame count is exactly the pipe depth
6675 frameCount = mPipeFramesP2;
6676 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6677 *notificationFrames = mFrameCount;
6678 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006679 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6680 // or 20 ms if there is a fast capture
6681 // TODO This could be a roundupRatio inline, and const
6682 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6683 * sampleRate + mSampleRate - 1) / mSampleRate;
6684 // minimum number of notification periods is at least kMinNotifications,
6685 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6686 static const size_t kMinNotifications = 3;
6687 static const uint32_t kMinMs = 30;
6688 // TODO This could be a roundupRatio inline
6689 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6690 // TODO This could be a roundupRatio inline
6691 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6692 maxNotificationFrames;
6693 const size_t minFrameCount = maxNotificationFrames *
6694 max(kMinNotifications, minNotificationsByMs);
6695 frameCount = max(frameCount, minFrameCount);
6696 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6697 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006698 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006699 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006700 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006701
Glenn Kasten15e57982013-09-24 11:52:37 -07006702 lStatus = initCheck();
6703 if (lStatus != NO_ERROR) {
6704 ALOGE("createRecordTrack_l() audio driver not initialized");
6705 goto Exit;
6706 }
Eric Laurent81784c32012-11-19 14:55:58 -08006707
6708 { // scope for mLock
6709 Mutex::Autolock _l(mLock);
6710
6711 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006712 format, channelMask, frameCount,
6713 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006714 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006715
Glenn Kasten03003332013-08-06 15:40:54 -07006716 lStatus = track->initCheck();
6717 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006718 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006719 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006720 goto Exit;
6721 }
6722 mTracks.add(track);
6723
6724 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
6725 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
6726 mAudioFlinger->btNrecIsOff();
6727 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
6728 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006729
Eric Laurent05067782016-06-01 18:27:28 -07006730 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006731 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6732 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6733 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006734 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006735 }
Eric Laurent81784c32012-11-19 14:55:58 -08006736 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006737
Eric Laurent81784c32012-11-19 14:55:58 -08006738 lStatus = NO_ERROR;
6739
6740Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006741 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006742 return track;
6743}
6744
6745status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6746 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006747 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006748{
6749 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6750 sp<ThreadBase> strongMe = this;
6751 status_t status = NO_ERROR;
6752
6753 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006754 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006755 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006756 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006757 triggerSession,
6758 recordTrack->sessionId(),
6759 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006760 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006761 // Sync event can be cancelled by the trigger session if the track is not in a
6762 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006763 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006764 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006765 } else {
6766 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006767 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006768 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006769 }
6770 }
6771
6772 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006773 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006774 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006775 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6776 if (recordTrack->mState == TrackBase::PAUSING) {
6777 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006778 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006779 } else {
6780 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006781 }
6782 return status;
6783 }
6784
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006785 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6786 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6787 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006788 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006789 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006790 status_t status = NO_ERROR;
6791 if (recordTrack->isExternalTrack()) {
6792 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006793 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006794 mLock.lock();
6795 // FIXME should verify that recordTrack is still in mActiveTracks
6796 if (status != NO_ERROR) {
6797 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006798 recordTrack->clearSyncStartEvent();
6799 ALOGV("RecordThread::start error %d", status);
6800 return status;
6801 }
Eric Laurent81784c32012-11-19 14:55:58 -08006802 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006803 // Catch up with current buffer indices if thread is already running.
6804 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6805 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6806 // see previously buffered data before it called start(), but with greater risk of overrun.
6807
Andy Hung73c02e42015-03-29 01:13:58 -07006808 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006809 // clear any converter state as new data will be discontinuous
6810 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006811 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006812 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006813 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006814 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006815 ALOGV("Record failed to start");
6816 status = BAD_VALUE;
6817 goto startError;
6818 }
Eric Laurent81784c32012-11-19 14:55:58 -08006819 return status;
6820 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006821
Eric Laurent81784c32012-11-19 14:55:58 -08006822startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006823 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006824 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006825 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006826 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006827 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006828 return status;
6829}
6830
Eric Laurent81784c32012-11-19 14:55:58 -08006831void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6832{
6833 sp<SyncEvent> strongEvent = event.promote();
6834
6835 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006836 sp<RefBase> ptr = strongEvent->cookie().promote();
6837 if (ptr != 0) {
6838 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6839 recordTrack->handleSyncStartEvent(strongEvent);
6840 }
Eric Laurent81784c32012-11-19 14:55:58 -08006841 }
6842}
6843
Glenn Kastena8356f62013-07-25 14:37:52 -07006844bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006845 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006846 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006847 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006848 return false;
6849 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006850 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006851 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006852 // signal thread to stop
6853 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006854 // do not wait for mStartStopCond if exiting
6855 if (exitPending()) {
6856 return true;
6857 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006858 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006859 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006860 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006861 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006862 ALOGV("Record stopped OK");
6863 return true;
6864 }
6865 return false;
6866}
6867
Glenn Kasten0f11b512014-01-31 16:18:54 -08006868bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006869{
6870 return false;
6871}
6872
Glenn Kasten0f11b512014-01-31 16:18:54 -08006873status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006874{
6875#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6876 if (!isValidSyncEvent(event)) {
6877 return BAD_VALUE;
6878 }
6879
Glenn Kastend848eb42016-03-08 13:42:11 -08006880 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006881 status_t ret = NAME_NOT_FOUND;
6882
6883 Mutex::Autolock _l(mLock);
6884
6885 for (size_t i = 0; i < mTracks.size(); i++) {
6886 sp<RecordTrack> track = mTracks[i];
6887 if (eventSession == track->sessionId()) {
6888 (void) track->setSyncEvent(event);
6889 ret = NO_ERROR;
6890 }
6891 }
6892 return ret;
6893#else
6894 return BAD_VALUE;
6895#endif
6896}
6897
6898// destroyTrack_l() must be called with ThreadBase::mLock held
6899void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6900{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006901 track->terminate();
6902 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006903 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006904 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006905 removeTrack_l(track);
6906 }
6907}
6908
6909void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6910{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006911 String8 result;
6912 track->appendDump(result, false /* active */);
6913 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
6914
Eric Laurent81784c32012-11-19 14:55:58 -08006915 mTracks.remove(track);
6916 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006917 if (track->isFastTrack()) {
6918 ALOG_ASSERT(!mFastTrackAvail);
6919 mFastTrackAvail = true;
6920 }
Eric Laurent81784c32012-11-19 14:55:58 -08006921}
6922
6923void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6924{
6925 dumpInternals(fd, args);
6926 dumpTracks(fd, args);
6927 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006928 dprintf(fd, " Local log:\n");
6929 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08006930}
6931
6932void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6933{
Glenn Kasten44182c22015-03-05 17:12:23 -08006934 dumpBase(fd, args);
6935
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006936 AudioStreamIn *input = mInput;
6937 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6938 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6939 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006940 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006941 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006942 }
Andy Hungbfa64962017-06-12 14:43:19 -07006943
6944 if (input != nullptr) {
6945 dprintf(fd, " Hal stream dump:\n");
6946 (void)input->stream->dump(fd);
6947 }
6948
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006949 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006950 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006951
Glenn Kasten2f90c512015-12-02 11:40:09 -08006952 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6953 // while we are dumping it. It may be inconsistent, but it won't mutate!
6954 // This is a large object so we place it on the heap.
6955 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6956 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6957 copy->dump(fd);
6958 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006959}
6960
Glenn Kasten0f11b512014-01-31 16:18:54 -08006961void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006962{
Eric Laurent81784c32012-11-19 14:55:58 -08006963 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08006964 size_t numtracks = mTracks.size();
6965 size_t numactive = mActiveTracks.size();
6966 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006967 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006968 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08006969 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006970 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006971 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08006972 RecordTrack::appendDumpHeader(result);
6973 for (size_t i = 0; i < numtracks ; ++i) {
6974 sp<RecordTrack> track = mTracks[i];
6975 if (track != 0) {
6976 bool active = mActiveTracks.indexOf(track) >= 0;
6977 if (active) {
6978 numactiveseen++;
6979 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006980 result.append(prefix);
6981 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08006982 }
Eric Laurent81784c32012-11-19 14:55:58 -08006983 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006984 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006985 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006986 }
6987
Marco Nelissenb2208842014-02-07 14:00:50 -08006988 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006989 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08006990 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006991 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08006992 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006993 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006994 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006995 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006996 result.append(prefix);
6997 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08006998 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006999 }
Eric Laurent81784c32012-11-19 14:55:58 -08007000
7001 }
7002 write(fd, result.string(), result.size());
7003}
7004
Andy Hung73c02e42015-03-29 01:13:58 -07007005
7006void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7007{
7008 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7009 RecordThread *recordThread = (RecordThread *) threadBase.get();
7010 mRsmpInFront = recordThread->mRsmpInRear;
7011 mRsmpInUnrel = 0;
7012}
7013
7014void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7015 size_t *framesAvailable, bool *hasOverrun)
7016{
7017 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7018 RecordThread *recordThread = (RecordThread *) threadBase.get();
7019 const int32_t rear = recordThread->mRsmpInRear;
7020 const int32_t front = mRsmpInFront;
7021 const ssize_t filled = rear - front;
7022
7023 size_t framesIn;
7024 bool overrun = false;
7025 if (filled < 0) {
7026 // should not happen, but treat like a massive overrun and re-sync
7027 framesIn = 0;
7028 mRsmpInFront = rear;
7029 overrun = true;
7030 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7031 framesIn = (size_t) filled;
7032 } else {
7033 // client is not keeping up with server, but give it latest data
7034 framesIn = recordThread->mRsmpInFrames;
7035 mRsmpInFront = /* front = */ rear - framesIn;
7036 overrun = true;
7037 }
7038 if (framesAvailable != NULL) {
7039 *framesAvailable = framesIn;
7040 }
7041 if (hasOverrun != NULL) {
7042 *hasOverrun = overrun;
7043 }
7044}
7045
Eric Laurent81784c32012-11-19 14:55:58 -08007046// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007047status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007048 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007049{
Andy Hung73c02e42015-03-29 01:13:58 -07007050 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007051 if (threadBase == 0) {
7052 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007053 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007054 return NOT_ENOUGH_DATA;
7055 }
7056 RecordThread *recordThread = (RecordThread *) threadBase.get();
7057 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007058 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007059 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007060 // FIXME should not be P2 (don't want to increase latency)
7061 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007062 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007063 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007064 front &= recordThread->mRsmpInFramesP2 - 1;
7065 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007066 if (part1 > (size_t) filled) {
7067 part1 = filled;
7068 }
7069 size_t ask = buffer->frameCount;
7070 ALOG_ASSERT(ask > 0);
7071 if (part1 > ask) {
7072 part1 = ask;
7073 }
7074 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007075 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007076 buffer->raw = NULL;
7077 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007078 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007079 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007080 }
7081
Andy Hung57446612015-04-19 23:56:46 -07007082 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007083 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007084 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007085 return NO_ERROR;
7086}
7087
7088// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007089void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7090 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007091{
Glenn Kasten85948432013-08-19 12:09:05 -07007092 size_t stepCount = buffer->frameCount;
7093 if (stepCount == 0) {
7094 return;
7095 }
Andy Hung73c02e42015-03-29 01:13:58 -07007096 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7097 mRsmpInUnrel -= stepCount;
7098 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007099 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007100 buffer->frameCount = 0;
7101}
7102
Andy Hung97a893e2015-03-29 01:03:07 -07007103
Eric Laurent10351942014-05-08 18:49:52 -07007104bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7105 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007106{
7107 bool reconfig = false;
7108
Eric Laurent10351942014-05-08 18:49:52 -07007109 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007110
Eric Laurent10351942014-05-08 18:49:52 -07007111 audio_format_t reqFormat = mFormat;
7112 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007113 // 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 -07007114 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7115
7116 AudioParameter param = AudioParameter(keyValuePair);
7117 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007118
7119 // scope for AutoPark extends to end of method
7120 AutoPark<FastCapture> park(mFastCapture);
7121
Eric Laurent10351942014-05-08 18:49:52 -07007122 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7123 // channel count change can be requested. Do we mandate the first client defines the
7124 // HAL sampling rate and channel count or do we allow changes on the fly?
7125 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7126 samplingRate = value;
7127 reconfig = true;
7128 }
7129 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007130 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007131 status = BAD_VALUE;
7132 } else {
7133 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007134 reconfig = true;
7135 }
Eric Laurent10351942014-05-08 18:49:52 -07007136 }
7137 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7138 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007139 if (!audio_is_input_channel(mask) ||
7140 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007141 status = BAD_VALUE;
7142 } else {
7143 channelMask = mask;
7144 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007145 }
Eric Laurent10351942014-05-08 18:49:52 -07007146 }
7147 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7148 // do not accept frame count changes if tracks are open as the track buffer
7149 // size depends on frame count and correct behavior would not be guaranteed
7150 // if frame count is changed after track creation
7151 if (mActiveTracks.size() > 0) {
7152 status = INVALID_OPERATION;
7153 } else {
7154 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007155 }
Eric Laurent10351942014-05-08 18:49:52 -07007156 }
7157 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7158 // forward device change to effects that have requested to be
7159 // aware of attached audio device.
7160 for (size_t i = 0; i < mEffectChains.size(); i++) {
7161 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007162 }
Eric Laurent81784c32012-11-19 14:55:58 -08007163
Eric Laurent10351942014-05-08 18:49:52 -07007164 // store input device and output device but do not forward output device to audio HAL.
7165 // Note that status is ignored by the caller for output device
7166 // (see AudioFlinger::setParameters()
7167 if (audio_is_output_devices(value)) {
7168 mOutDevice = value;
7169 status = BAD_VALUE;
7170 } else {
7171 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007172 if (value != AUDIO_DEVICE_NONE) {
7173 mPrevInDevice = value;
7174 }
Eric Laurent10351942014-05-08 18:49:52 -07007175 // disable AEC and NS if the device is a BT SCO headset supporting those
7176 // pre processings
7177 if (mTracks.size() > 0) {
7178 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7179 mAudioFlinger->btNrecIsOff();
7180 for (size_t i = 0; i < mTracks.size(); i++) {
7181 sp<RecordTrack> track = mTracks[i];
7182 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7183 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08007184 }
7185 }
7186 }
Eric Laurent10351942014-05-08 18:49:52 -07007187 }
7188 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7189 mAudioSource != (audio_source_t)value) {
7190 // forward device change to effects that have requested to be
7191 // aware of attached audio device.
7192 for (size_t i = 0; i < mEffectChains.size(); i++) {
7193 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007194 }
Eric Laurent10351942014-05-08 18:49:52 -07007195 mAudioSource = (audio_source_t)value;
7196 }
Glenn Kastene198c362013-08-13 09:13:36 -07007197
Eric Laurent10351942014-05-08 18:49:52 -07007198 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007199 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007200 if (status == INVALID_OPERATION) {
7201 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007202 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007203 }
7204 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007205 if (status == BAD_VALUE) {
7206 uint32_t sRate;
7207 audio_channel_mask_t channelMask;
7208 audio_format_t format;
7209 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7210 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7211 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7212 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7213 status = NO_ERROR;
7214 }
Eric Laurent81784c32012-11-19 14:55:58 -08007215 }
Eric Laurent10351942014-05-08 18:49:52 -07007216 if (status == NO_ERROR) {
7217 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007218 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007219 }
7220 }
Eric Laurent81784c32012-11-19 14:55:58 -08007221 }
Eric Laurent10351942014-05-08 18:49:52 -07007222
Eric Laurent81784c32012-11-19 14:55:58 -08007223 return reconfig;
7224}
7225
7226String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7227{
Eric Laurent81784c32012-11-19 14:55:58 -08007228 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007229 if (initCheck() == NO_ERROR) {
7230 String8 out_s8;
7231 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7232 return out_s8;
7233 }
Eric Laurent81784c32012-11-19 14:55:58 -08007234 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007235 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007236}
7237
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007238void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007239 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7240
7241 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007242
7243 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007244 case AUDIO_INPUT_OPENED:
7245 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007246 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007247 desc->mChannelMask = mChannelMask;
7248 desc->mSamplingRate = mSampleRate;
7249 desc->mFormat = mFormat;
7250 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007251 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007252 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007253 break;
7254
Eric Laurent73e26b62015-04-27 16:55:58 -07007255 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007256 default:
7257 break;
7258 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007259 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007260}
7261
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007262void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007263{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007264 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7265 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007266 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007267 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007268 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007269 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7270 result = mInput->stream->getFrameSize(&mFrameSize);
7271 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7272 result = mInput->stream->getBufferSize(&mBufferSize);
7273 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007274 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007275 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7276 "mBufferSize=%lld, mFrameCount=%lld",
7277 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7278 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007279 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007280 // 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 -07007281 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007282 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007283 // A larger value should allow more old data to be read after a track calls start(),
7284 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007285 //
7286 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007287 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007288 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007289 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007290 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007291
7292 // TODO optimize audio capture buffer sizes ...
7293 // Here we calculate the size of the sliding buffer used as a source
7294 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7295 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7296 // be better to have it derived from the pipe depth in the long term.
7297 // The current value is higher than necessary. However it should not add to latency.
7298
Glenn Kasten85948432013-08-19 12:09:05 -07007299 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007300 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7301 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007302 // if posix_memalign fails, will segv here.
7303 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007304
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007305 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7306 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007307}
7308
Glenn Kasten5f972c02014-01-13 09:59:31 -08007309uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007310{
7311 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007312 uint32_t result;
7313 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7314 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007315 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007316 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007317}
7318
Eric Laurent4c415062016-06-17 16:14:16 -07007319// hasAudioSession_l() must be called with ThreadBase::mLock held
7320uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007321{
Eric Laurent81784c32012-11-19 14:55:58 -08007322 uint32_t result = 0;
7323 if (getEffectChain_l(sessionId) != 0) {
7324 result = EFFECT_SESSION;
7325 }
7326
7327 for (size_t i = 0; i < mTracks.size(); ++i) {
7328 if (sessionId == mTracks[i]->sessionId()) {
7329 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007330 if (mTracks[i]->isFastTrack()) {
7331 result |= FAST_SESSION;
7332 }
Eric Laurent81784c32012-11-19 14:55:58 -08007333 break;
7334 }
7335 }
7336
7337 return result;
7338}
7339
Glenn Kastend848eb42016-03-08 13:42:11 -08007340KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007341{
Glenn Kastend848eb42016-03-08 13:42:11 -08007342 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007343 Mutex::Autolock _l(mLock);
7344 for (size_t j = 0; j < mTracks.size(); ++j) {
7345 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007346 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007347 if (ids.indexOfKey(sessionId) < 0) {
7348 ids.add(sessionId, true);
7349 }
7350 }
7351 return ids;
7352}
7353
7354AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7355{
7356 Mutex::Autolock _l(mLock);
7357 AudioStreamIn *input = mInput;
7358 mInput = NULL;
7359 return input;
7360}
7361
7362// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007363sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007364{
7365 if (mInput == NULL) {
7366 return NULL;
7367 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007368 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007369}
7370
7371status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7372{
7373 // only one chain per input thread
7374 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007375 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007376 return INVALID_OPERATION;
7377 }
7378 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007379 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007380 chain->setInBuffer(NULL);
7381 chain->setOutBuffer(NULL);
7382
7383 checkSuspendOnAddEffectChain_l(chain);
7384
Eric Laurent1b928682014-10-02 19:41:47 -07007385 // make sure enabled pre processing effects state is communicated to the HAL as we
7386 // just moved them to a new input stream.
7387 chain->syncHalEffectsState();
7388
Eric Laurent81784c32012-11-19 14:55:58 -08007389 mEffectChains.add(chain);
7390
7391 return NO_ERROR;
7392}
7393
7394size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7395{
7396 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7397 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007398 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007399 chain.get(), mEffectChains.size(), this);
7400 if (mEffectChains.size() == 1) {
7401 mEffectChains.removeAt(0);
7402 }
7403 return 0;
7404}
7405
Eric Laurent1c333e22014-05-20 10:48:17 -07007406status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7407 audio_patch_handle_t *handle)
7408{
7409 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007410
7411 // store new device and send to effects
7412 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007413 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007414 for (size_t i = 0; i < mEffectChains.size(); i++) {
7415 mEffectChains[i]->setDevice_l(mInDevice);
7416 }
7417
7418 // disable AEC and NS if the device is a BT SCO headset supporting those
7419 // pre processings
7420 if (mTracks.size() > 0) {
7421 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7422 mAudioFlinger->btNrecIsOff();
7423 for (size_t i = 0; i < mTracks.size(); i++) {
7424 sp<RecordTrack> track = mTracks[i];
7425 setEffectSuspended_l(FX_IID_AEC, suspend, track->sessionId());
7426 setEffectSuspended_l(FX_IID_NS, suspend, track->sessionId());
7427 }
7428 }
7429
7430 // store new source and send to effects
7431 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7432 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007433 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007434 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007435 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007436 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007437
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007438 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007439 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7440 status = hwDevice->createAudioPatch(patch->num_sources,
7441 patch->sources,
7442 patch->num_sinks,
7443 patch->sinks,
7444 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007445 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007446 char *address;
7447 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7448 address = audio_device_address_to_parameter(
7449 patch->sources[0].ext.device.type,
7450 patch->sources[0].ext.device.address);
7451 } else {
7452 address = (char *)calloc(1, 1);
7453 }
7454 AudioParameter param = AudioParameter(String8(address));
7455 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007456 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007457 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007458 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007459 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007460 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007461 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007462 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007463
Eric Laurente8726fe2015-06-26 09:39:24 -07007464 if (mInDevice != mPrevInDevice) {
7465 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7466 mPrevInDevice = mInDevice;
7467 }
Eric Laurent296fb132015-05-01 11:38:42 -07007468
Eric Laurent1c333e22014-05-20 10:48:17 -07007469 return status;
7470}
7471
7472status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7473{
7474 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007475
7476 mInDevice = AUDIO_DEVICE_NONE;
7477
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007478 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007479 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7480 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007481 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007482 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007483 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007484 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007485 }
7486 return status;
7487}
7488
Eric Laurent83b88082014-06-20 18:31:16 -07007489void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7490{
7491 Mutex::Autolock _l(mLock);
7492 mTracks.add(record);
7493}
7494
7495void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7496{
7497 Mutex::Autolock _l(mLock);
7498 destroyTrack_l(record);
7499}
7500
7501void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7502{
7503 ThreadBase::getAudioPortConfig(config);
7504 config->role = AUDIO_PORT_ROLE_SINK;
7505 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7506 config->ext.mix.usecase.source = mAudioSource;
7507}
Eric Laurent1c333e22014-05-20 10:48:17 -07007508
Eric Laurent6acd1d42017-01-04 14:23:29 -08007509// ----------------------------------------------------------------------------
7510// Mmap
7511// ----------------------------------------------------------------------------
7512
7513AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7514 : mThread(thread)
7515{
7516}
7517
7518AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7519{
7520 MmapThread *thread = mThread.get();
7521 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007522 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007523 // and the thread removed from mMMapThreads list causing the thread destruction.
7524 mThread.clear();
7525 if (thread != nullptr) {
7526 thread->disconnect();
7527 }
7528}
7529
7530status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7531 struct audio_mmap_buffer_info *info)
7532{
7533 if (mThread == 0) {
7534 return NO_INIT;
7535 }
7536 return mThread->createMmapBuffer(minSizeFrames, info);
7537}
7538
7539status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7540{
7541 if (mThread == 0) {
7542 return NO_INIT;
7543 }
7544 return mThread->getMmapPosition(position);
7545}
7546
Glenn Kastend3bb6452016-12-05 18:14:37 -08007547status_t AudioFlinger::MmapThreadHandle::start(const MmapStreamInterface::Client& client,
7548 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007549
7550{
7551 if (mThread == 0) {
7552 return NO_INIT;
7553 }
7554 return mThread->start(client, handle);
7555}
7556
7557status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7558{
7559 if (mThread == 0) {
7560 return NO_INIT;
7561 }
7562 return mThread->stop(handle);
7563}
7564
Eric Laurent18b57012017-02-13 16:23:52 -08007565status_t AudioFlinger::MmapThreadHandle::standby()
7566{
7567 if (mThread == 0) {
7568 return NO_INIT;
7569 }
7570 return mThread->standby();
7571}
7572
Eric Laurent6acd1d42017-01-04 14:23:29 -08007573
7574AudioFlinger::MmapThread::MmapThread(
7575 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7576 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7577 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7578 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007579 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7580 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007581{
Eric Laurent18b57012017-02-13 16:23:52 -08007582 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007583 readHalParameters_l();
7584}
7585
7586AudioFlinger::MmapThread::~MmapThread()
7587{
Eric Laurent18b57012017-02-13 16:23:52 -08007588 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007589}
7590
7591void AudioFlinger::MmapThread::onFirstRef()
7592{
7593 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7594}
7595
7596void AudioFlinger::MmapThread::disconnect()
7597{
7598 for (const sp<MmapTrack> &t : mActiveTracks) {
7599 stop(t->portId());
7600 }
7601 // this will cause the destruction of this thread.
7602 if (isOutput()) {
7603 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7604 } else {
7605 AudioSystem::releaseInput(mId, mSessionId);
7606 }
7607}
7608
7609
7610void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7611 audio_stream_type_t streamType __unused,
7612 audio_session_t sessionId,
7613 const sp<MmapStreamCallback>& callback,
7614 audio_port_handle_t portId)
7615{
7616 mAttr = *attr;
7617 mSessionId = sessionId;
7618 mCallback = callback;
7619 mPortId = portId;
7620}
7621
7622status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7623 struct audio_mmap_buffer_info *info)
7624{
7625 if (mHalStream == 0) {
7626 return NO_INIT;
7627 }
Eric Laurent18b57012017-02-13 16:23:52 -08007628 mStandby = true;
7629 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007630 return mHalStream->createMmapBuffer(minSizeFrames, info);
7631}
7632
7633status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7634{
7635 if (mHalStream == 0) {
7636 return NO_INIT;
7637 }
7638 return mHalStream->getMmapPosition(position);
7639}
7640
7641status_t AudioFlinger::MmapThread::start(const MmapStreamInterface::Client& client,
7642 audio_port_handle_t *handle)
7643{
Eric Laurent18b57012017-02-13 16:23:52 -08007644 ALOGV("%s clientUid %d mStandby %d", __FUNCTION__, client.clientUid, mStandby);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007645 if (mHalStream == 0) {
7646 return NO_INIT;
7647 }
7648
7649 status_t ret;
7650 audio_session_t sessionId;
7651 audio_port_handle_t portId;
7652
7653 if (mActiveTracks.size() == 0) {
7654 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007655 ret = mHalStream->start();
7656 if (ret != NO_ERROR) {
7657 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7658 return ret;
7659 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007660 portId = mPortId;
7661 sessionId = mSessionId;
Eric Laurent18b57012017-02-13 16:23:52 -08007662 mStandby = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007663 } else {
7664 // for other tracks than first one, get a new port ID from APM.
7665 sessionId = (audio_session_t)mAudioFlinger->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
7666 audio_io_handle_t io;
7667 if (isOutput()) {
7668 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7669 config.sample_rate = mSampleRate;
7670 config.channel_mask = mChannelMask;
7671 config.format = mFormat;
7672 audio_stream_type_t stream = streamType();
7673 audio_output_flags_t flags =
7674 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent9ae8c592017-06-22 17:17:09 -07007675 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007676 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7677 sessionId,
7678 &stream,
7679 client.clientUid,
7680 &config,
7681 flags,
Eric Laurent9ae8c592017-06-22 17:17:09 -07007682 &deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007683 &portId);
7684 } else {
7685 audio_config_base_t config;
7686 config.sample_rate = mSampleRate;
7687 config.channel_mask = mChannelMask;
7688 config.format = mFormat;
Eric Laurent9ae8c592017-06-22 17:17:09 -07007689 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007690 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7691 sessionId,
7692 client.clientPid,
7693 client.clientUid,
7694 &config,
7695 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
Eric Laurent9ae8c592017-06-22 17:17:09 -07007696 &deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007697 &portId);
7698 }
7699 // APM should not chose a different input or output stream for the same set of attributes
7700 // and audo configuration
7701 if (ret != NO_ERROR || io != mId) {
7702 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7703 __FUNCTION__, ret, io, mId);
7704 return BAD_VALUE;
7705 }
7706 }
7707
7708 if (isOutput()) {
7709 ret = AudioSystem::startOutput(mId, streamType(), sessionId);
7710 } else {
7711 ret = AudioSystem::startInput(mId, sessionId);
7712 }
7713
7714 // abort if start is rejected by audio policy manager
7715 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007716 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007717 if (mActiveTracks.size() != 0) {
7718 if (isOutput()) {
7719 AudioSystem::releaseOutput(mId, streamType(), sessionId);
7720 } else {
7721 AudioSystem::releaseInput(mId, sessionId);
7722 }
Eric Laurent18b57012017-02-13 16:23:52 -08007723 } else {
7724 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007725 }
7726 return PERMISSION_DENIED;
7727 }
7728
7729 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, sessionId,
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007730 client.clientUid, client.clientPid,
7731 portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007732
7733 mActiveTracks.add(track);
7734 sp<EffectChain> chain = getEffectChain_l(sessionId);
7735 if (chain != 0) {
7736 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7737 chain->incTrackCnt();
7738 chain->incActiveTrackCnt();
7739 }
7740
7741 *handle = portId;
7742
7743 broadcast_l();
7744
Eric Laurent18b57012017-02-13 16:23:52 -08007745 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, portId, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007746
7747 return NO_ERROR;
7748}
7749
7750status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7751{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007752 ALOGV("%s handle %d", __FUNCTION__, handle);
7753
7754 if (mHalStream == 0) {
7755 return NO_INIT;
7756 }
7757
7758 sp<MmapTrack> track;
7759 for (const sp<MmapTrack> &t : mActiveTracks) {
7760 if (handle == t->portId()) {
7761 track = t;
7762 break;
7763 }
7764 }
7765 if (track == 0) {
7766 return BAD_VALUE;
7767 }
7768
7769 mActiveTracks.remove(track);
7770
7771 if (isOutput()) {
7772 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
7773 if (mActiveTracks.size() != 0) {
7774 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
7775 }
7776 } else {
7777 AudioSystem::stopInput(mId, track->sessionId());
7778 if (mActiveTracks.size() != 0) {
7779 AudioSystem::releaseInput(mId, track->sessionId());
7780 }
7781 }
7782
7783 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7784 if (chain != 0) {
7785 chain->decActiveTrackCnt();
7786 chain->decTrackCnt();
7787 }
7788
7789 broadcast_l();
7790
7791 if (mActiveTracks.size() == 0) {
7792 mHalStream->stop();
7793 }
7794 return NO_ERROR;
7795}
7796
Eric Laurent18b57012017-02-13 16:23:52 -08007797status_t AudioFlinger::MmapThread::standby()
7798{
7799 ALOGV("%s", __FUNCTION__);
7800
7801 if (mHalStream == 0) {
7802 return NO_INIT;
7803 }
7804 if (mActiveTracks.size() != 0) {
7805 return INVALID_OPERATION;
7806 }
7807 mHalStream->standby();
7808 mStandby = true;
7809 releaseWakeLock();
7810 return NO_ERROR;
7811}
7812
Eric Laurent6acd1d42017-01-04 14:23:29 -08007813
7814void AudioFlinger::MmapThread::readHalParameters_l()
7815{
7816 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7817 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7818 mFormat = mHALFormat;
7819 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7820 result = mHalStream->getFrameSize(&mFrameSize);
7821 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7822 result = mHalStream->getBufferSize(&mBufferSize);
7823 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7824 mFrameCount = mBufferSize / mFrameSize;
7825}
7826
7827bool AudioFlinger::MmapThread::threadLoop()
7828{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007829 checkSilentMode_l();
7830
7831 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7832
7833 while (!exitPending())
7834 {
7835 Mutex::Autolock _l(mLock);
7836 Vector< sp<EffectChain> > effectChains;
7837
7838 if (mSignalPending) {
7839 // A signal was raised while we were unlocked
7840 mSignalPending = false;
7841 } else {
7842 if (mConfigEvents.isEmpty()) {
7843 // we're about to wait, flush the binder command buffer
7844 IPCThreadState::self()->flushCommands();
7845
7846 if (exitPending()) {
7847 break;
7848 }
7849
Eric Laurent6acd1d42017-01-04 14:23:29 -08007850 // wait until we have something to do...
7851 ALOGV("%s going to sleep", myName.string());
7852 mWaitWorkCV.wait(mLock);
7853 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007854
7855 checkSilentMode_l();
7856
7857 continue;
7858 }
7859 }
7860
7861 processConfigEvents_l();
7862
7863 processVolume_l();
7864
7865 checkInvalidTracks_l();
7866
7867 mActiveTracks.updatePowerState(this);
7868
7869 lockEffectChains_l(effectChains);
7870 for (size_t i = 0; i < effectChains.size(); i ++) {
7871 effectChains[i]->process_l();
7872 }
7873 // enable changes in effect chain
7874 unlockEffectChains(effectChains);
7875 // Effect chains will be actually deleted here if they were removed from
7876 // mEffectChains list during mixing or effects processing
7877 }
7878
7879 threadLoop_exit();
7880
7881 if (!mStandby) {
7882 threadLoop_standby();
7883 mStandby = true;
7884 }
7885
Eric Laurent6acd1d42017-01-04 14:23:29 -08007886 ALOGV("Thread %p type %d exiting", this, mType);
7887 return false;
7888}
7889
7890// checkForNewParameter_l() must be called with ThreadBase::mLock held
7891bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7892 status_t& status)
7893{
7894 AudioParameter param = AudioParameter(keyValuePair);
7895 int value;
7896 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7897 // forward device change to effects that have requested to be
7898 // aware of attached audio device.
7899 if (value != AUDIO_DEVICE_NONE) {
7900 mOutDevice = value;
7901 for (size_t i = 0; i < mEffectChains.size(); i++) {
7902 mEffectChains[i]->setDevice_l(mOutDevice);
7903 }
7904 }
7905 }
7906 status = mHalStream->setParameters(keyValuePair);
7907
7908 return false;
7909}
7910
7911String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7912{
7913 Mutex::Autolock _l(mLock);
7914 String8 out_s8;
7915 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7916 return out_s8;
7917 }
7918 return String8();
7919}
7920
7921void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7922 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7923
7924 desc->mIoHandle = mId;
7925
7926 switch (event) {
7927 case AUDIO_INPUT_OPENED:
7928 case AUDIO_INPUT_CONFIG_CHANGED:
7929 case AUDIO_OUTPUT_OPENED:
7930 case AUDIO_OUTPUT_CONFIG_CHANGED:
7931 desc->mPatch = mPatch;
7932 desc->mChannelMask = mChannelMask;
7933 desc->mSamplingRate = mSampleRate;
7934 desc->mFormat = mFormat;
7935 desc->mFrameCount = mFrameCount;
7936 desc->mFrameCountHAL = mFrameCount;
7937 desc->mLatency = 0;
7938 break;
7939
7940 case AUDIO_INPUT_CLOSED:
7941 case AUDIO_OUTPUT_CLOSED:
7942 default:
7943 break;
7944 }
7945 mAudioFlinger->ioConfigChanged(event, desc, pid);
7946}
7947
7948status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7949 audio_patch_handle_t *handle)
7950{
7951 status_t status = NO_ERROR;
7952
7953 // store new device and send to effects
7954 audio_devices_t type = AUDIO_DEVICE_NONE;
7955 audio_port_handle_t deviceId;
7956 if (isOutput()) {
7957 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7958 type |= patch->sinks[i].ext.device.type;
7959 }
7960 deviceId = patch->sinks[0].id;
7961 } else {
7962 type = patch->sources[0].ext.device.type;
7963 deviceId = patch->sources[0].id;
7964 }
7965
7966 for (size_t i = 0; i < mEffectChains.size(); i++) {
7967 mEffectChains[i]->setDevice_l(type);
7968 }
7969
7970 if (isOutput()) {
7971 mOutDevice = type;
7972 } else {
7973 mInDevice = type;
7974 // store new source and send to effects
7975 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7976 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7977 for (size_t i = 0; i < mEffectChains.size(); i++) {
7978 mEffectChains[i]->setAudioSource_l(mAudioSource);
7979 }
7980 }
7981 }
7982
7983 if (mAudioHwDev->supportsAudioPatches()) {
7984 status = mHalDevice->createAudioPatch(patch->num_sources,
7985 patch->sources,
7986 patch->num_sinks,
7987 patch->sinks,
7988 handle);
7989 } else {
7990 char *address;
7991 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7992 //FIXME: we only support address on first sink with HAL version < 3.0
7993 address = audio_device_address_to_parameter(
7994 patch->sinks[0].ext.device.type,
7995 patch->sinks[0].ext.device.address);
7996 } else {
7997 address = (char *)calloc(1, 1);
7998 }
7999 AudioParameter param = AudioParameter(String8(address));
8000 free(address);
8001 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8002 if (!isOutput()) {
8003 param.addInt(String8(AudioParameter::keyInputSource),
8004 (int)patch->sinks[0].ext.mix.usecase.source);
8005 }
8006 status = mHalStream->setParameters(param.toString());
8007 *handle = AUDIO_PATCH_HANDLE_NONE;
8008 }
8009
8010 if (isOutput() && mPrevOutDevice != mOutDevice) {
8011 mPrevOutDevice = type;
8012 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008013 sp<MmapStreamCallback> callback = mCallback.promote();
8014 if (callback != 0) {
8015 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008016 }
8017 }
8018 if (!isOutput() && mPrevInDevice != mInDevice) {
8019 mPrevInDevice = type;
8020 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008021 sp<MmapStreamCallback> callback = mCallback.promote();
8022 if (callback != 0) {
8023 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008024 }
8025 }
8026 return status;
8027}
8028
8029status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8030{
8031 status_t status = NO_ERROR;
8032
8033 mInDevice = AUDIO_DEVICE_NONE;
8034
8035 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8036 supportsAudioPatches : false;
8037
8038 if (supportsAudioPatches) {
8039 status = mHalDevice->releaseAudioPatch(handle);
8040 } else {
8041 AudioParameter param;
8042 param.addInt(String8(AudioParameter::keyRouting), 0);
8043 status = mHalStream->setParameters(param.toString());
8044 }
8045 return status;
8046}
8047
8048void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8049{
8050 ThreadBase::getAudioPortConfig(config);
8051 if (isOutput()) {
8052 config->role = AUDIO_PORT_ROLE_SOURCE;
8053 config->ext.mix.hw_module = mAudioHwDev->handle();
8054 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8055 } else {
8056 config->role = AUDIO_PORT_ROLE_SINK;
8057 config->ext.mix.hw_module = mAudioHwDev->handle();
8058 config->ext.mix.usecase.source = mAudioSource;
8059 }
8060}
8061
8062status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8063{
8064 audio_session_t session = chain->sessionId();
8065
8066 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8067 // Attach all tracks with same session ID to this chain.
8068 // indicate all active tracks in the chain
8069 for (const sp<MmapTrack> &track : mActiveTracks) {
8070 if (session == track->sessionId()) {
8071 chain->incTrackCnt();
8072 chain->incActiveTrackCnt();
8073 }
8074 }
8075
8076 chain->setThread(this);
8077 chain->setInBuffer(nullptr);
8078 chain->setOutBuffer(nullptr);
8079 chain->syncHalEffectsState();
8080
8081 mEffectChains.add(chain);
8082 checkSuspendOnAddEffectChain_l(chain);
8083 return NO_ERROR;
8084}
8085
8086size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8087{
8088 audio_session_t session = chain->sessionId();
8089
8090 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8091
8092 for (size_t i = 0; i < mEffectChains.size(); i++) {
8093 if (chain == mEffectChains[i]) {
8094 mEffectChains.removeAt(i);
8095 // detach all active tracks from the chain
8096 // detach all tracks with same session ID from this chain
8097 for (const sp<MmapTrack> &track : mActiveTracks) {
8098 if (session == track->sessionId()) {
8099 chain->decActiveTrackCnt();
8100 chain->decTrackCnt();
8101 }
8102 }
8103 break;
8104 }
8105 }
8106 return mEffectChains.size();
8107}
8108
8109// hasAudioSession_l() must be called with ThreadBase::mLock held
8110uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8111{
8112 uint32_t result = 0;
8113 if (getEffectChain_l(sessionId) != 0) {
8114 result = EFFECT_SESSION;
8115 }
8116
8117 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8118 sp<MmapTrack> track = mActiveTracks[i];
8119 if (sessionId == track->sessionId()) {
8120 result |= TRACK_SESSION;
8121 if (track->isFastTrack()) {
8122 result |= FAST_SESSION;
8123 }
8124 break;
8125 }
8126 }
8127
8128 return result;
8129}
8130
8131void AudioFlinger::MmapThread::threadLoop_standby()
8132{
8133 mHalStream->standby();
8134}
8135
8136void AudioFlinger::MmapThread::threadLoop_exit()
8137{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008138 sp<MmapStreamCallback> callback = mCallback.promote();
8139 if (callback != 0) {
8140 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008141 }
8142}
8143
8144status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8145{
8146 return BAD_VALUE;
8147}
8148
8149bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8150{
8151 return false;
8152}
8153
8154status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8155 const effect_descriptor_t *desc, audio_session_t sessionId)
8156{
8157 // No global effect sessions on mmap threads
8158 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8159 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8160 desc->name, mThreadName);
8161 return BAD_VALUE;
8162 }
8163
8164 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8165 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8166 desc->name);
8167 return BAD_VALUE;
8168 }
8169 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008170 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8171 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008172 return BAD_VALUE;
8173 }
8174
8175 // Only allow effects without processing load or latency
8176 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8177 return BAD_VALUE;
8178 }
8179
8180 return NO_ERROR;
8181
8182}
8183
8184void AudioFlinger::MmapThread::checkInvalidTracks_l()
8185{
8186 for (const sp<MmapTrack> &track : mActiveTracks) {
8187 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008188 sp<MmapStreamCallback> callback = mCallback.promote();
8189 if (callback != 0) {
8190 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008191 }
8192 break;
8193 }
8194 }
8195}
8196
8197void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8198{
8199 dumpInternals(fd, args);
8200 dumpTracks(fd, args);
8201 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008202 dprintf(fd, " Local log:\n");
8203 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008204}
8205
8206void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8207{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008208 dumpBase(fd, args);
8209
8210 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8211 mAttr.content_type, mAttr.usage, mAttr.source);
8212 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8213 if (mActiveTracks.size() == 0) {
8214 dprintf(fd, " No active clients\n");
8215 }
8216}
8217
8218void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8219{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008220 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008221 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008222 dprintf(fd, " %zu Tracks\n", numtracks);
8223 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008224 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008225 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008226 MmapTrack::appendDumpHeader(result);
8227 for (size_t i = 0; i < numtracks ; ++i) {
8228 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008229 result.append(prefix);
8230 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008231 }
8232 } else {
8233 dprintf(fd, "\n");
8234 }
8235 write(fd, result.string(), result.size());
8236}
8237
8238AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8239 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8240 AudioHwDevice *hwDev, AudioStreamOut *output,
8241 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8242 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8243 mStreamType(AUDIO_STREAM_MUSIC),
8244 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8245{
8246 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8247 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8248 mMasterVolume = audioFlinger->masterVolume_l();
8249 mMasterMute = audioFlinger->masterMute_l();
8250 if (mAudioHwDev) {
8251 if (mAudioHwDev->canSetMasterVolume()) {
8252 mMasterVolume = 1.0;
8253 }
8254
8255 if (mAudioHwDev->canSetMasterMute()) {
8256 mMasterMute = false;
8257 }
8258 }
8259}
8260
8261void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8262 audio_stream_type_t streamType,
8263 audio_session_t sessionId,
8264 const sp<MmapStreamCallback>& callback,
8265 audio_port_handle_t portId)
8266{
8267 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8268 mStreamType = streamType;
8269}
8270
8271AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8272{
8273 Mutex::Autolock _l(mLock);
8274 AudioStreamOut *output = mOutput;
8275 mOutput = NULL;
8276 return output;
8277}
8278
8279void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8280{
8281 Mutex::Autolock _l(mLock);
8282 // Don't apply master volume in SW if our HAL can do it for us.
8283 if (mAudioHwDev &&
8284 mAudioHwDev->canSetMasterVolume()) {
8285 mMasterVolume = 1.0;
8286 } else {
8287 mMasterVolume = value;
8288 }
8289}
8290
8291void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8292{
8293 Mutex::Autolock _l(mLock);
8294 // Don't apply master mute in SW if our HAL can do it for us.
8295 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8296 mMasterMute = false;
8297 } else {
8298 mMasterMute = muted;
8299 }
8300}
8301
8302void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8303{
8304 Mutex::Autolock _l(mLock);
8305 if (stream == mStreamType) {
8306 mStreamVolume = value;
8307 broadcast_l();
8308 }
8309}
8310
8311float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8312{
8313 Mutex::Autolock _l(mLock);
8314 if (stream == mStreamType) {
8315 return mStreamVolume;
8316 }
8317 return 0.0f;
8318}
8319
8320void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8321{
8322 Mutex::Autolock _l(mLock);
8323 if (stream == mStreamType) {
8324 mStreamMute= muted;
8325 broadcast_l();
8326 }
8327}
8328
8329void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8330{
8331 Mutex::Autolock _l(mLock);
8332 if (streamType == mStreamType) {
8333 for (const sp<MmapTrack> &track : mActiveTracks) {
8334 track->invalidate();
8335 }
8336 broadcast_l();
8337 }
8338}
8339
8340void AudioFlinger::MmapPlaybackThread::processVolume_l()
8341{
8342 float volume;
8343
8344 if (mMasterMute || mStreamMute) {
8345 volume = 0;
8346 } else {
8347 volume = mMasterVolume * mStreamVolume;
8348 }
8349
8350 if (volume != mHalVolFloat) {
8351 mHalVolFloat = volume;
8352
8353 // Convert volumes from float to 8.24
8354 uint32_t vol = (uint32_t)(volume * (1 << 24));
8355
8356 // Delegate volume control to effect in track effect chain if needed
8357 // only one effect chain can be present on DirectOutputThread, so if
8358 // there is one, the track is connected to it
8359 if (!mEffectChains.isEmpty()) {
8360 mEffectChains[0]->setVolume_l(&vol, &vol);
8361 volume = (float)vol / (1 << 24);
8362 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008363 // Try to use HW volume control and fall back to SW control if not implemented
8364 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8365 sp<MmapStreamCallback> callback = mCallback.promote();
8366 if (callback != 0) {
8367 int channelCount;
8368 if (isOutput()) {
8369 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8370 } else {
8371 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8372 }
8373 Vector<float> values;
8374 for (int i = 0; i < channelCount; i++) {
8375 values.add(volume);
8376 }
8377 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008378 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008379 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008380 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008381 }
8382 }
8383}
8384
8385void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8386{
8387 if (!mMasterMute) {
8388 char value[PROPERTY_VALUE_MAX];
8389 if (property_get("ro.audio.silent", value, "0") > 0) {
8390 char *endptr;
8391 unsigned long ul = strtoul(value, &endptr, 0);
8392 if (*endptr == '\0' && ul != 0) {
8393 ALOGD("Silence is golden");
8394 // The setprop command will not allow a property to be changed after
8395 // the first time it is set, so we don't have to worry about un-muting.
8396 setMasterMute_l(true);
8397 }
8398 }
8399 }
8400}
8401
8402void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8403{
8404 MmapThread::dumpInternals(fd, args);
8405
Glenn Kastend3bb6452016-12-05 18:14:37 -08008406 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8407 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008408 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8409}
8410
8411AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8412 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8413 AudioHwDevice *hwDev, AudioStreamIn *input,
8414 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8415 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8416 mInput(input)
8417{
8418 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8419 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8420}
8421
8422AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8423{
8424 Mutex::Autolock _l(mLock);
8425 AudioStreamIn *input = mInput;
8426 mInput = NULL;
8427 return input;
8428}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008429} // namespace android