blob: 2a877e35c3b34f1a2e96337a9a7a48df286bf075 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Eric Laurent81784c32012-11-19 14:55:58 -080059#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080060#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070061#include "FastCapture.h"
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070063#include "mediautils/SchedulingPolicyService.h"
Eric Laurent81784c32012-11-19 14:55:58 -080064
Eric Laurent81784c32012-11-19 14:55:58 -080065#ifdef ADD_BATTERY_DATA
66#include <media/IMediaPlayerService.h>
67#include <media/IMediaDeathNotifier.h>
68#endif
69
Eric Laurent81784c32012-11-19 14:55:58 -080070#ifdef DEBUG_CPU_USAGE
71#include <cpustats/CentralTendencyStatistics.h>
72#include <cpustats/ThreadCpuUsage.h>
73#endif
74
Glenn Kastenc05b8d72016-03-24 09:48:17 -070075#include "AutoPark.h"
76
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080077#include <pthread.h>
78#include "TypedLogger.h"
79
Eric Laurent81784c32012-11-19 14:55:58 -080080// ----------------------------------------------------------------------------
81
82// Note: the following macro is used for extremely verbose logging message. In
83// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
84// 0; but one side effect of this is to turn all LOGV's as well. Some messages
85// are so verbose that we want to suppress them even when we have ALOG_ASSERT
86// turned on. Do not uncomment the #def below unless you really know what you
87// are doing and want to see all of the extremely verbose messages.
88//#define VERY_VERY_VERBOSE_LOGGING
89#ifdef VERY_VERY_VERBOSE_LOGGING
90#define ALOGVV ALOGV
91#else
92#define ALOGVV(a...) do { } while(0)
93#endif
94
Andy Hung6770c6f2015-04-07 13:43:36 -070095// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070096#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -070097template <typename T>
98static inline T min(const T& a, const T& b)
99{
100 return a < b ? a : b;
101}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700102
Eric Laurent81784c32012-11-19 14:55:58 -0800103namespace android {
104
105// retry counts for buffer fill timeout
106// 50 * ~20msecs = 1 second
107static const int8_t kMaxTrackRetries = 50;
108static const int8_t kMaxTrackStartupRetries = 50;
109// allow less retry attempts on direct output thread.
110// direct outputs can be a scarce resource in audio hardware and should
111// be released as quickly as possible.
112static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700113
Eric Laurent51716182016-02-29 18:00:56 -0800114
Eric Laurent81784c32012-11-19 14:55:58 -0800115
116// don't warn about blocked writes or record buffer overflows more often than this
117static const nsecs_t kWarningThrottleNs = seconds(5);
118
119// RecordThread loop sleep time upon application overrun or audio HAL read error
120static const int kRecordThreadSleepUs = 5000;
121
Eric Laurent10351942014-05-08 18:49:52 -0700122// maximum time to wait in sendConfigEvent_l() for a status to be received
123static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800124
125// minimum sleep time for the mixer thread loop when tracks are active but in underrun
126static const uint32_t kMinThreadSleepTimeUs = 5000;
127// maximum divider applied to the active sleep time in the mixer thread loop
128static const uint32_t kMaxThreadSleepTimeShift = 2;
129
Andy Hung09a50072014-02-27 14:30:47 -0800130// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700131// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800132static const uint32_t kMinNormalSinkBufferSizeMs = 20;
133// maximum normal sink buffer size
134static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800135
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700136// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
137// FIXME This should be based on experimentally observed scheduling jitter
138static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
139
Eric Laurent972a1732013-09-04 09:42:59 -0700140// Offloaded output thread standby delay: allows track transition without going to standby
141static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
142
Eric Laurent51716182016-02-29 18:00:56 -0800143// Direct output thread minimum sleep time in idle or active(underrun) state
144static const nsecs_t kDirectMinSleepTimeUs = 10000;
145
Glenn Kasten1b291842016-07-18 14:55:21 -0700146// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
147// balance between power consumption and latency, and allows threads to be scheduled reliably
148// by the CFS scheduler.
149// FIXME Express other hardcoded references to 20ms with references to this constant and move
150// it appropriately.
151#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800152
Eric Laurent81784c32012-11-19 14:55:58 -0800153// Whether to use fast mixer
154static const enum {
155 FastMixer_Never, // never initialize or use: for debugging only
156 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
157 // normal mixer multiplier is 1
158 FastMixer_Static, // initialize if needed, then use all the time if initialized,
159 // multiplier is calculated based on min & max normal mixer buffer size
160 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
161 // multiplier is calculated based on min & max normal mixer buffer size
162 // FIXME for FastMixer_Dynamic:
163 // Supporting this option will require fixing HALs that can't handle large writes.
164 // For example, one HAL implementation returns an error from a large write,
165 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
166 // We could either fix the HAL implementations, or provide a wrapper that breaks
167 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
168} kUseFastMixer = FastMixer_Static;
169
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700170// Whether to use fast capture
171static const enum {
172 FastCapture_Never, // never initialize or use: for debugging only
173 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
174 FastCapture_Static, // initialize if needed, then use all the time if initialized
175} kUseFastCapture = FastCapture_Static;
176
Eric Laurent81784c32012-11-19 14:55:58 -0800177// Priorities for requestPriority
178static const int kPriorityAudioApp = 2;
179static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700180static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800181
Glenn Kastenea38ee72016-04-18 11:08:01 -0700182// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
183// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
184// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700185
186// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800187static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kasten03490092014-05-27 12:30:54 -0700189// The minimum and maximum allowed values
190static const int kFastTrackMultiplierMin = 1;
191static const int kFastTrackMultiplierMax = 2;
192
193// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
194static int sFastTrackMultiplier = kFastTrackMultiplier;
195
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700196// See Thread::readOnlyHeap().
197// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
198// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
199// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Glenn Kasten9f81de32014-07-27 15:02:23 -0700200static const size_t kRecordThreadReadOnlyHeapSize = 0x2000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// ----------------------------------------------------------------------------
203
Glenn Kasten03490092014-05-27 12:30:54 -0700204static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
205
206static void sFastTrackMultiplierInit()
207{
208 char value[PROPERTY_VALUE_MAX];
209 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
210 char *endptr;
211 unsigned long ul = strtoul(value, &endptr, 0);
212 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
213 sFastTrackMultiplier = (int) ul;
214 }
215 }
216}
217
218// ----------------------------------------------------------------------------
219
Eric Laurent81784c32012-11-19 14:55:58 -0800220#ifdef ADD_BATTERY_DATA
221// To collect the amplifier usage
222static void addBatteryData(uint32_t params) {
223 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
224 if (service == NULL) {
225 // it already logged
226 return;
227 }
228
229 service->addBatteryData(params);
230}
231#endif
232
Andy Hung3f0c9022016-01-15 17:49:46 -0800233// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
234struct {
235 // call when you acquire a partial wakelock
236 void acquire(const sp<IBinder> &wakeLockToken) {
237 pthread_mutex_lock(&mLock);
238 if (wakeLockToken.get() == nullptr) {
239 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
240 } else {
241 if (mCount == 0) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 }
244 ++mCount;
245 }
246 pthread_mutex_unlock(&mLock);
247 }
248
249 // call when you release a partial wakelock.
250 void release(const sp<IBinder> &wakeLockToken) {
251 if (wakeLockToken.get() == nullptr) {
252 return;
253 }
254 pthread_mutex_lock(&mLock);
255 if (--mCount < 0) {
256 ALOGE("negative wakelock count");
257 mCount = 0;
258 }
259 pthread_mutex_unlock(&mLock);
260 }
261
262 // retrieves the boottime timebase offset from monotonic.
263 int64_t getBoottimeOffset() {
264 pthread_mutex_lock(&mLock);
265 int64_t boottimeOffset = mBoottimeOffset;
266 pthread_mutex_unlock(&mLock);
267 return boottimeOffset;
268 }
269
270 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
271 // and the selected timebase.
272 // Currently only TIMEBASE_BOOTTIME is allowed.
273 //
274 // This only needs to be called upon acquiring the first partial wakelock
275 // after all other partial wakelocks are released.
276 //
277 // We do an empirical measurement of the offset rather than parsing
278 // /proc/timer_list since the latter is not a formal kernel ABI.
279 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
280 int clockbase;
281 switch (timebase) {
282 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
283 clockbase = SYSTEM_TIME_BOOTTIME;
284 break;
285 default:
286 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
287 break;
288 }
289 // try three times to get the clock offset, choose the one
290 // with the minimum gap in measurements.
291 const int tries = 3;
292 nsecs_t bestGap, measured;
293 for (int i = 0; i < tries; ++i) {
294 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
295 const nsecs_t tbase = systemTime(clockbase);
296 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
297 const nsecs_t gap = tmono2 - tmono;
298 if (i == 0 || gap < bestGap) {
299 bestGap = gap;
300 measured = tbase - ((tmono + tmono2) >> 1);
301 }
302 }
303
304 // to avoid micro-adjusting, we don't change the timebase
305 // unless it is significantly different.
306 //
307 // Assumption: It probably takes more than toleranceNs to
308 // suspend and resume the device.
309 static int64_t toleranceNs = 10000; // 10 us
310 if (llabs(*offset - measured) > toleranceNs) {
311 ALOGV("Adjusting timebase offset old: %lld new: %lld",
312 (long long)*offset, (long long)measured);
313 *offset = measured;
314 }
315 }
316
317 pthread_mutex_t mLock;
318 int32_t mCount;
319 int64_t mBoottimeOffset;
320} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800321
322// ----------------------------------------------------------------------------
323// CPU Stats
324// ----------------------------------------------------------------------------
325
326class CpuStats {
327public:
328 CpuStats();
329 void sample(const String8 &title);
330#ifdef DEBUG_CPU_USAGE
331private:
332 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
333 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
334
335 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
336
337 int mCpuNum; // thread's current CPU number
338 int mCpukHz; // frequency of thread's current CPU in kHz
339#endif
340};
341
342CpuStats::CpuStats()
343#ifdef DEBUG_CPU_USAGE
344 : mCpuNum(-1), mCpukHz(-1)
345#endif
346{
347}
348
Glenn Kasten0f11b512014-01-31 16:18:54 -0800349void CpuStats::sample(const String8 &title
350#ifndef DEBUG_CPU_USAGE
351 __unused
352#endif
353 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800354#ifdef DEBUG_CPU_USAGE
355 // get current thread's delta CPU time in wall clock ns
356 double wcNs;
357 bool valid = mCpuUsage.sampleAndEnable(wcNs);
358
359 // record sample for wall clock statistics
360 if (valid) {
361 mWcStats.sample(wcNs);
362 }
363
364 // get the current CPU number
365 int cpuNum = sched_getcpu();
366
367 // get the current CPU frequency in kHz
368 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
369
370 // check if either CPU number or frequency changed
371 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
372 mCpuNum = cpuNum;
373 mCpukHz = cpukHz;
374 // ignore sample for purposes of cycles
375 valid = false;
376 }
377
378 // if no change in CPU number or frequency, then record sample for cycle statistics
379 if (valid && mCpukHz > 0) {
380 double cycles = wcNs * cpukHz * 0.000001;
381 mHzStats.sample(cycles);
382 }
383
384 unsigned n = mWcStats.n();
385 // mCpuUsage.elapsed() is expensive, so don't call it every loop
386 if ((n & 127) == 1) {
387 long long elapsed = mCpuUsage.elapsed();
388 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
389 double perLoop = elapsed / (double) n;
390 double perLoop100 = perLoop * 0.01;
391 double perLoop1k = perLoop * 0.001;
392 double mean = mWcStats.mean();
393 double stddev = mWcStats.stddev();
394 double minimum = mWcStats.minimum();
395 double maximum = mWcStats.maximum();
396 double meanCycles = mHzStats.mean();
397 double stddevCycles = mHzStats.stddev();
398 double minCycles = mHzStats.minimum();
399 double maxCycles = mHzStats.maximum();
400 mCpuUsage.resetElapsed();
401 mWcStats.reset();
402 mHzStats.reset();
403 ALOGD("CPU usage for %s over past %.1f secs\n"
404 " (%u mixer loops at %.1f mean ms per loop):\n"
405 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
406 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
407 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
408 title.string(),
409 elapsed * .000000001, n, perLoop * .000001,
410 mean * .001,
411 stddev * .001,
412 minimum * .001,
413 maximum * .001,
414 mean / perLoop100,
415 stddev / perLoop100,
416 minimum / perLoop100,
417 maximum / perLoop100,
418 meanCycles / perLoop1k,
419 stddevCycles / perLoop1k,
420 minCycles / perLoop1k,
421 maxCycles / perLoop1k);
422
423 }
424 }
425#endif
426};
427
428// ----------------------------------------------------------------------------
429// ThreadBase
430// ----------------------------------------------------------------------------
431
Glenn Kasten97b7b752014-09-28 13:04:24 -0700432// static
433const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
434{
435 switch (type) {
436 case MIXER:
437 return "MIXER";
438 case DIRECT:
439 return "DIRECT";
440 case DUPLICATING:
441 return "DUPLICATING";
442 case RECORD:
443 return "RECORD";
444 case OFFLOAD:
445 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800446 case MMAP:
447 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700448 default:
449 return "unknown";
450 }
451}
452
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700453std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800454{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700455 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800456 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700457 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800458 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700459 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800460 }
461 return result;
462}
463
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 std::string result;
467 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475 return result;
476}
477
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800478const char *sourceToString(audio_source_t source)
479{
480 switch (source) {
481 case AUDIO_SOURCE_DEFAULT: return "default";
482 case AUDIO_SOURCE_MIC: return "mic";
483 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
484 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
485 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
486 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
487 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
488 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
489 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800490 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800491 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
492 case AUDIO_SOURCE_HOTWORD: return "hotword";
493 default: return "unknown";
494 }
495}
496
Eric Laurent81784c32012-11-19 14:55:58 -0800497AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700498 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800499 : Thread(false /*canCallJava*/),
500 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700501 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700502 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800503 // are set by PlaybackThread::readOutputParameters_l() or
504 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700505 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800506 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700507 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
508 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800509 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700510 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800511 mSystemReady(systemReady),
512 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800513{
Eric Laurent296fb132015-05-01 11:38:42 -0700514 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800515}
516
517AudioFlinger::ThreadBase::~ThreadBase()
518{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700519 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700520 mConfigEvents.clear();
521
Eric Laurent81784c32012-11-19 14:55:58 -0800522 // do not lock the mutex in destructor
523 releaseWakeLock_l();
524 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800525 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800526 binder->unlinkToDeath(mDeathRecipient);
527 }
528}
529
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700530status_t AudioFlinger::ThreadBase::readyToRun()
531{
532 status_t status = initCheck();
533 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800534 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700535 } else {
536 ALOGE("No working audio driver found.");
537 }
538 return status;
539}
540
Eric Laurent81784c32012-11-19 14:55:58 -0800541void AudioFlinger::ThreadBase::exit()
542{
543 ALOGV("ThreadBase::exit");
544 // do any cleanup required for exit to succeed
545 preExit();
546 {
547 // This lock prevents the following race in thread (uniprocessor for illustration):
548 // if (!exitPending()) {
549 // // context switch from here to exit()
550 // // exit() calls requestExit(), what exitPending() observes
551 // // exit() calls signal(), which is dropped since no waiters
552 // // context switch back from exit() to here
553 // mWaitWorkCV.wait(...);
554 // // now thread is hung
555 // }
556 AutoMutex lock(mLock);
557 requestExit();
558 mWaitWorkCV.broadcast();
559 }
560 // When Thread::requestExitAndWait is made virtual and this method is renamed to
561 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
562 requestExitAndWait();
563}
564
565status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
566{
Eric Laurent81784c32012-11-19 14:55:58 -0800567 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
568 Mutex::Autolock _l(mLock);
569
Eric Laurent10351942014-05-08 18:49:52 -0700570 return sendSetParameterConfigEvent_l(keyValuePairs);
571}
572
573// sendConfigEvent_l() must be called with ThreadBase::mLock held
574// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
575status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
576{
577 status_t status = NO_ERROR;
578
Eric Laurent72e3f392015-05-20 14:43:50 -0700579 if (event->mRequiresSystemReady && !mSystemReady) {
580 event->mWaitStatus = false;
581 mPendingConfigEvents.add(event);
582 return status;
583 }
Eric Laurent10351942014-05-08 18:49:52 -0700584 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700585 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800586 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700587 mLock.unlock();
588 {
589 Mutex::Autolock _l(event->mLock);
590 while (event->mWaitStatus) {
591 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
592 event->mStatus = TIMED_OUT;
593 event->mWaitStatus = false;
594 }
595 }
596 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800597 }
Eric Laurent10351942014-05-08 18:49:52 -0700598 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800599 return status;
600}
601
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700602void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
604 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
608// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700609void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700612 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800613}
614
Mikhail Naganov83f04272017-02-07 10:45:09 -0800615void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700616{
617 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700619}
620
Eric Laurent81784c32012-11-19 14:55:58 -0800621// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800622void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
623 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800624{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700626 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800627}
628
Eric Laurent10351942014-05-08 18:49:52 -0700629// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
630status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
Andy Hung2ddee192015-12-18 17:34:44 -0800632 sp<ConfigEvent> configEvent;
633 AudioParameter param(keyValuePair);
634 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700635 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800636 setMasterMono_l(value != 0);
637 if (param.size() == 1) {
638 return NO_ERROR; // should be a solo parameter - we don't pass down
639 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700640 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800641 configEvent = new SetParameterConfigEvent(param.toString());
642 } else {
643 configEvent = new SetParameterConfigEvent(keyValuePair);
644 }
Eric Laurent10351942014-05-08 18:49:52 -0700645 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700646}
647
Eric Laurent1c333e22014-05-20 10:48:17 -0700648status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
649 const struct audio_patch *patch,
650 audio_patch_handle_t *handle)
651{
652 Mutex::Autolock _l(mLock);
653 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
654 status_t status = sendConfigEvent_l(configEvent);
655 if (status == NO_ERROR) {
656 CreateAudioPatchConfigEventData *data =
657 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
658 *handle = data->mHandle;
659 }
660 return status;
661}
662
663status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
664 const audio_patch_handle_t handle)
665{
666 Mutex::Autolock _l(mLock);
667 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
668 return sendConfigEvent_l(configEvent);
669}
670
671
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700672// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700673void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700674{
Eric Laurent10351942014-05-08 18:49:52 -0700675 bool configChanged = false;
676
Eric Laurent81784c32012-11-19 14:55:58 -0800677 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700678 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700679 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800680 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700681 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700682 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700683 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
684 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800685 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700686 true /*asynchronous*/);
687 if (err != 0) {
688 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700689 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700690 }
691 } break;
692 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700693 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700694 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700695 } break;
696 case CFG_EVENT_SET_PARAMETER: {
697 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
698 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
699 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700700 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
701 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700702 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700703 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700705 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700706 CreateAudioPatchConfigEventData *data =
707 (CreateAudioPatchConfigEventData *)event->mData.get();
708 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700709 const audio_devices_t newDevice = getDevice();
710 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
711 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
712 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 } break;
714 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700715 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 ReleaseAudioPatchConfigEventData *data =
717 (ReleaseAudioPatchConfigEventData *)event->mData.get();
718 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700719 const audio_devices_t newDevice = getDevice();
720 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
721 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
722 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700723 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700724 default:
Eric Laurent10351942014-05-08 18:49:52 -0700725 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700726 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 {
729 Mutex::Autolock _l(event->mLock);
730 if (event->mWaitStatus) {
731 event->mWaitStatus = false;
732 event->mCond.signal();
733 }
734 }
735 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
736 }
737
738 if (configChanged) {
739 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800740 }
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Marco Nelissenb2208842014-02-07 14:00:50 -0800743String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
744 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700745 const audio_channel_representation_t representation =
746 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700747
748 switch (representation) {
749 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
750 if (output) {
751 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
752 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
753 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
754 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
755 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
757 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
758 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
760 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
768 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
769 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
770 } else {
771 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
772 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
773 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
774 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
775 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
776 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
780 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
781 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
782 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
783 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
784 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
785 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
786 }
787 const int len = s.length();
788 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700789 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 s.unlockBuffer(len - 2); // remove trailing ", "
791 }
792 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800793 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
795 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
796 return s;
797 default:
798 s.appendFormat("unknown mask, representation:%d bits:%#x",
799 representation, audio_channel_mask_get_bits(mask));
800 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800801 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800802}
803
Glenn Kasten0f11b512014-01-31 16:18:54 -0800804void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800805{
806 const size_t SIZE = 256;
807 char buffer[SIZE];
808 String8 result;
809
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800810 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
811 this, mThreadName, getTid(), type(), threadTypeToString(type()));
812
Eric Laurent81784c32012-11-19 14:55:58 -0800813 bool locked = AudioFlinger::dumpTryLock(mLock);
814 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800815 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800816 }
817
Elliott Hughes87cebad2014-05-22 10:14:43 -0700818 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700819 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700820 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700822 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700823 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700824 dprintf(fd, " Channel count: %u\n", mChannelCount);
825 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800826 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700827 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700828 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800830 size_t numConfig = mConfigEvents.size();
831 if (numConfig) {
832 for (size_t i = 0; i < numConfig; i++) {
833 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700834 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800839 }
Andy Hung293558a2017-03-21 12:19:20 -0700840 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700841 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
842 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800843 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800844
845 if (locked) {
846 mLock.unlock();
847 }
848}
849
850void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
851{
852 const size_t SIZE = 256;
853 char buffer[SIZE];
854 String8 result;
855
Marco Nelissenb2208842014-02-07 14:00:50 -0800856 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000857 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800858 write(fd, buffer, strlen(buffer));
859
Marco Nelissenb2208842014-02-07 14:00:50 -0800860 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800861 sp<EffectChain> chain = mEffectChains[i];
862 if (chain != 0) {
863 chain->dump(fd, args);
864 }
865 }
866}
867
Andy Hungdae27702016-10-31 14:01:16 -0700868void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800869{
870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700871 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800872}
873
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100874String16 AudioFlinger::ThreadBase::getWakeLockTag()
875{
876 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800877 case MIXER:
878 return String16("AudioMix");
879 case DIRECT:
880 return String16("AudioDirectOut");
881 case DUPLICATING:
882 return String16("AudioDup");
883 case RECORD:
884 return String16("AudioIn");
885 case OFFLOAD:
886 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800887 case MMAP:
888 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800889 default:
890 ALOG_ASSERT(false);
891 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100892 }
893}
894
Andy Hungdae27702016-10-31 14:01:16 -0700895void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800896{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800897 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800898 if (mPowerManager != 0) {
899 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700900 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
901 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700902 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700904 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700905 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800906 if (status == NO_ERROR) {
907 mWakeLockToken = binder;
908 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800909 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800910 }
Wei Jia3f273d12015-11-24 09:06:49 -0800911
Andy Hung3f0c9022016-01-15 17:49:46 -0800912 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800913 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
914 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800915}
916
917void AudioFlinger::ThreadBase::releaseWakeLock()
918{
919 Mutex::Autolock _l(mLock);
920 releaseWakeLock_l();
921}
922
923void AudioFlinger::ThreadBase::releaseWakeLock_l()
924{
Andy Hung3f0c9022016-01-15 17:49:46 -0800925 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800927 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700929 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
930 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 }
932 mWakeLockToken.clear();
933 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800934}
935
936void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700937 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800938 // use checkService() to avoid blocking if power service is not up yet
939 sp<IBinder> binder =
940 defaultServiceManager()->checkService(String16("power"));
941 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800942 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800943 } else {
944 mPowerManager = interface_cast<IPowerManager>(binder);
945 binder->linkToDeath(mDeathRecipient);
946 }
947 }
948}
949
Andy Hungd01b0f12016-11-07 16:10:30 -0800950void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800951 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700952
953#if !LOG_NDEBUG
954 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800955 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700956 s << uid << " ";
957 }
958 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
959#endif
960
Andy Hung438e7572015-12-14 15:51:17 -0800961 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
962 if (mSystemReady) {
963 ALOGE("no wake lock to update, but system ready!");
964 } else {
965 ALOGW("no wake lock to update, system not ready yet");
966 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800967 return;
968 }
969 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800970 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
971 status_t status = mPowerManager->updateWakeLockUids(
972 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
973 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800974 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800975 }
976}
977
Eric Laurent81784c32012-11-19 14:55:58 -0800978void AudioFlinger::ThreadBase::clearPowerManager()
979{
980 Mutex::Autolock _l(mLock);
981 releaseWakeLock_l();
982 mPowerManager.clear();
983}
984
Glenn Kasten0f11b512014-01-31 16:18:54 -0800985void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800986{
987 sp<ThreadBase> thread = mThread.promote();
988 if (thread != 0) {
989 thread->clearPowerManager();
990 }
991 ALOGW("power manager service died !!!");
992}
993
Eric Laurent81784c32012-11-19 14:55:58 -0800994void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800995 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800996{
997 sp<EffectChain> chain = getEffectChain_l(sessionId);
998 if (chain != 0) {
999 if (type != NULL) {
1000 chain->setEffectSuspended_l(type, suspend);
1001 } else {
1002 chain->setEffectSuspendedAll_l(suspend);
1003 }
1004 }
1005
1006 updateSuspendedSessions_l(type, suspend, sessionId);
1007}
1008
1009void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1010{
1011 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1012 if (index < 0) {
1013 return;
1014 }
1015
1016 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1017 mSuspendedSessions.valueAt(index);
1018
1019 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001020 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001021 for (int j = 0; j < desc->mRefCount; j++) {
1022 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1023 chain->setEffectSuspendedAll_l(true);
1024 } else {
1025 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1026 desc->mType.timeLow);
1027 chain->setEffectSuspended_l(&desc->mType, true);
1028 }
1029 }
1030 }
1031}
1032
1033void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1034 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001035 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001036{
1037 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1038
1039 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1040
1041 if (suspend) {
1042 if (index >= 0) {
1043 sessionEffects = mSuspendedSessions.valueAt(index);
1044 } else {
1045 mSuspendedSessions.add(sessionId, sessionEffects);
1046 }
1047 } else {
1048 if (index < 0) {
1049 return;
1050 }
1051 sessionEffects = mSuspendedSessions.valueAt(index);
1052 }
1053
1054
1055 int key = EffectChain::kKeyForSuspendAll;
1056 if (type != NULL) {
1057 key = type->timeLow;
1058 }
1059 index = sessionEffects.indexOfKey(key);
1060
1061 sp<SuspendedSessionDesc> desc;
1062 if (suspend) {
1063 if (index >= 0) {
1064 desc = sessionEffects.valueAt(index);
1065 } else {
1066 desc = new SuspendedSessionDesc();
1067 if (type != NULL) {
1068 desc->mType = *type;
1069 }
1070 sessionEffects.add(key, desc);
1071 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1072 }
1073 desc->mRefCount++;
1074 } else {
1075 if (index < 0) {
1076 return;
1077 }
1078 desc = sessionEffects.valueAt(index);
1079 if (--desc->mRefCount == 0) {
1080 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1081 sessionEffects.removeItemsAt(index);
1082 if (sessionEffects.isEmpty()) {
1083 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1084 sessionId);
1085 mSuspendedSessions.removeItem(sessionId);
1086 }
1087 }
1088 }
1089 if (!sessionEffects.isEmpty()) {
1090 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1091 }
1092}
1093
1094void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1095 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001096 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001097{
1098 Mutex::Autolock _l(mLock);
1099 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1100}
1101
1102void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1103 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001104 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001105{
1106 if (mType != RECORD) {
1107 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1108 // another session. This gives the priority to well behaved effect control panels
1109 // and applications not using global effects.
1110 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1111 // global effects
1112 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1113 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1114 }
1115 }
1116
1117 sp<EffectChain> chain = getEffectChain_l(sessionId);
1118 if (chain != 0) {
1119 chain->checkSuspendOnEffectEnabled(effect, enabled);
1120 }
1121}
1122
Eric Laurent4c415062016-06-17 16:14:16 -07001123// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1124status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1125 const effect_descriptor_t *desc, audio_session_t sessionId)
1126{
1127 // No global effect sessions on record threads
1128 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1129 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1130 desc->name, mThreadName);
1131 return BAD_VALUE;
1132 }
1133 // only pre processing effects on record thread
1134 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1135 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1136 desc->name, mThreadName);
1137 return BAD_VALUE;
1138 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001139
1140 // always allow effects without processing load or latency
1141 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1142 return NO_ERROR;
1143 }
1144
Eric Laurent4c415062016-06-17 16:14:16 -07001145 audio_input_flags_t flags = mInput->flags;
1146 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1147 if (flags & AUDIO_INPUT_FLAG_RAW) {
1148 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1153 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1154 desc->name, mThreadName);
1155 return BAD_VALUE;
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
1161// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1162status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1163 const effect_descriptor_t *desc, audio_session_t sessionId)
1164{
1165 // no preprocessing on playback threads
1166 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1167 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1168 " thread %s", desc->name, mThreadName);
1169 return BAD_VALUE;
1170 }
1171
1172 switch (mType) {
1173 case MIXER: {
1174 // Reject any effect on mixer multichannel sinks.
1175 // TODO: fix both format and multichannel issues with effects.
1176 if (mChannelCount != FCC_2) {
1177 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1178 " thread %s", desc->name, mChannelCount, mThreadName);
1179 return BAD_VALUE;
1180 }
1181 audio_output_flags_t flags = mOutput->flags;
1182 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1184 // global effects are applied only to non fast tracks if they are SW
1185 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1186 break;
1187 }
1188 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1189 // only post processing on output stage session
1190 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1191 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1192 " on output stage session", desc->name);
1193 return BAD_VALUE;
1194 }
1195 } else {
1196 // no restriction on effects applied on non fast tracks
1197 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1198 break;
1199 }
1200 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001201
1202 // always allow effects without processing load or latency
1203 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1204 break;
1205 }
Eric Laurent4c415062016-06-17 16:14:16 -07001206 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1207 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1208 desc->name);
1209 return BAD_VALUE;
1210 }
1211 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1212 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1213 " in fast mode", desc->name);
1214 return BAD_VALUE;
1215 }
1216 }
1217 } break;
1218 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001219 // nothing actionable on offload threads, if the effect:
1220 // - is offloadable: the effect can be created
1221 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1222 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001223 break;
1224 case DIRECT:
1225 // Reject any effect on Direct output threads for now, since the format of
1226 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1227 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1228 desc->name, mThreadName);
1229 return BAD_VALUE;
1230 case DUPLICATING:
1231 // Reject any effect on mixer multichannel sinks.
1232 // TODO: fix both format and multichannel issues with effects.
1233 if (mChannelCount != FCC_2) {
1234 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1235 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1236 return BAD_VALUE;
1237 }
1238 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1239 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1240 " thread %s", desc->name, mThreadName);
1241 return BAD_VALUE;
1242 }
1243 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1244 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1245 " DUPLICATING thread %s", desc->name, mThreadName);
1246 return BAD_VALUE;
1247 }
1248 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1249 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1250 " DUPLICATING thread %s", desc->name, mThreadName);
1251 return BAD_VALUE;
1252 }
1253 break;
1254 default:
1255 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1256 }
1257
1258 return NO_ERROR;
1259}
1260
Eric Laurent81784c32012-11-19 14:55:58 -08001261// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1262sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1263 const sp<AudioFlinger::Client>& client,
1264 const sp<IEffectClient>& effectClient,
1265 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001266 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001267 effect_descriptor_t *desc,
1268 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001269 status_t *status,
1270 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001271{
1272 sp<EffectModule> effect;
1273 sp<EffectHandle> handle;
1274 status_t lStatus;
1275 sp<EffectChain> chain;
1276 bool chainCreated = false;
1277 bool effectCreated = false;
1278 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001279 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001280
1281 lStatus = initCheck();
1282 if (lStatus != NO_ERROR) {
1283 ALOGW("createEffect_l() Audio driver not initialized.");
1284 goto Exit;
1285 }
1286
Eric Laurent81784c32012-11-19 14:55:58 -08001287 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1288
1289 { // scope for mLock
1290 Mutex::Autolock _l(mLock);
1291
Eric Laurent4c415062016-06-17 16:14:16 -07001292 lStatus = checkEffectCompatibility_l(desc, sessionId);
1293 if (lStatus != NO_ERROR) {
1294 goto Exit;
1295 }
1296
Eric Laurent81784c32012-11-19 14:55:58 -08001297 // check for existing effect chain with the requested audio session
1298 chain = getEffectChain_l(sessionId);
1299 if (chain == 0) {
1300 // create a new chain for this session
1301 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1302 chain = new EffectChain(this, sessionId);
1303 addEffectChain_l(chain);
1304 chain->setStrategy(getStrategyForSession_l(sessionId));
1305 chainCreated = true;
1306 } else {
1307 effect = chain->getEffectFromDesc_l(desc);
1308 }
1309
1310 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1311
1312 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001313 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001314 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001315 lStatus = AudioSystem::registerEffect(
1316 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001317 if (lStatus != NO_ERROR) {
1318 goto Exit;
1319 }
1320 effectRegistered = true;
1321 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001322 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001323 if (lStatus != NO_ERROR) {
1324 goto Exit;
1325 }
1326 effectCreated = true;
1327
1328 effect->setDevice(mOutDevice);
1329 effect->setDevice(mInDevice);
1330 effect->setMode(mAudioFlinger->getMode());
1331 effect->setAudioSource(mAudioSource);
1332 }
1333 // create effect handle and connect it to effect module
1334 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001335 lStatus = handle->initCheck();
1336 if (lStatus == OK) {
1337 lStatus = effect->addHandle(handle.get());
1338 }
Eric Laurent81784c32012-11-19 14:55:58 -08001339 if (enabled != NULL) {
1340 *enabled = (int)effect->isEnabled();
1341 }
1342 }
1343
1344Exit:
1345 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1346 Mutex::Autolock _l(mLock);
1347 if (effectCreated) {
1348 chain->removeEffect_l(effect);
1349 }
1350 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001351 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 }
1353 if (chainCreated) {
1354 removeEffectChain_l(chain);
1355 }
1356 handle.clear();
1357 }
1358
Glenn Kasten9156ef32013-08-06 15:39:08 -07001359 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001360 return handle;
1361}
1362
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001363void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1364 bool unpinIfLast)
1365{
1366 bool remove = false;
1367 sp<EffectModule> effect;
1368 {
1369 Mutex::Autolock _l(mLock);
1370
1371 effect = handle->effect().promote();
1372 if (effect == 0) {
1373 return;
1374 }
1375 // restore suspended effects if the disconnected handle was enabled and the last one.
1376 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1377 if (remove) {
1378 removeEffect_l(effect, true);
1379 }
1380 }
1381 if (remove) {
1382 mAudioFlinger->updateOrphanEffectChains(effect);
1383 AudioSystem::unregisterEffect(effect->id());
1384 if (handle->enabled()) {
1385 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1386 }
1387 }
1388}
1389
Glenn Kastend848eb42016-03-08 13:42:11 -08001390sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1391 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001392{
1393 Mutex::Autolock _l(mLock);
1394 return getEffect_l(sessionId, effectId);
1395}
1396
Glenn Kastend848eb42016-03-08 13:42:11 -08001397sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1398 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001399{
1400 sp<EffectChain> chain = getEffectChain_l(sessionId);
1401 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1402}
1403
1404// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1405// PlaybackThread::mLock held
1406status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1407{
1408 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001409 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001410 sp<EffectChain> chain = getEffectChain_l(sessionId);
1411 bool chainCreated = false;
1412
Eric Laurent5baf2af2013-09-12 17:37:00 -07001413 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1414 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1415 this, effect->desc().name, effect->desc().flags);
1416
Eric Laurent81784c32012-11-19 14:55:58 -08001417 if (chain == 0) {
1418 // create a new chain for this session
1419 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1420 chain = new EffectChain(this, sessionId);
1421 addEffectChain_l(chain);
1422 chain->setStrategy(getStrategyForSession_l(sessionId));
1423 chainCreated = true;
1424 }
1425 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1426
1427 if (chain->getEffectFromId_l(effect->id()) != 0) {
1428 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1429 this, effect->desc().name, chain.get());
1430 return BAD_VALUE;
1431 }
1432
Eric Laurent5baf2af2013-09-12 17:37:00 -07001433 effect->setOffloaded(mType == OFFLOAD, mId);
1434
Eric Laurent81784c32012-11-19 14:55:58 -08001435 status_t status = chain->addEffect_l(effect);
1436 if (status != NO_ERROR) {
1437 if (chainCreated) {
1438 removeEffectChain_l(chain);
1439 }
1440 return status;
1441 }
1442
1443 effect->setDevice(mOutDevice);
1444 effect->setDevice(mInDevice);
1445 effect->setMode(mAudioFlinger->getMode());
1446 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001447
Eric Laurent81784c32012-11-19 14:55:58 -08001448 return NO_ERROR;
1449}
1450
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001451void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001452
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001453 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001454 effect_descriptor_t desc = effect->desc();
1455 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1456 detachAuxEffect_l(effect->id());
1457 }
1458
1459 sp<EffectChain> chain = effect->chain().promote();
1460 if (chain != 0) {
1461 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001462 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001463 removeEffectChain_l(chain);
1464 }
1465 } else {
1466 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1467 }
1468}
1469
1470void AudioFlinger::ThreadBase::lockEffectChains_l(
1471 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1472{
1473 effectChains = mEffectChains;
1474 for (size_t i = 0; i < mEffectChains.size(); i++) {
1475 mEffectChains[i]->lock();
1476 }
1477}
1478
1479void AudioFlinger::ThreadBase::unlockEffectChains(
1480 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1481{
1482 for (size_t i = 0; i < effectChains.size(); i++) {
1483 effectChains[i]->unlock();
1484 }
1485}
1486
Glenn Kastend848eb42016-03-08 13:42:11 -08001487sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001488{
1489 Mutex::Autolock _l(mLock);
1490 return getEffectChain_l(sessionId);
1491}
1492
Glenn Kastend848eb42016-03-08 13:42:11 -08001493sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1494 const
Eric Laurent81784c32012-11-19 14:55:58 -08001495{
1496 size_t size = mEffectChains.size();
1497 for (size_t i = 0; i < size; i++) {
1498 if (mEffectChains[i]->sessionId() == sessionId) {
1499 return mEffectChains[i];
1500 }
1501 }
1502 return 0;
1503}
1504
1505void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1506{
1507 Mutex::Autolock _l(mLock);
1508 size_t size = mEffectChains.size();
1509 for (size_t i = 0; i < size; i++) {
1510 mEffectChains[i]->setMode_l(mode);
1511 }
1512}
1513
Eric Laurent83b88082014-06-20 18:31:16 -07001514void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1515{
1516 config->type = AUDIO_PORT_TYPE_MIX;
1517 config->ext.mix.handle = mId;
1518 config->sample_rate = mSampleRate;
1519 config->format = mFormat;
1520 config->channel_mask = mChannelMask;
1521 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1522 AUDIO_PORT_CONFIG_FORMAT;
1523}
1524
Eric Laurent72e3f392015-05-20 14:43:50 -07001525void AudioFlinger::ThreadBase::systemReady()
1526{
1527 Mutex::Autolock _l(mLock);
1528 if (mSystemReady) {
1529 return;
1530 }
1531 mSystemReady = true;
1532
1533 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1534 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1535 }
1536 mPendingConfigEvents.clear();
1537}
1538
Andy Hungdae27702016-10-31 14:01:16 -07001539template <typename T>
1540ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1541 ssize_t index = mActiveTracks.indexOf(track);
1542 if (index >= 0) {
1543 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1544 return index;
1545 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001546 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001547 mActiveTracksGeneration++;
1548 mLatestActiveTrack = track;
1549 ++mBatteryCounter[track->uid()].second;
1550 return mActiveTracks.add(track);
1551}
1552
1553template <typename T>
1554ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1555 ssize_t index = mActiveTracks.remove(track);
1556 if (index < 0) {
1557 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1558 return index;
1559 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001560 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001561 mActiveTracksGeneration++;
1562 --mBatteryCounter[track->uid()].second;
1563 // mLatestActiveTrack is not cleared even if is the same as track.
1564 return index;
1565}
1566
1567template <typename T>
1568void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1569 for (const sp<T> &track : mActiveTracks) {
1570 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001571 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001572 }
1573 mLastActiveTracksGeneration = mActiveTracksGeneration;
1574 mActiveTracks.clear();
1575 mLatestActiveTrack.clear();
1576 mBatteryCounter.clear();
1577}
1578
1579template <typename T>
1580void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1581 sp<ThreadBase> thread, bool force) {
1582 // Updates ActiveTracks client uids to the thread wakelock.
1583 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1584 thread->updateWakeLockUids_l(getWakeLockUids());
1585 mLastActiveTracksGeneration = mActiveTracksGeneration;
1586 }
1587
1588 // Updates BatteryNotifier uids
1589 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1590 const uid_t uid = it->first;
1591 ssize_t &previous = it->second.first;
1592 ssize_t &current = it->second.second;
1593 if (current > 0) {
1594 if (previous == 0) {
1595 BatteryNotifier::getInstance().noteStartAudio(uid);
1596 }
1597 previous = current;
1598 ++it;
1599 } else if (current == 0) {
1600 if (previous > 0) {
1601 BatteryNotifier::getInstance().noteStopAudio(uid);
1602 }
1603 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1604 } else /* (current < 0) */ {
1605 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1606 }
1607 }
1608}
Eric Laurent83b88082014-06-20 18:31:16 -07001609
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001610template <typename T>
1611void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1612 const char *funcName, const sp<T> &track) const {
1613 if (mLocalLog != nullptr) {
1614 String8 result;
1615 track->appendDump(result, false /* active */);
1616 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1617 }
1618}
1619
Eric Laurent6acd1d42017-01-04 14:23:29 -08001620void AudioFlinger::ThreadBase::broadcast_l()
1621{
1622 // Thread could be blocked waiting for async
1623 // so signal it to handle state changes immediately
1624 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1625 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1626 mSignalPending = true;
1627 mWaitWorkCV.broadcast();
1628}
1629
Eric Laurent81784c32012-11-19 14:55:58 -08001630// ----------------------------------------------------------------------------
1631// Playback
1632// ----------------------------------------------------------------------------
1633
1634AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1635 AudioStreamOut* output,
1636 audio_io_handle_t id,
1637 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001638 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001639 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001640 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001641 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001642 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001643 mMixerBuffer(NULL),
1644 mMixerBufferSize(0),
1645 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1646 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001647 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001648 mEffectBuffer(NULL),
1649 mEffectBufferSize(0),
1650 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1651 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001652 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001653 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001654 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001655 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001656 // mStreamTypes[] initialized in constructor body
1657 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001658 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001659 mMixerStatus(MIXER_IDLE),
1660 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001661 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001662 mBytesRemaining(0),
1663 mCurrentWriteLength(0),
1664 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001665 mWriteAckSequence(0),
1666 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001667 mScreenState(AudioFlinger::mScreenState),
1668 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001669 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001670 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001671{
Glenn Kastend7dca052015-03-05 16:05:54 -08001672 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1673 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001674
1675 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1676 // it would be safer to explicitly pass initial masterVolume/masterMute as
1677 // parameter.
1678 //
1679 // If the HAL we are using has support for master volume or master mute,
1680 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1681 // and the mute set to false).
1682 mMasterVolume = audioFlinger->masterVolume_l();
1683 mMasterMute = audioFlinger->masterMute_l();
1684 if (mOutput && mOutput->audioHwDev) {
1685 if (mOutput->audioHwDev->canSetMasterVolume()) {
1686 mMasterVolume = 1.0;
1687 }
1688
1689 if (mOutput->audioHwDev->canSetMasterMute()) {
1690 mMasterMute = false;
1691 }
1692 }
1693
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001694 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001695
Eric Laurent223fd5c2014-11-11 13:43:36 -08001696 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001697 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001698 stream = (audio_stream_type_t) (stream + 1)) {
1699 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1700 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1701 }
Eric Laurent81784c32012-11-19 14:55:58 -08001702}
1703
1704AudioFlinger::PlaybackThread::~PlaybackThread()
1705{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001706 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001707 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001708 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001709 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001710}
1711
1712void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1713{
1714 dumpInternals(fd, args);
1715 dumpTracks(fd, args);
1716 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001717 dprintf(fd, " Local log:\n");
1718 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001719}
1720
Glenn Kasten0f11b512014-01-31 16:18:54 -08001721void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001722{
Eric Laurent81784c32012-11-19 14:55:58 -08001723 String8 result;
1724
Marco Nelissenb2208842014-02-07 14:00:50 -08001725 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001726 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1727 const stream_type_t *st = &mStreamTypes[i];
1728 if (i > 0) {
1729 result.appendFormat(", ");
1730 }
1731 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1732 if (st->mute) {
1733 result.append("M");
1734 }
1735 }
1736 result.append("\n");
1737 write(fd, result.string(), result.length());
1738 result.clear();
1739
Eric Laurent81784c32012-11-19 14:55:58 -08001740 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1741 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001742 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001743 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001744
1745 size_t numtracks = mTracks.size();
1746 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001747 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001748 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001749 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001750 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001751 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001752 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001753 Track::appendDumpHeader(result);
1754 for (size_t i = 0; i < numtracks; ++i) {
1755 sp<Track> track = mTracks[i];
1756 if (track != 0) {
1757 bool active = mActiveTracks.indexOf(track) >= 0;
1758 if (active) {
1759 numactiveseen++;
1760 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001761 result.append(prefix);
1762 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001763 }
1764 }
1765 } else {
1766 result.append("\n");
1767 }
1768 if (numactiveseen != numactive) {
1769 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001770 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001771 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001772 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001773 Track::appendDumpHeader(result);
1774 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001775 sp<Track> track = mActiveTracks[i];
1776 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001777 result.append(prefix);
1778 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001779 }
1780 }
1781 }
1782
1783 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001784}
1785
1786void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1787{
Glenn Kasten44182c22015-03-05 17:12:23 -08001788 dumpBase(fd, args);
1789
Elliott Hughes87cebad2014-05-22 10:14:43 -07001790 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001791 dprintf(fd, " Last write occurred (msecs): %llu\n",
1792 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001793 dprintf(fd, " Total writes: %d\n", mNumWrites);
1794 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1795 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1796 dprintf(fd, " Suspend count: %d\n", mSuspended);
1797 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1798 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1799 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1800 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001801 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001802 AudioStreamOut *output = mOutput;
1803 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001804 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1805 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001806 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1807 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1808 if (mPipeSink.get() != nullptr) {
1809 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1810 }
1811 if (output != nullptr) {
1812 dprintf(fd, " Hal stream dump:\n");
1813 (void)output->stream->dump(fd);
1814 }
Eric Laurent81784c32012-11-19 14:55:58 -08001815}
1816
1817// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001818
1819void AudioFlinger::PlaybackThread::onFirstRef()
1820{
Glenn Kastend7dca052015-03-05 16:05:54 -08001821 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001822}
1823
1824// ThreadBase virtuals
1825void AudioFlinger::PlaybackThread::preExit()
1826{
1827 ALOGV(" preExit()");
1828 // FIXME this is using hard-coded strings but in the future, this functionality will be
1829 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001830 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1831 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001832}
1833
1834// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1835sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1836 const sp<AudioFlinger::Client>& client,
1837 audio_stream_type_t streamType,
1838 uint32_t sampleRate,
1839 audio_format_t format,
1840 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001841 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001842 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001843 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001844 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001845 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001846 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001847 status_t *status,
1848 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001849{
Glenn Kasten74935e42013-12-19 08:56:45 -08001850 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001851 sp<Track> track;
1852 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001853 audio_output_flags_t outputFlags = mOutput->flags;
1854
1855 // special case for FAST flag considered OK if fast mixer is present
1856 if (hasFastMixer()) {
1857 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1858 }
1859
1860 // Check if requested flags are compatible with output stream flags
1861 if ((*flags & outputFlags) != *flags) {
1862 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1863 *flags, outputFlags);
1864 *flags = (audio_output_flags_t)(*flags & outputFlags);
1865 }
Eric Laurent81784c32012-11-19 14:55:58 -08001866
Eric Laurent81784c32012-11-19 14:55:58 -08001867 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001868 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001869 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001870 // PCM data
1871 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001872 // TODO: extract as a data library function that checks that a computationally
1873 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001874 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001875 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1876 (channelMask == AUDIO_CHANNEL_OUT_MONO
1877 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001878 // hardware sample rate
1879 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001880 // normal mixer has an associated fast mixer
1881 hasFastMixer() &&
1882 // there are sufficient fast track slots available
1883 (mFastTrackAvailMask != 0)
1884 // FIXME test that MixerThread for this fast track has a capable output HAL
1885 // FIXME add a permission test also?
1886 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001887 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1888 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001889 // read the fast track multiplier property the first time it is needed
1890 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1891 if (ok != 0) {
1892 ALOGE("%s pthread_once failed: %d", __func__, ok);
1893 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001894 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001895 }
Eric Laurent4c415062016-06-17 16:14:16 -07001896
1897 // check compatibility with audio effects.
1898 { // scope for mLock
1899 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001900 for (audio_session_t session : {
1901 AUDIO_SESSION_OUTPUT_STAGE,
1902 AUDIO_SESSION_OUTPUT_MIX,
1903 sessionId,
1904 }) {
1905 sp<EffectChain> chain = getEffectChain_l(session);
1906 if (chain.get() != nullptr) {
1907 audio_output_flags_t old = *flags;
1908 chain->checkOutputFlagCompatibility(flags);
1909 if (old != *flags) {
1910 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1911 (int)session, (int)old, (int)*flags);
1912 }
Eric Laurent4c415062016-06-17 16:14:16 -07001913 }
1914 }
1915 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001916 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001917 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1918 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001919 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001920 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1921 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001922 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001923 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001924 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001925 audio_is_linear_pcm(format),
1926 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001927 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001928 }
1929 }
1930 // For normal PCM streaming tracks, update minimum frame count.
1931 // For compatibility with AudioTrack calculation, buffer depth is forced
1932 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1933 // This is probably too conservative, but legacy application code may depend on it.
1934 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001935 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001936 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001937 // this must match AudioTrack.cpp calculateMinFrameCount().
1938 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001939 uint32_t latencyMs = 0;
1940 lStatus = mOutput->stream->getLatency(&latencyMs);
1941 if (lStatus != OK) {
1942 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1943 goto Exit;
1944 }
Eric Laurent81784c32012-11-19 14:55:58 -08001945 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1946 if (minBufCount < 2) {
1947 minBufCount = 2;
1948 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001949 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1950 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001951 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001952 minBufCount * sourceFramesNeededWithTimestretch(
1953 sampleRate, mNormalFrameCount,
1954 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001955 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001956 frameCount = minFrameCount;
1957 }
Eric Laurent81784c32012-11-19 14:55:58 -08001958 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001959 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001960
Glenn Kastenc3df8382014-03-13 15:05:25 -07001961 switch (mType) {
1962
1963 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001964 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001965 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001966 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1967 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001968 sampleRate, format, channelMask, mOutput, mFormat);
1969 lStatus = BAD_VALUE;
1970 goto Exit;
1971 }
1972 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001973 break;
1974
1975 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001976 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001977 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1978 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001979 sampleRate, format, channelMask, mOutput, mFormat);
1980 lStatus = BAD_VALUE;
1981 goto Exit;
1982 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001983 break;
1984
1985 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001986 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001987 ALOGE("createTrack_l() Bad parameter: format %#x \""
1988 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001989 format, mOutput, mFormat);
1990 lStatus = BAD_VALUE;
1991 goto Exit;
1992 }
Andy Hungcd044842014-08-07 11:04:34 -07001993 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001994 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1995 lStatus = BAD_VALUE;
1996 goto Exit;
1997 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001998 break;
1999
Eric Laurent81784c32012-11-19 14:55:58 -08002000 }
2001
2002 lStatus = initCheck();
2003 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002004 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002005 goto Exit;
2006 }
2007
2008 { // scope for mLock
2009 Mutex::Autolock _l(mLock);
2010
2011 // all tracks in same audio session must share the same routing strategy otherwise
2012 // conflicts will happen when tracks are moved from one output to another by audio policy
2013 // manager
2014 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2015 for (size_t i = 0; i < mTracks.size(); ++i) {
2016 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002017 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002018 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2019 if (sessionId == t->sessionId() && strategy != actual) {
2020 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2021 strategy, actual);
2022 lStatus = BAD_VALUE;
2023 goto Exit;
2024 }
2025 }
2026 }
2027
Glenn Kastend79072e2016-01-06 08:41:20 -08002028 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002029 channelMask, frameCount,
2030 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002031 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002032
Glenn Kasten03003332013-08-06 15:40:54 -07002033 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2034 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002035 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002036 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002037 goto Exit;
2038 }
2039 mTracks.add(track);
2040
2041 sp<EffectChain> chain = getEffectChain_l(sessionId);
2042 if (chain != 0) {
2043 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2044 track->setMainBuffer(chain->inBuffer());
2045 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2046 chain->incTrackCnt();
2047 }
2048
Eric Laurent05067782016-06-01 18:27:28 -07002049 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002050 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2051 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2052 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002053 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002054 }
2055 }
2056
2057 lStatus = NO_ERROR;
2058
2059Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002060 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002061 return track;
2062}
2063
2064uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2065{
2066 return latency;
2067}
2068
2069uint32_t AudioFlinger::PlaybackThread::latency() const
2070{
2071 Mutex::Autolock _l(mLock);
2072 return latency_l();
2073}
2074uint32_t AudioFlinger::PlaybackThread::latency_l() const
2075{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002076 uint32_t latency;
2077 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2078 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002079 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002080 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002081}
2082
2083void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2084{
2085 Mutex::Autolock _l(mLock);
2086 // Don't apply master volume in SW if our HAL can do it for us.
2087 if (mOutput && mOutput->audioHwDev &&
2088 mOutput->audioHwDev->canSetMasterVolume()) {
2089 mMasterVolume = 1.0;
2090 } else {
2091 mMasterVolume = value;
2092 }
2093}
2094
2095void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2096{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002097 if (isDuplicating()) {
2098 return;
2099 }
Eric Laurent81784c32012-11-19 14:55:58 -08002100 Mutex::Autolock _l(mLock);
2101 // Don't apply master mute in SW if our HAL can do it for us.
2102 if (mOutput && mOutput->audioHwDev &&
2103 mOutput->audioHwDev->canSetMasterMute()) {
2104 mMasterMute = false;
2105 } else {
2106 mMasterMute = muted;
2107 }
2108}
2109
2110void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2111{
2112 Mutex::Autolock _l(mLock);
2113 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002114 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002115}
2116
2117void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2118{
2119 Mutex::Autolock _l(mLock);
2120 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002121 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002122}
2123
2124float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2125{
2126 Mutex::Autolock _l(mLock);
2127 return mStreamTypes[stream].volume;
2128}
2129
2130// addTrack_l() must be called with ThreadBase::mLock held
2131status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2132{
2133 status_t status = ALREADY_EXISTS;
2134
Eric Laurent81784c32012-11-19 14:55:58 -08002135 if (mActiveTracks.indexOf(track) < 0) {
2136 // the track is newly added, make sure it fills up all its
2137 // buffers before playing. This is to ensure the client will
2138 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002139 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002140 TrackBase::track_state state = track->mState;
2141 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002142 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002143 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 mLock.lock();
2145 // abort track was stopped/paused while we released the lock
2146 if (state != track->mState) {
2147 if (status == NO_ERROR) {
2148 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002149 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002150 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002151 mLock.lock();
2152 }
2153 return INVALID_OPERATION;
2154 }
2155 // abort if start is rejected by audio policy manager
2156 if (status != NO_ERROR) {
2157 return PERMISSION_DENIED;
2158 }
2159#ifdef ADD_BATTERY_DATA
2160 // to track the speaker usage
2161 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2162#endif
2163 }
2164
Eric Laurent51716182016-02-29 18:00:56 -08002165 // set retry count for buffer fill
2166 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002167 if (track->isStopping_1()) {
2168 track->mRetryCount = kMaxTrackStopRetriesOffload;
2169 } else {
2170 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2171 }
2172 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002173 } else {
2174 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002175 track->mFillingUpStatus =
2176 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002177 }
2178
Eric Laurent81784c32012-11-19 14:55:58 -08002179 track->mResetDone = false;
2180 track->mPresentationCompleteFrames = 0;
2181 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002182 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2183 if (chain != 0) {
2184 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2185 track->sessionId());
2186 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002187 }
2188
2189 status = NO_ERROR;
2190 }
2191
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002192 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002193 return status;
2194}
2195
Eric Laurentbfb1b832013-01-07 09:53:42 -08002196bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002197{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002198 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002199 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002200 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2201 track->mState = TrackBase::STOPPED;
2202 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002203 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002204 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002205 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002206 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002207
2208 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002209}
2210
2211void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2212{
2213 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002214
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002215 String8 result;
2216 track->appendDump(result, false /* active */);
2217 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002218
Eric Laurent81784c32012-11-19 14:55:58 -08002219 mTracks.remove(track);
2220 deleteTrackName_l(track->name());
2221 // redundant as track is about to be destroyed, for dumpsys only
2222 track->mName = -1;
2223 if (track->isFastTrack()) {
2224 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002225 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002226 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2227 mFastTrackAvailMask |= 1 << index;
2228 // redundant as track is about to be destroyed, for dumpsys only
2229 track->mFastIndex = -1;
2230 }
2231 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2232 if (chain != 0) {
2233 chain->decTrackCnt();
2234 }
2235}
2236
2237String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2238{
Eric Laurent81784c32012-11-19 14:55:58 -08002239 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002240 String8 out_s8;
2241 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2242 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002243 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002244 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002247void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002248 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2249 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002250
Eric Laurent73e26b62015-04-27 16:55:58 -07002251 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002252
2253 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002254 case AUDIO_OUTPUT_OPENED:
2255 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002256 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002257 desc->mChannelMask = mChannelMask;
2258 desc->mSamplingRate = mSampleRate;
2259 desc->mFormat = mFormat;
2260 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002261 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002262 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002263 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002264 break;
2265
Eric Laurent73e26b62015-04-27 16:55:58 -07002266 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002267 default:
2268 break;
2269 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002270 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002271}
2272
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002273void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002274{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002275 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002276}
2277
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002278void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002279{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002280 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002281}
2282
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002283void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002284{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002285 mCallbackThread->setAsyncError();
2286}
2287
Eric Laurent3b4529e2013-09-05 18:09:19 -07002288void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002289{
2290 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002291 // reject out of sequence requests
2292 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2293 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002294 mWaitWorkCV.signal();
2295 }
2296}
2297
Eric Laurent3b4529e2013-09-05 18:09:19 -07002298void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299{
2300 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002301 // reject out of sequence requests
2302 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2303 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002304 mWaitWorkCV.signal();
2305 }
2306}
2307
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002308void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002309{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002310 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002311 mSampleRate = mOutput->getSampleRate();
2312 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002313 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002314 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 }
Andy Hung9a592762014-07-21 21:56:01 -07002316 if ((mType == MIXER || mType == DUPLICATING)
2317 && !isValidPcmSinkChannelMask(mChannelMask)) {
2318 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2319 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002320 }
Andy Hunge5412692014-05-16 11:25:07 -07002321 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002322
2323 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002324 status_t result = mOutput->stream->getFormat(&mHALFormat);
2325 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002326 // Get format from the shim, which will be different than the HAL format
2327 // if playing compressed audio over HDMI passthrough.
2328 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002329 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002330 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002331 }
Andy Hung6146c082014-03-18 11:56:15 -07002332 if ((mType == MIXER || mType == DUPLICATING)
2333 && !isValidPcmSinkFormat(mFormat)) {
2334 LOG_FATAL("HAL format %#x not supported for mixed output",
2335 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002336 }
Phil Burk062e67a2015-02-11 13:40:50 -08002337 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 result = mOutput->stream->getBufferSize(&mBufferSize);
2339 LOG_ALWAYS_FATAL_IF(result != OK,
2340 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002341 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002342 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002343 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002344 mFrameCount);
2345 }
2346
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002347 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2348 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002349 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002350 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 }
2352 }
2353
Eric Laurentd1f69b02014-12-15 14:33:13 -08002354 mHwSupportsPause = false;
2355 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002356 bool supportsPause = false, supportsResume = false;
2357 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2358 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002359 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002360 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002361 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002362 } else if (supportsResume) {
2363 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002364 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002365 }
2366 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002367 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2368 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2369 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002370
Andy Hungfbfc3952015-01-15 13:33:51 -08002371 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2372 // For best precision, we use float instead of the associated output
2373 // device format (typically PCM 16 bit).
2374
2375 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2376 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2377 mBufferSize = mFrameSize * mFrameCount;
2378
2379 // TODO: We currently use the associated output device channel mask and sample rate.
2380 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2381 // (if a valid mask) to avoid premature downmix.
2382 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2383 // instead of the output device sample rate to avoid loss of high frequency information.
2384 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2385 }
2386
Andy Hung09a50072014-02-27 14:30:47 -08002387 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002388 double multiplier = 1.0;
2389 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2390 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002391 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2392 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002393
Eric Laurent81784c32012-11-19 14:55:58 -08002394 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2395 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2396 maxNormalFrameCount = maxNormalFrameCount & ~15;
2397 if (maxNormalFrameCount < minNormalFrameCount) {
2398 maxNormalFrameCount = minNormalFrameCount;
2399 }
2400 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2401 if (multiplier <= 1.0) {
2402 multiplier = 1.0;
2403 } else if (multiplier <= 2.0) {
2404 if (2 * mFrameCount <= maxNormalFrameCount) {
2405 multiplier = 2.0;
2406 } else {
2407 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2408 }
2409 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002410 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002411 }
2412 }
2413 mNormalFrameCount = multiplier * mFrameCount;
2414 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002415 if (mType == MIXER || mType == DUPLICATING) {
2416 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2417 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002418 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002419 mNormalFrameCount);
2420
Andy Hung08fb1742015-05-31 23:22:10 -07002421 // Check if we want to throttle the processing to no more than 2x normal rate
2422 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002423 mThreadThrottleTimeMs = 0;
2424 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002425 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2426
Andy Hung010a1a12014-03-13 13:57:33 -07002427 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2428 // Originally this was int16_t[] array, need to remove legacy implications.
2429 free(mSinkBuffer);
2430 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002431 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2432 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2433 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002434 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002435
Andy Hung69aed5f2014-02-25 17:24:40 -08002436 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2437 // drives the output.
2438 free(mMixerBuffer);
2439 mMixerBuffer = NULL;
2440 if (mMixerBufferEnabled) {
2441 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2442 mMixerBufferSize = mNormalFrameCount * mChannelCount
2443 * audio_bytes_per_sample(mMixerBufferFormat);
2444 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2445 }
Andy Hung98ef9782014-03-04 14:46:50 -08002446 free(mEffectBuffer);
2447 mEffectBuffer = NULL;
2448 if (mEffectBufferEnabled) {
2449 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2450 mEffectBufferSize = mNormalFrameCount * mChannelCount
2451 * audio_bytes_per_sample(mEffectBufferFormat);
2452 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2453 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002454
Eric Laurent81784c32012-11-19 14:55:58 -08002455 // force reconfiguration of effect chains and engines to take new buffer size and audio
2456 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002457 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2459 // matter.
2460 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2461 Vector< sp<EffectChain> > effectChains = mEffectChains;
2462 for (size_t i = 0; i < effectChains.size(); i ++) {
2463 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2464 }
2465}
2466
2467
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002468status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002469{
2470 if (halFrames == NULL || dspFrames == NULL) {
2471 return BAD_VALUE;
2472 }
2473 Mutex::Autolock _l(mLock);
2474 if (initCheck() != NO_ERROR) {
2475 return INVALID_OPERATION;
2476 }
Andy Hung818e7a32016-02-16 18:08:07 -08002477 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002478 *halFrames = framesWritten;
2479
2480 if (isSuspended()) {
2481 // return an estimation of rendered frames when the output is suspended
2482 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002483 *dspFrames = (uint32_t)
2484 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002485 return NO_ERROR;
2486 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002487 status_t status;
2488 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002489 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002490 *dspFrames = (size_t)frames;
2491 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002492 }
2493}
2494
Eric Laurent4c415062016-06-17 16:14:16 -07002495// hasAudioSession_l() must be called with ThreadBase::mLock held
2496uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002497{
Eric Laurent81784c32012-11-19 14:55:58 -08002498 uint32_t result = 0;
2499 if (getEffectChain_l(sessionId) != 0) {
2500 result = EFFECT_SESSION;
2501 }
2502
2503 for (size_t i = 0; i < mTracks.size(); ++i) {
2504 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002505 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002506 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002507 if (track->isFastTrack()) {
2508 result |= FAST_SESSION;
2509 }
Eric Laurent81784c32012-11-19 14:55:58 -08002510 break;
2511 }
2512 }
2513
2514 return result;
2515}
2516
Glenn Kastend848eb42016-03-08 13:42:11 -08002517uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002518{
2519 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2520 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2521 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2522 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2523 }
2524 for (size_t i = 0; i < mTracks.size(); i++) {
2525 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002526 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002527 return AudioSystem::getStrategyForStream(track->streamType());
2528 }
2529 }
2530 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2531}
2532
2533
Phil Burk062e67a2015-02-11 13:40:50 -08002534AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002535{
2536 Mutex::Autolock _l(mLock);
2537 return mOutput;
2538}
2539
Phil Burk062e67a2015-02-11 13:40:50 -08002540AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002541{
2542 Mutex::Autolock _l(mLock);
2543 AudioStreamOut *output = mOutput;
2544 mOutput = NULL;
2545 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2546 // must push a NULL and wait for ack
2547 mOutputSink.clear();
2548 mPipeSink.clear();
2549 mNormalSink.clear();
2550 return output;
2551}
2552
2553// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002554sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002555{
2556 if (mOutput == NULL) {
2557 return NULL;
2558 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002559 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002560}
2561
2562uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2563{
2564 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2565}
2566
2567status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2568{
2569 if (!isValidSyncEvent(event)) {
2570 return BAD_VALUE;
2571 }
2572
2573 Mutex::Autolock _l(mLock);
2574
2575 for (size_t i = 0; i < mTracks.size(); ++i) {
2576 sp<Track> track = mTracks[i];
2577 if (event->triggerSession() == track->sessionId()) {
2578 (void) track->setSyncEvent(event);
2579 return NO_ERROR;
2580 }
2581 }
2582
2583 return NAME_NOT_FOUND;
2584}
2585
2586bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2587{
2588 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2589}
2590
2591void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2592 const Vector< sp<Track> >& tracksToRemove)
2593{
2594 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002595 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002596 for (size_t i = 0 ; i < count ; i++) {
2597 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002598 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002599 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002600 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002601#ifdef ADD_BATTERY_DATA
2602 // to track the speaker usage
2603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2604#endif
2605 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002606 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002607 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002608 }
Eric Laurent81784c32012-11-19 14:55:58 -08002609 }
2610 }
2611 }
Eric Laurent81784c32012-11-19 14:55:58 -08002612}
2613
2614void AudioFlinger::PlaybackThread::checkSilentMode_l()
2615{
2616 if (!mMasterMute) {
2617 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002618 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2619 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2620 return;
2621 }
Eric Laurent81784c32012-11-19 14:55:58 -08002622 if (property_get("ro.audio.silent", value, "0") > 0) {
2623 char *endptr;
2624 unsigned long ul = strtoul(value, &endptr, 0);
2625 if (*endptr == '\0' && ul != 0) {
2626 ALOGD("Silence is golden");
2627 // The setprop command will not allow a property to be changed after
2628 // the first time it is set, so we don't have to worry about un-muting.
2629 setMasterMute_l(true);
2630 }
2631 }
2632 }
2633}
2634
2635// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002636ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002637{
Eric Laurent81784c32012-11-19 14:55:58 -08002638 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002640 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002641
2642 // If an NBAIO sink is present, use it to write the normal mixer's submix
2643 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002644
Andy Hung010a1a12014-03-13 13:57:33 -07002645 const size_t count = mBytesRemaining / mFrameSize;
2646
Simon Wilson2d590962012-11-29 15:18:50 -08002647 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002648 // update the setpoint when AudioFlinger::mScreenState changes
2649 uint32_t screenState = AudioFlinger::mScreenState;
2650 if (screenState != mScreenState) {
2651 mScreenState = screenState;
2652 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2653 if (pipe != NULL) {
2654 pipe->setAvgFrames((mScreenState & 1) ?
2655 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2656 }
2657 }
Andy Hung010a1a12014-03-13 13:57:33 -07002658 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002659 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002660 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002661 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002662 } else {
2663 bytesWritten = framesWritten;
2664 }
2665 // otherwise use the HAL / AudioStreamOut directly
2666 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002668
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002670 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2671 mWriteAckSequence += 2;
2672 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002673 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002674 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002676 // FIXME We should have an implementation of timestamps for direct output threads.
2677 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002678 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002679
Eric Laurentbfb1b832013-01-07 09:53:42 -08002680 if (mUseAsyncWrite &&
2681 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2682 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002683 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002685 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 }
Eric Laurent81784c32012-11-19 14:55:58 -08002687 }
2688
Eric Laurent81784c32012-11-19 14:55:58 -08002689 mNumWrites++;
2690 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002691 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002692 return bytesWritten;
2693}
2694
2695void AudioFlinger::PlaybackThread::threadLoop_drain()
2696{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002697 bool supportsDrain = false;
2698 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002699 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2700 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002701 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2702 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002703 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002704 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002705 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002706 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002707 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002708 }
2709}
2710
2711void AudioFlinger::PlaybackThread::threadLoop_exit()
2712{
Eric Laurent275e8e92014-11-30 15:14:47 -08002713 {
2714 Mutex::Autolock _l(mLock);
2715 for (size_t i = 0; i < mTracks.size(); i++) {
2716 sp<Track> track = mTracks[i];
2717 track->invalidate();
2718 }
Andy Hungdae27702016-10-31 14:01:16 -07002719 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2720 // After we exit there are no more track changes sent to BatteryNotifier
2721 // because that requires an active threadLoop.
2722 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2723 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002724 }
Eric Laurent81784c32012-11-19 14:55:58 -08002725}
2726
2727/*
2728The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002729 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002730 - mActiveSleepTimeUs from activeSleepTimeUs()
2731 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002732 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2733 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002734 - maxPeriod from frame count and sample rate (MIXER only)
2735
2736The parameters that affect these derived values are:
2737 - frame count
2738 - frame size
2739 - sample rate
2740 - device type: A2DP or not
2741 - device latency
2742 - format: PCM or not
2743 - active sleep time
2744 - idle sleep time
2745*/
2746
2747void AudioFlinger::PlaybackThread::cacheParameters_l()
2748{
Andy Hung25c2dac2014-02-27 14:56:00 -08002749 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002750 mActiveSleepTimeUs = activeSleepTimeUs();
2751 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002752
2753 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2754 // truncating audio when going to standby.
2755 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2756 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2757 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2758 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2759 }
2760 }
Eric Laurent81784c32012-11-19 14:55:58 -08002761}
2762
Eric Laurent13084622016-05-17 10:51:49 -07002763bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002764{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002765 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002766 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002767 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002768 size_t size = mTracks.size();
2769 for (size_t i = 0; i < size; i++) {
2770 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002771 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002772 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002773 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002774 }
2775 }
Eric Laurent13084622016-05-17 10:51:49 -07002776 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002777}
2778
Haynes Mathew George05317d22016-05-03 16:34:26 -07002779void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2780{
2781 Mutex::Autolock _l(mLock);
2782 invalidateTracks_l(streamType);
2783}
2784
Eric Laurent81784c32012-11-19 14:55:58 -08002785status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2786{
Glenn Kastend848eb42016-03-08 13:42:11 -08002787 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002788 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2789 status_t result = EffectBufferHalInterface::mirror(
2790 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2791 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2792 &halInBuffer);
2793 if (result != OK) return result;
2794 halOutBuffer = halInBuffer;
2795 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002796
2797 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002798 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002799 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002800 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002801 if (mType != DIRECT) {
2802 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002803 status_t result = EffectBufferHalInterface::allocate(
2804 numSamples * sizeof(int16_t),
2805 &halInBuffer);
2806 if (result != OK) return result;
2807 buffer = halInBuffer->audioBuffer()->s16;
2808 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2809 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002810 }
2811
2812 // Attach all tracks with same session ID to this chain.
2813 for (size_t i = 0; i < mTracks.size(); ++i) {
2814 sp<Track> track = mTracks[i];
2815 if (session == track->sessionId()) {
2816 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2817 buffer);
2818 track->setMainBuffer(buffer);
2819 chain->incTrackCnt();
2820 }
2821 }
2822
2823 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002824 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002825 if (session == track->sessionId()) {
2826 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2827 chain->incActiveTrackCnt();
2828 }
2829 }
2830 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002831 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002832 chain->setInBuffer(halInBuffer);
2833 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002834 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002835 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002836 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2837 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002838 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002839 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // Effect chain for other sessions are inserted at beginning of effect
2842 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002843 // sessions is not important.
2844 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2845 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2846 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002847 size_t size = mEffectChains.size();
2848 size_t i = 0;
2849 for (i = 0; i < size; i++) {
2850 if (mEffectChains[i]->sessionId() < session) {
2851 break;
2852 }
2853 }
2854 mEffectChains.insertAt(chain, i);
2855 checkSuspendOnAddEffectChain_l(chain);
2856
2857 return NO_ERROR;
2858}
2859
2860size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2861{
Glenn Kastend848eb42016-03-08 13:42:11 -08002862 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002863
2864 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2865
2866 for (size_t i = 0; i < mEffectChains.size(); i++) {
2867 if (chain == mEffectChains[i]) {
2868 mEffectChains.removeAt(i);
2869 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002870 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002871 if (session == track->sessionId()) {
2872 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2873 chain.get(), session);
2874 chain->decActiveTrackCnt();
2875 }
2876 }
2877
2878 // detach all tracks with same session ID from this chain
2879 for (size_t i = 0; i < mTracks.size(); ++i) {
2880 sp<Track> track = mTracks[i];
2881 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002882 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002883 chain->decTrackCnt();
2884 }
2885 }
2886 break;
2887 }
2888 }
2889 return mEffectChains.size();
2890}
2891
2892status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002893 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002894{
2895 Mutex::Autolock _l(mLock);
2896 return attachAuxEffect_l(track, EffectId);
2897}
2898
2899status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002900 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002901{
2902 status_t status = NO_ERROR;
2903
2904 if (EffectId == 0) {
2905 track->setAuxBuffer(0, NULL);
2906 } else {
2907 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2908 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2909 if (effect != 0) {
2910 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2911 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2912 } else {
2913 status = INVALID_OPERATION;
2914 }
2915 } else {
2916 status = BAD_VALUE;
2917 }
2918 }
2919 return status;
2920}
2921
2922void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2923{
2924 for (size_t i = 0; i < mTracks.size(); ++i) {
2925 sp<Track> track = mTracks[i];
2926 if (track->auxEffectId() == effectId) {
2927 attachAuxEffect_l(track, 0);
2928 }
2929 }
2930}
2931
2932bool AudioFlinger::PlaybackThread::threadLoop()
2933{
Glenn Kasten388d5712017-04-07 14:38:41 -07002934 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002935
Eric Laurent81784c32012-11-19 14:55:58 -08002936 Vector< sp<Track> > tracksToRemove;
2937
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002938 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002939 nsecs_t lastWriteFinished = -1; // time last server write completed
2940 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002941
2942 // MIXER
2943 nsecs_t lastWarning = 0;
2944
2945 // DUPLICATING
2946 // FIXME could this be made local to while loop?
2947 writeFrames = 0;
2948
2949 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002950 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002951
2952 if (mType == MIXER) {
2953 sleepTimeShift = 0;
2954 }
2955
2956 CpuStats cpuStats;
2957 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2958
2959 acquireWakeLock();
2960
Glenn Kasteneef598c2017-04-03 14:41:13 -07002961 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2962 // thread associated with this PlaybackThread.
2963 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2964 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002965 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2966 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002967 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002968 const char *logString = NULL;
2969
rago1bb90822017-05-02 18:31:48 -07002970 // Estimated time for next buffer to be written to hal. This is used only on
2971 // suspended mode (for now) to help schedule the wait time until next iteration.
2972 nsecs_t timeLoopNextNs = 0;
2973
Eric Laurent664539d2013-09-23 18:24:31 -07002974 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002975
Eric Laurent81784c32012-11-19 14:55:58 -08002976 while (!exitPending())
2977 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002978 // Log merge requests are performed during AudioFlinger binder transactions, but
2979 // that does not cover audio playback. It's requested here for that reason.
2980 mAudioFlinger->requestLogMerge();
2981
Eric Laurent81784c32012-11-19 14:55:58 -08002982 cpuStats.sample(myName);
2983
2984 Vector< sp<EffectChain> > effectChains;
2985
Eric Laurent81784c32012-11-19 14:55:58 -08002986 { // scope for mLock
2987
2988 Mutex::Autolock _l(mLock);
2989
Eric Laurent021cf962014-05-13 10:18:14 -07002990 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002991
Glenn Kasteneef598c2017-04-03 14:41:13 -07002992 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002993 if (logString != NULL) {
2994 mNBLogWriter->logTimestamp();
2995 mNBLogWriter->log(logString);
2996 logString = NULL;
2997 }
2998
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002999 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003000 // and associate with the sink frames written out. We need
3001 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003002 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003003 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003004 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003005 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003006 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003007 ExtendedTimestamp timestamp; // use private copy to fetch
3008 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003009
3010 // We keep track of the last valid kernel position in case we are in underrun
3011 // and the normal mixer period is the same as the fast mixer period, or there
3012 // is some error from the HAL.
3013 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3014 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3016 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3017 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3018
3019 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3020 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3021 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3022 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003023 }
3024
3025 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3026 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003027 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003028 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003029 }
3030
Andy Hung818e7a32016-02-16 18:08:07 -08003031 // copy over kernel info
3032 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003033 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3034 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003035 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3036 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003037 }
3038 // mFramesWritten for non-offloaded tracks are contiguous
3039 // even after standby() is called. This is useful for the track frame
3040 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003041 bool serverLocationUpdate = false;
3042 if (mFramesWritten != lastFramesWritten) {
3043 serverLocationUpdate = true;
3044 lastFramesWritten = mFramesWritten;
3045 }
3046 // Only update timestamps if there is a meaningful change.
3047 // Either the kernel timestamp must be valid or we have written something.
3048 if (kernelLocationUpdate || serverLocationUpdate) {
3049 if (serverLocationUpdate) {
3050 // use the time before we called the HAL write - it is a bit more accurate
3051 // to when the server last read data than the current time here.
3052 //
3053 // If we haven't written anything, mLastWriteTime will be -1
3054 // and we use systemTime().
3055 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3056 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3057 ? systemTime() : mLastWriteTime;
3058 }
Andy Hungdae27702016-10-31 14:01:16 -07003059
3060 for (const sp<Track> &t : mActiveTracks) {
3061 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003062 t->updateTrackFrameInfo(
3063 t->mAudioTrackServerProxy->framesReleased(),
3064 mFramesWritten,
3065 mTimestamp);
3066 }
Andy Hunge10393e2015-06-12 13:59:33 -07003067 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003068 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003069#if 0
3070 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003071 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003072 timespec ts;
3073 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003074 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003075 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003076 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003077 }
3078 ++z;
3079#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003080 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081 if (mSignalPending) {
3082 // A signal was raised while we were unlocked
3083 mSignalPending = false;
3084 } else if (waitingAsyncCallback_l()) {
3085 if (exitPending()) {
3086 break;
3087 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003088 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003089 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003090 releaseWakeLock_l();
3091 released = true;
3092 }
Andy Hung10cbff12017-02-21 17:30:14 -08003093
3094 const int64_t waitNs = computeWaitTimeNs_l();
3095 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3096 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3097 if (status == TIMED_OUT) {
3098 mSignalPending = true; // if timeout recheck everything
3099 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003101 if (released) {
3102 acquireWakeLock_l();
3103 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003104 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3105 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003106
3107 continue;
3108 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003109 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110 isSuspended()) {
3111 // put audio hardware into standby after short delay
3112 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003113
3114 threadLoop_standby();
3115
3116 mStandby = true;
3117 }
3118
3119 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3120 // we're about to wait, flush the binder command buffer
3121 IPCThreadState::self()->flushCommands();
3122
3123 clearOutputTracks();
3124
3125 if (exitPending()) {
3126 break;
3127 }
3128
3129 releaseWakeLock_l();
3130 // wait until we have something to do...
3131 ALOGV("%s going to sleep", myName.string());
3132 mWaitWorkCV.wait(mLock);
3133 ALOGV("%s waking up", myName.string());
3134 acquireWakeLock_l();
3135
3136 mMixerStatus = MIXER_IDLE;
3137 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3138 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003139 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003140 checkSilentMode_l();
3141
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003142 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3143 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003144 if (mType == MIXER) {
3145 sleepTimeShift = 0;
3146 }
3147
3148 continue;
3149 }
3150 }
Eric Laurent81784c32012-11-19 14:55:58 -08003151 // mMixerStatusIgnoringFastTracks is also updated internally
3152 mMixerStatus = prepareTracks_l(&tracksToRemove);
3153
Andy Hungdae27702016-10-31 14:01:16 -07003154 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003155
Eric Laurent81784c32012-11-19 14:55:58 -08003156 // prevent any changes in effect chain list and in each effect chain
3157 // during mixing and effect process as the audio buffers could be deleted
3158 // or modified if an effect is created or deleted
3159 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003160 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003161
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162 if (mBytesRemaining == 0) {
3163 mCurrentWriteLength = 0;
3164 if (mMixerStatus == MIXER_TRACKS_READY) {
3165 // threadLoop_mix() sets mCurrentWriteLength
3166 threadLoop_mix();
3167 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3168 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003169 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170 // must be written to HAL
3171 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003172 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003173 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003174 }
3175 }
Andy Hung98ef9782014-03-04 14:46:50 -08003176 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003177 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003178 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3179 // or mSinkBuffer (if there are no effects).
3180 //
3181 // This is done pre-effects computation; if effects change to
3182 // support higher precision, this needs to move.
3183 //
3184 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003185 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003186 if (mMixerBufferValid) {
3187 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3188 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3189
Andy Hung2ddee192015-12-18 17:34:44 -08003190 // mono blend occurs for mixer threads only (not direct or offloaded)
3191 // and is handled here if we're going directly to the sink.
3192 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003193 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3194 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003195 }
3196
Andy Hung98ef9782014-03-04 14:46:50 -08003197 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3198 mNormalFrameCount * mChannelCount);
3199 }
3200
Eric Laurentbfb1b832013-01-07 09:53:42 -08003201 mBytesRemaining = mCurrentWriteLength;
3202 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003203 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3204 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3205 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3206 mBytesWritten += mBytesRemaining;
3207 mFramesWritten += framesRemaining;
3208 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003209 mBytesRemaining = 0;
3210 }
Eric Laurent81784c32012-11-19 14:55:58 -08003211
Eric Laurentbfb1b832013-01-07 09:53:42 -08003212 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003213 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003214 for (size_t i = 0; i < effectChains.size(); i ++) {
3215 effectChains[i]->process_l();
3216 }
Eric Laurent81784c32012-11-19 14:55:58 -08003217 }
3218 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003219 // Process effect chains for offloaded thread even if no audio
3220 // was read from audio track: process only updates effect state
3221 // and thus does have to be synchronized with audio writes but may have
3222 // to be called while waiting for async write callback
3223 if (mType == OFFLOAD) {
3224 for (size_t i = 0; i < effectChains.size(); i ++) {
3225 effectChains[i]->process_l();
3226 }
3227 }
Eric Laurent81784c32012-11-19 14:55:58 -08003228
Andy Hung98ef9782014-03-04 14:46:50 -08003229 // Only if the Effects buffer is enabled and there is data in the
3230 // Effects buffer (buffer valid), we need to
3231 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003232 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003233 if (mEffectBufferValid) {
3234 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003235
3236 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003237 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3238 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003239 }
3240
Andy Hung98ef9782014-03-04 14:46:50 -08003241 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3242 mNormalFrameCount * mChannelCount);
3243 }
3244
Eric Laurent81784c32012-11-19 14:55:58 -08003245 // enable changes in effect chain
3246 unlockEffectChains(effectChains);
3247
Eric Laurentbfb1b832013-01-07 09:53:42 -08003248 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003249 // mSleepTimeUs == 0 means we must write to audio hardware
3250 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003251 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003252 // We save lastWriteFinished here, as previousLastWriteFinished,
3253 // for throttling. On thread start, previousLastWriteFinished will be
3254 // set to -1, which properly results in no throttling after the first write.
3255 nsecs_t previousLastWriteFinished = lastWriteFinished;
3256 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003257 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003258 // FIXME rewrite to reduce number of system calls
3259 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003260 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003261 lastWriteFinished = systemTime();
3262 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003263 if (ret < 0) {
3264 mBytesRemaining = 0;
3265 } else {
3266 mBytesWritten += ret;
3267 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003268 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003269 }
3270 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3271 (mMixerStatus == MIXER_DRAIN_ALL)) {
3272 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003273 }
Andy Hung08fb1742015-05-31 23:22:10 -07003274 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003275 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003276 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003277 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003278 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003279 ATRACE_NAME("underrun");
3280 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003281 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003282 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003283 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 }
Andy Hung08fb1742015-05-31 23:22:10 -07003285
3286 if (mThreadThrottle
3287 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3288 && ret > 0) { // we wrote something
3289 // Limit MixerThread data processing to no more than twice the
3290 // expected processing rate.
3291 //
3292 // This helps prevent underruns with NuPlayer and other applications
3293 // which may set up buffers that are close to the minimum size, or use
3294 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3295 //
3296 // The throttle smooths out sudden large data drains from the device,
3297 // e.g. when it comes out of standby, which often causes problems with
3298 // (1) mixer threads without a fast mixer (which has its own warm-up)
3299 // (2) minimum buffer sized tracks (even if the track is full,
3300 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003301 //
3302 // Total time spent in last processing cycle equals time spent in
3303 // 1. threadLoop_write, as well as time spent in
3304 // 2. threadLoop_mix (significant for heavy mixing, especially
3305 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003306
Andy Hung69488c42016-05-16 18:43:33 -07003307 // it's OK if deltaMs is an overestimate.
3308 const int32_t deltaMs =
3309 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003310 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3311 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3312 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003313 // notify of throttle start on verbose log
3314 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3315 "mixer(%p) throttle begin:"
3316 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003317 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003318 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003319 // Throttle must be attributed to the previous mixer loop's write time
3320 // to allow back-to-back throttling.
3321 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003322 } else {
3323 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3324 if (diff > 0) {
3325 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003326 // but prevent spamming for bluetooth
3327 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3328 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003329 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3330 }
Andy Hung08fb1742015-05-31 23:22:10 -07003331 }
3332 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003333 }
Eric Laurent81784c32012-11-19 14:55:58 -08003334
Eric Laurentbfb1b832013-01-07 09:53:42 -08003335 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003336 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003337 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003338 // suspended requires accurate metering of sleep time.
3339 if (isSuspended()) {
3340 // advance by expected sleepTime
3341 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3342 const nsecs_t nowNs = systemTime();
3343
3344 // compute expected next time vs current time.
3345 // (negative deltas are treated as delays).
3346 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3347 if (deltaNs < -kMaxNextBufferDelayNs) {
3348 // Delays longer than the max allowed trigger a reset.
3349 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3350 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3351 timeLoopNextNs = nowNs + deltaNs;
3352 } else if (deltaNs < 0) {
3353 // Delays within the max delay allowed: zero the delta/sleepTime
3354 // to help the system catch up in the next iteration(s)
3355 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3356 deltaNs = 0;
3357 }
3358 // update sleep time (which is >= 0)
3359 mSleepTimeUs = deltaNs / 1000;
3360 }
Eric Laurente93cc032016-05-05 10:15:10 -07003361 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3362 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003363 }
Glenn Kastene7754022014-10-31 12:11:26 -07003364 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 }
Eric Laurent81784c32012-11-19 14:55:58 -08003366 }
3367
3368 // Finally let go of removed track(s), without the lock held
3369 // since we can't guarantee the destructors won't acquire that
3370 // same lock. This will also mutate and push a new fast mixer state.
3371 threadLoop_removeTracks(tracksToRemove);
3372 tracksToRemove.clear();
3373
3374 // FIXME I don't understand the need for this here;
3375 // it was in the original code but maybe the
3376 // assignment in saveOutputTracks() makes this unnecessary?
3377 clearOutputTracks();
3378
3379 // Effect chains will be actually deleted here if they were removed from
3380 // mEffectChains list during mixing or effects processing
3381 effectChains.clear();
3382
3383 // FIXME Note that the above .clear() is no longer necessary since effectChains
3384 // is now local to this block, but will keep it for now (at least until merge done).
3385 }
3386
Eric Laurentbfb1b832013-01-07 09:53:42 -08003387 threadLoop_exit();
3388
Eric Laurentcf817a22014-08-04 20:36:31 -07003389 if (!mStandby) {
3390 threadLoop_standby();
3391 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003392 }
3393
3394 releaseWakeLock();
3395
3396 ALOGV("Thread %p type %d exiting", this, mType);
3397 return false;
3398}
3399
Eric Laurentbfb1b832013-01-07 09:53:42 -08003400// removeTracks_l() must be called with ThreadBase::mLock held
3401void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3402{
3403 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003404 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003405 for (size_t i=0 ; i<count ; i++) {
3406 const sp<Track>& track = tracksToRemove.itemAt(i);
3407 mActiveTracks.remove(track);
3408 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3409 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3410 if (chain != 0) {
3411 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3412 track->sessionId());
3413 chain->decActiveTrackCnt();
3414 }
3415 if (track->isTerminated()) {
3416 removeTrack_l(track);
3417 }
3418 }
3419 }
3420
3421}
Eric Laurent81784c32012-11-19 14:55:58 -08003422
Eric Laurentaccc1472013-09-20 09:36:34 -07003423status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3424{
3425 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003426 ExtendedTimestamp ets;
3427 status_t status = mNormalSink->getTimestamp(ets);
3428 if (status == NO_ERROR) {
3429 status = ets.getBestTimestamp(&timestamp);
3430 }
3431 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003432 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003433 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003434 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003435 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003436 timestamp.mPosition = (uint32_t)position64;
3437 return NO_ERROR;
3438 }
3439 }
3440 return INVALID_OPERATION;
3441}
Eric Laurent1c333e22014-05-20 10:48:17 -07003442
Eric Laurent054d9d32015-04-24 08:48:48 -07003443status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3444 audio_patch_handle_t *handle)
3445{
Andy Hungf60abce2016-08-26 11:37:54 -07003446 status_t status;
3447 if (property_get_bool("af.patch_park", false /* default_value */)) {
3448 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3449 // or if HAL does not properly lock against access.
3450 AutoPark<FastMixer> park(mFastMixer);
3451 status = PlaybackThread::createAudioPatch_l(patch, handle);
3452 } else {
3453 status = PlaybackThread::createAudioPatch_l(patch, handle);
3454 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003455 return status;
3456}
3457
Eric Laurent1c333e22014-05-20 10:48:17 -07003458status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3459 audio_patch_handle_t *handle)
3460{
3461 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003462
3463 // store new device and send to effects
3464 audio_devices_t type = AUDIO_DEVICE_NONE;
3465 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3466 type |= patch->sinks[i].ext.device.type;
3467 }
3468
3469#ifdef ADD_BATTERY_DATA
3470 // when changing the audio output device, call addBatteryData to notify
3471 // the change
3472 if (mOutDevice != type) {
3473 uint32_t params = 0;
3474 // check whether speaker is on
3475 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3476 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003477 }
3478
Eric Laurent054d9d32015-04-24 08:48:48 -07003479 audio_devices_t deviceWithoutSpeaker
3480 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3481 // check if any other device (except speaker) is on
3482 if (type & deviceWithoutSpeaker) {
3483 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3484 }
3485
3486 if (params != 0) {
3487 addBatteryData(params);
3488 }
3489 }
3490#endif
3491
3492 for (size_t i = 0; i < mEffectChains.size(); i++) {
3493 mEffectChains[i]->setDevice_l(type);
3494 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003495
3496 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3497 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3498 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003499 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003500 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003501
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003502 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003503 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3504 status = hwDevice->createAudioPatch(patch->num_sources,
3505 patch->sources,
3506 patch->num_sinks,
3507 patch->sinks,
3508 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003509 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003510 char *address;
3511 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3512 //FIXME: we only support address on first sink with HAL version < 3.0
3513 address = audio_device_address_to_parameter(
3514 patch->sinks[0].ext.device.type,
3515 patch->sinks[0].ext.device.address);
3516 } else {
3517 address = (char *)calloc(1, 1);
3518 }
3519 AudioParameter param = AudioParameter(String8(address));
3520 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003521 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003522 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003523 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003524 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003525 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003526 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003527 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3528 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003529 return status;
3530}
3531
Eric Laurent054d9d32015-04-24 08:48:48 -07003532status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3533{
Andy Hungf60abce2016-08-26 11:37:54 -07003534 status_t status;
3535 if (property_get_bool("af.patch_park", false /* default_value */)) {
3536 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3537 // or if HAL does not properly lock against access.
3538 AutoPark<FastMixer> park(mFastMixer);
3539 status = PlaybackThread::releaseAudioPatch_l(handle);
3540 } else {
3541 status = PlaybackThread::releaseAudioPatch_l(handle);
3542 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003543 return status;
3544}
3545
Eric Laurent1c333e22014-05-20 10:48:17 -07003546status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3547{
3548 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003549
3550 mOutDevice = AUDIO_DEVICE_NONE;
3551
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003552 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003553 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3554 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003555 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003556 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003557 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003558 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003559 }
3560 return status;
3561}
3562
Eric Laurent83b88082014-06-20 18:31:16 -07003563void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3564{
3565 Mutex::Autolock _l(mLock);
3566 mTracks.add(track);
3567}
3568
3569void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3570{
3571 Mutex::Autolock _l(mLock);
3572 destroyTrack_l(track);
3573}
3574
3575void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3576{
3577 ThreadBase::getAudioPortConfig(config);
3578 config->role = AUDIO_PORT_ROLE_SOURCE;
3579 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3580 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3581}
3582
Eric Laurent81784c32012-11-19 14:55:58 -08003583// ----------------------------------------------------------------------------
3584
3585AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003586 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3587 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003588 // mAudioMixer below
3589 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003590 mFastMixerFutex(0),
3591 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003592 // mOutputSink below
3593 // mPipeSink below
3594 // mNormalSink below
3595{
3596 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003597 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3598 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003599 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3600 mNormalFrameCount);
3601 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3602
Andy Hungfbfc3952015-01-15 13:33:51 -08003603 if (type == DUPLICATING) {
3604 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3605 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3606 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3607 return;
3608 }
Eric Laurent81784c32012-11-19 14:55:58 -08003609 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003610 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003611 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003612 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003613#if !LOG_NDEBUG
3614 ssize_t index =
3615#else
3616 (void)
3617#endif
3618 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003619 ALOG_ASSERT(index == 0);
3620
3621 // initialize fast mixer depending on configuration
3622 bool initFastMixer;
3623 switch (kUseFastMixer) {
3624 case FastMixer_Never:
3625 initFastMixer = false;
3626 break;
3627 case FastMixer_Always:
3628 initFastMixer = true;
3629 break;
3630 case FastMixer_Static:
3631 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003632 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3633 // where the period is less than an experimentally determined threshold that can be
3634 // scheduled reliably with CFS. However, the BT A2DP HAL is
3635 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3636 initFastMixer = mFrameCount < mNormalFrameCount
3637 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003638 break;
3639 }
Andy Hungfda69402017-02-15 14:33:12 -08003640 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3641 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3642 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003643 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003644 audio_format_t fastMixerFormat;
3645 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3646 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3647 } else {
3648 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3649 }
3650 if (mFormat != fastMixerFormat) {
3651 // change our Sink format to accept our intermediate precision
3652 mFormat = fastMixerFormat;
3653 free(mSinkBuffer);
3654 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3655 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3656 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3657 }
Eric Laurent81784c32012-11-19 14:55:58 -08003658
3659 // create a MonoPipe to connect our submix to FastMixer
3660 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003661#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003662 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003663#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003664 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003665 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003666 format.mFormat = fastMixerFormat;
3667 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3668
Eric Laurent81784c32012-11-19 14:55:58 -08003669 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3670 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3671 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3672 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3673 const NBAIO_Format offers[1] = {format};
3674 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003675#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003676 ssize_t index =
3677#else
3678 (void)
3679#endif
3680 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003681 ALOG_ASSERT(index == 0);
3682 monoPipe->setAvgFrames((mScreenState & 1) ?
3683 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3684 mPipeSink = monoPipe;
3685
Glenn Kasten46909e72013-02-26 09:20:22 -08003686#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003687 if (mTeeSinkOutputEnabled) {
3688 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003689 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3690 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003691 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003692 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003693 ALOG_ASSERT(index == 0);
3694 mTeeSink = teeSink;
3695 PipeReader *teeSource = new PipeReader(*teeSink);
3696 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003697 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003698 ALOG_ASSERT(index == 0);
3699 mTeeSource = teeSource;
3700 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003701#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003702
3703 // create fast mixer and configure it initially with just one fast track for our submix
3704 mFastMixer = new FastMixer();
3705 FastMixerStateQueue *sq = mFastMixer->sq();
3706#ifdef STATE_QUEUE_DUMP
3707 sq->setObserverDump(&mStateQueueObserverDump);
3708 sq->setMutatorDump(&mStateQueueMutatorDump);
3709#endif
3710 FastMixerState *state = sq->begin();
3711 FastTrack *fastTrack = &state->mFastTracks[0];
3712 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3713 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3714 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003715 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3716 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003717 fastTrack->mGeneration++;
3718 state->mFastTracksGen++;
3719 state->mTrackMask = 1;
3720 // fast mixer will use the HAL output sink
3721 state->mOutputSink = mOutputSink.get();
3722 state->mOutputSinkGen++;
3723 state->mFrameCount = mFrameCount;
3724 state->mCommand = FastMixerState::COLD_IDLE;
3725 // already done in constructor initialization list
3726 //mFastMixerFutex = 0;
3727 state->mColdFutexAddr = &mFastMixerFutex;
3728 state->mColdGen++;
3729 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003730#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003731 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003732#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003733 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3734 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003735 sq->end();
3736 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3737
3738 // start the fast mixer
3739 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3740 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003741 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003742 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003743
3744#ifdef AUDIO_WATCHDOG
3745 // create and start the watchdog
3746 mAudioWatchdog = new AudioWatchdog();
3747 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3748 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3749 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003750 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003751#endif
3752
Eric Laurent81784c32012-11-19 14:55:58 -08003753 }
3754
3755 switch (kUseFastMixer) {
3756 case FastMixer_Never:
3757 case FastMixer_Dynamic:
3758 mNormalSink = mOutputSink;
3759 break;
3760 case FastMixer_Always:
3761 mNormalSink = mPipeSink;
3762 break;
3763 case FastMixer_Static:
3764 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3765 break;
3766 }
3767}
3768
3769AudioFlinger::MixerThread::~MixerThread()
3770{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003771 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003772 FastMixerStateQueue *sq = mFastMixer->sq();
3773 FastMixerState *state = sq->begin();
3774 if (state->mCommand == FastMixerState::COLD_IDLE) {
3775 int32_t old = android_atomic_inc(&mFastMixerFutex);
3776 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003777 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003778 }
3779 }
3780 state->mCommand = FastMixerState::EXIT;
3781 sq->end();
3782 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3783 mFastMixer->join();
3784 // Though the fast mixer thread has exited, it's state queue is still valid.
3785 // We'll use that extract the final state which contains one remaining fast track
3786 // corresponding to our sub-mix.
3787 state = sq->begin();
3788 ALOG_ASSERT(state->mTrackMask == 1);
3789 FastTrack *fastTrack = &state->mFastTracks[0];
3790 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3791 delete fastTrack->mBufferProvider;
3792 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003793 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003794#ifdef AUDIO_WATCHDOG
3795 if (mAudioWatchdog != 0) {
3796 mAudioWatchdog->requestExit();
3797 mAudioWatchdog->requestExitAndWait();
3798 mAudioWatchdog.clear();
3799 }
3800#endif
3801 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003802 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003803 delete mAudioMixer;
3804}
3805
3806
3807uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3808{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003809 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003810 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3811 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3812 }
3813 return latency;
3814}
3815
3816
3817void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3818{
3819 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3820}
3821
Eric Laurentbfb1b832013-01-07 09:53:42 -08003822ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003823{
3824 // FIXME we should only do one push per cycle; confirm this is true
3825 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003826 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003827 FastMixerStateQueue *sq = mFastMixer->sq();
3828 FastMixerState *state = sq->begin();
3829 if (state->mCommand != FastMixerState::MIX_WRITE &&
3830 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3831 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003832
3833 // FIXME workaround for first HAL write being CPU bound on some devices
3834 ATRACE_BEGIN("write");
3835 mOutput->write((char *)mSinkBuffer, 0);
3836 ATRACE_END();
3837
Eric Laurent81784c32012-11-19 14:55:58 -08003838 int32_t old = android_atomic_inc(&mFastMixerFutex);
3839 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003840 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003841 }
3842#ifdef AUDIO_WATCHDOG
3843 if (mAudioWatchdog != 0) {
3844 mAudioWatchdog->resume();
3845 }
3846#endif
3847 }
3848 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003849#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003850 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003851 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003852#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003853 sq->end();
3854 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3855 if (kUseFastMixer == FastMixer_Dynamic) {
3856 mNormalSink = mPipeSink;
3857 }
3858 } else {
3859 sq->end(false /*didModify*/);
3860 }
3861 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003862 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003863}
3864
3865void AudioFlinger::MixerThread::threadLoop_standby()
3866{
3867 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003868 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003869 FastMixerStateQueue *sq = mFastMixer->sq();
3870 FastMixerState *state = sq->begin();
3871 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003872 // Report any frames trapped in the Monopipe
3873 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3874 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3875 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3876 "monoPipeWritten:%lld monoPipeLeft:%lld",
3877 (long long)mFramesWritten, (long long)mSuspendedFrames,
3878 (long long)mPipeSink->framesWritten(), pipeFrames);
3879 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3880
Eric Laurent81784c32012-11-19 14:55:58 -08003881 state->mCommand = FastMixerState::COLD_IDLE;
3882 state->mColdFutexAddr = &mFastMixerFutex;
3883 state->mColdGen++;
3884 mFastMixerFutex = 0;
3885 sq->end();
3886 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3887 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3888 if (kUseFastMixer == FastMixer_Dynamic) {
3889 mNormalSink = mOutputSink;
3890 }
3891#ifdef AUDIO_WATCHDOG
3892 if (mAudioWatchdog != 0) {
3893 mAudioWatchdog->pause();
3894 }
3895#endif
3896 } else {
3897 sq->end(false /*didModify*/);
3898 }
3899 }
3900 PlaybackThread::threadLoop_standby();
3901}
3902
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3904{
3905 return false;
3906}
3907
3908bool AudioFlinger::PlaybackThread::shouldStandby_l()
3909{
3910 return !mStandby;
3911}
3912
3913bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3914{
3915 Mutex::Autolock _l(mLock);
3916 return waitingAsyncCallback_l();
3917}
3918
Eric Laurent81784c32012-11-19 14:55:58 -08003919// shared by MIXER and DIRECT, overridden by DUPLICATING
3920void AudioFlinger::PlaybackThread::threadLoop_standby()
3921{
3922 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003923 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003924 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003925 // discard any pending drain or write ack by incrementing sequence
3926 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3927 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003928 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003929 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3930 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003931 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003932 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003933}
3934
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003935void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3936{
3937 ALOGV("signal playback thread");
3938 broadcast_l();
3939}
3940
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003941void AudioFlinger::PlaybackThread::onAsyncError()
3942{
3943 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3944 invalidateTracks((audio_stream_type_t)i);
3945 }
3946}
3947
Eric Laurent81784c32012-11-19 14:55:58 -08003948void AudioFlinger::MixerThread::threadLoop_mix()
3949{
Eric Laurent81784c32012-11-19 14:55:58 -08003950 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003951 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003952 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003953 // increase sleep time progressively when application underrun condition clears.
3954 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3955 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3956 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003957 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003958 sleepTimeShift--;
3959 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003960 mSleepTimeUs = 0;
3961 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003962 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003963
Eric Laurent81784c32012-11-19 14:55:58 -08003964}
3965
3966void AudioFlinger::MixerThread::threadLoop_sleepTime()
3967{
3968 // If no tracks are ready, sleep once for the duration of an output
3969 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003970 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003971 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003972 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3973 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3974 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003975 }
3976 // reduce sleep time in case of consecutive application underruns to avoid
3977 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3978 // duration we would end up writing less data than needed by the audio HAL if
3979 // the condition persists.
3980 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3981 sleepTimeShift++;
3982 }
3983 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003984 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003985 }
3986 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003987 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3988 // before effects processing or output.
3989 if (mMixerBufferValid) {
3990 memset(mMixerBuffer, 0, mMixerBufferSize);
3991 } else {
3992 memset(mSinkBuffer, 0, mSinkBufferSize);
3993 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003994 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003995 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3996 "anticipated start");
3997 }
3998 // TODO add standby time extension fct of effect tail
3999}
4000
4001// prepareTracks_l() must be called with ThreadBase::mLock held
4002AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4003 Vector< sp<Track> > *tracksToRemove)
4004{
4005
4006 mixer_state mixerStatus = MIXER_IDLE;
4007 // find out which tracks need to be processed
4008 size_t count = mActiveTracks.size();
4009 size_t mixedTracks = 0;
4010 size_t tracksWithEffect = 0;
4011 // counts only _active_ fast tracks
4012 size_t fastTracks = 0;
4013 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4014
4015 float masterVolume = mMasterVolume;
4016 bool masterMute = mMasterMute;
4017
4018 if (masterMute) {
4019 masterVolume = 0;
4020 }
4021 // Delegate master volume control to effect in output mix effect chain if needed
4022 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4023 if (chain != 0) {
4024 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4025 chain->setVolume_l(&v, &v);
4026 masterVolume = (float)((v + (1 << 23)) >> 24);
4027 chain.clear();
4028 }
4029
4030 // prepare a new state to push
4031 FastMixerStateQueue *sq = NULL;
4032 FastMixerState *state = NULL;
4033 bool didModify = false;
4034 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004035 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004036 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004037 sq = mFastMixer->sq();
4038 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004039 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004040 }
4041
Andy Hung69aed5f2014-02-25 17:24:40 -08004042 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004043 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004044
Eric Laurent81784c32012-11-19 14:55:58 -08004045 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004046 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004047
4048 // this const just means the local variable doesn't change
4049 Track* const track = t.get();
4050
4051 // process fast tracks
4052 if (track->isFastTrack()) {
4053
4054 // It's theoretically possible (though unlikely) for a fast track to be created
4055 // and then removed within the same normal mix cycle. This is not a problem, as
4056 // the track never becomes active so it's fast mixer slot is never touched.
4057 // The converse, of removing an (active) track and then creating a new track
4058 // at the identical fast mixer slot within the same normal mix cycle,
4059 // is impossible because the slot isn't marked available until the end of each cycle.
4060 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004061 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004062 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4063 FastTrack *fastTrack = &state->mFastTracks[j];
4064
4065 // Determine whether the track is currently in underrun condition,
4066 // and whether it had a recent underrun.
4067 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4068 FastTrackUnderruns underruns = ftDump->mUnderruns;
4069 uint32_t recentFull = (underruns.mBitFields.mFull -
4070 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4071 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4072 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4073 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4074 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4075 uint32_t recentUnderruns = recentPartial + recentEmpty;
4076 track->mObservedUnderruns = underruns;
4077 // don't count underruns that occur while stopping or pausing
4078 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004079 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4080 recentUnderruns > 0) {
4081 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4082 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004083 } else {
4084 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004085 }
4086
4087 // This is similar to the state machine for normal tracks,
4088 // with a few modifications for fast tracks.
4089 bool isActive = true;
4090 switch (track->mState) {
4091 case TrackBase::STOPPING_1:
4092 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004093 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004094 track->mState = TrackBase::STOPPING_2;
4095 }
4096 break;
4097 case TrackBase::PAUSING:
4098 // ramp down is not yet implemented
4099 track->setPaused();
4100 break;
4101 case TrackBase::RESUMING:
4102 // ramp up is not yet implemented
4103 track->mState = TrackBase::ACTIVE;
4104 break;
4105 case TrackBase::ACTIVE:
4106 if (recentFull > 0 || recentPartial > 0) {
4107 // track has provided at least some frames recently: reset retry count
4108 track->mRetryCount = kMaxTrackRetries;
4109 }
4110 if (recentUnderruns == 0) {
4111 // no recent underruns: stay active
4112 break;
4113 }
4114 // there has recently been an underrun of some kind
4115 if (track->sharedBuffer() == 0) {
4116 // were any of the recent underruns "empty" (no frames available)?
4117 if (recentEmpty == 0) {
4118 // no, then ignore the partial underruns as they are allowed indefinitely
4119 break;
4120 }
4121 // there has recently been an "empty" underrun: decrement the retry counter
4122 if (--(track->mRetryCount) > 0) {
4123 break;
4124 }
4125 // indicate to client process that the track was disabled because of underrun;
4126 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004127 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004128 // remove from active list, but state remains ACTIVE [confusing but true]
4129 isActive = false;
4130 break;
4131 }
4132 // fall through
4133 case TrackBase::STOPPING_2:
4134 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004135 case TrackBase::STOPPED:
4136 case TrackBase::FLUSHED: // flush() while active
4137 // Check for presentation complete if track is inactive
4138 // We have consumed all the buffers of this track.
4139 // This would be incomplete if we auto-paused on underrun
4140 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004141 uint32_t latency = 0;
4142 status_t result = mOutput->stream->getLatency(&latency);
4143 ALOGE_IF(result != OK,
4144 "Error when retrieving output stream latency: %d", result);
4145 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004146 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004147 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4148 // track stays in active list until presentation is complete
4149 break;
4150 }
4151 }
4152 if (track->isStopping_2()) {
4153 track->mState = TrackBase::STOPPED;
4154 }
4155 if (track->isStopped()) {
4156 // Can't reset directly, as fast mixer is still polling this track
4157 // track->reset();
4158 // So instead mark this track as needing to be reset after push with ack
4159 resetMask |= 1 << i;
4160 }
4161 isActive = false;
4162 break;
4163 case TrackBase::IDLE:
4164 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004165 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004166 }
4167
4168 if (isActive) {
4169 // was it previously inactive?
4170 if (!(state->mTrackMask & (1 << j))) {
4171 ExtendedAudioBufferProvider *eabp = track;
4172 VolumeProvider *vp = track;
4173 fastTrack->mBufferProvider = eabp;
4174 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004175 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004176 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004177 fastTrack->mGeneration++;
4178 state->mTrackMask |= 1 << j;
4179 didModify = true;
4180 // no acknowledgement required for newly active tracks
4181 }
4182 // cache the combined master volume and stream type volume for fast mixer; this
4183 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004184 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004185 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004186 track->mCachedVolume = masterVolume
4187 * mStreamTypes[track->streamType()].volume
4188 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004189 ++fastTracks;
4190 } else {
4191 // was it previously active?
4192 if (state->mTrackMask & (1 << j)) {
4193 fastTrack->mBufferProvider = NULL;
4194 fastTrack->mGeneration++;
4195 state->mTrackMask &= ~(1 << j);
4196 didModify = true;
4197 // If any fast tracks were removed, we must wait for acknowledgement
4198 // because we're about to decrement the last sp<> on those tracks.
4199 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4200 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004201 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4202 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4203 j, track->mState, state->mTrackMask, recentUnderruns,
4204 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004205 }
4206 tracksToRemove->add(track);
4207 // Avoids a misleading display in dumpsys
4208 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4209 }
4210 continue;
4211 }
4212
4213 { // local variable scope to avoid goto warning
4214
4215 audio_track_cblk_t* cblk = track->cblk();
4216
4217 // The first time a track is added we wait
4218 // for all its buffers to be filled before processing it
4219 int name = track->name();
4220 // make sure that we have enough frames to mix one full buffer.
4221 // enforce this condition only once to enable draining the buffer in case the client
4222 // app does not call stop() and relies on underrun to stop:
4223 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4224 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004225 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004226 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004227 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004228
4229 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004230 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004231 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4232 // add frames already consumed but not yet released by the resampler
4233 // because mAudioTrackServerProxy->framesReady() will include these frames
4234 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4235
Eric Laurent81784c32012-11-19 14:55:58 -08004236 uint32_t minFrames = 1;
4237 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4238 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004239 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004240 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004241
4242 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004243 if (ATRACE_ENABLED()) {
4244 // I wish we had formatted trace names
4245 char traceName[16];
4246 strcpy(traceName, "nRdy");
4247 int name = track->name();
4248 if (AudioMixer::TRACK0 <= name &&
4249 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4250 name -= AudioMixer::TRACK0;
4251 traceName[4] = (name / 10) + '0';
4252 traceName[5] = (name % 10) + '0';
4253 } else {
4254 traceName[4] = '?';
4255 traceName[5] = '?';
4256 }
4257 traceName[6] = '\0';
4258 ATRACE_INT(traceName, framesReady);
4259 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004260 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004261 !track->isPaused() && !track->isTerminated())
4262 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004263 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004264
4265 mixedTracks++;
4266
Andy Hung69aed5f2014-02-25 17:24:40 -08004267 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4268 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004269 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004270 if (track->mainBuffer() != mSinkBuffer &&
4271 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004272 if (mEffectBufferEnabled) {
4273 mEffectBufferValid = true; // Later can set directly.
4274 }
Eric Laurent81784c32012-11-19 14:55:58 -08004275 chain = getEffectChain_l(track->sessionId());
4276 // Delegate volume control to effect in track effect chain if needed
4277 if (chain != 0) {
4278 tracksWithEffect++;
4279 } else {
4280 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4281 "session %d",
4282 name, track->sessionId());
4283 }
4284 }
4285
4286
4287 int param = AudioMixer::VOLUME;
4288 if (track->mFillingUpStatus == Track::FS_FILLED) {
4289 // no ramp for the first volume setting
4290 track->mFillingUpStatus = Track::FS_ACTIVE;
4291 if (track->mState == TrackBase::RESUMING) {
4292 track->mState = TrackBase::ACTIVE;
4293 param = AudioMixer::RAMP_VOLUME;
4294 }
4295 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004296 // FIXME should not make a decision based on mServer
4297 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004298 // If the track is stopped before the first frame was mixed,
4299 // do not apply ramp
4300 param = AudioMixer::RAMP_VOLUME;
4301 }
4302
4303 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004304 uint32_t vl, vr; // in U8.24 integer format
4305 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004306 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004307 vl = vr = 0;
4308 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004309 if (track->isPausing()) {
4310 track->setPaused();
4311 }
4312 } else {
4313
4314 // read original volumes with volume control
4315 float typeVolume = mStreamTypes[track->streamType()].volume;
4316 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004317 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004318 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004319 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4320 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004321 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004322 if (vlf > GAIN_FLOAT_UNITY) {
4323 ALOGV("Track left volume out of range: %.3g", vlf);
4324 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004325 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004326 if (vrf > GAIN_FLOAT_UNITY) {
4327 ALOGV("Track right volume out of range: %.3g", vrf);
4328 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004329 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004330 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004331 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004332 // now apply the master volume and stream type volume and shaper volume
4333 vlf *= v * vh;
4334 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004335 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004336 // then derive vl and vr as U8.24 versions for the effect chain
4337 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4338 vl = (uint32_t) (scaleto8_24 * vlf);
4339 vr = (uint32_t) (scaleto8_24 * vrf);
4340 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004341 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004342 // send level comes from shared memory and so may be corrupt
4343 if (sendLevel > MAX_GAIN_INT) {
4344 ALOGV("Track send level out of range: %04X", sendLevel);
4345 sendLevel = MAX_GAIN_INT;
4346 }
Andy Hung6be49402014-05-30 10:42:03 -07004347 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4348 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004349 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004350
Eric Laurent81784c32012-11-19 14:55:58 -08004351 // Delegate volume control to effect in track effect chain if needed
4352 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4353 // Do not ramp volume if volume is controlled by effect
4354 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004355 // Update remaining floating point volume levels
4356 vlf = (float)vl / (1 << 24);
4357 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004358 track->mHasVolumeController = true;
4359 } else {
4360 // force no volume ramp when volume controller was just disabled or removed
4361 // from effect chain to avoid volume spike
4362 if (track->mHasVolumeController) {
4363 param = AudioMixer::VOLUME;
4364 }
4365 track->mHasVolumeController = false;
4366 }
4367
Eric Laurent81784c32012-11-19 14:55:58 -08004368 // XXX: these things DON'T need to be done each time
4369 mAudioMixer->setBufferProvider(name, track);
4370 mAudioMixer->enable(name);
4371
Andy Hung6be49402014-05-30 10:42:03 -07004372 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4373 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4374 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004375 mAudioMixer->setParameter(
4376 name,
4377 AudioMixer::TRACK,
4378 AudioMixer::FORMAT, (void *)track->format());
4379 mAudioMixer->setParameter(
4380 name,
4381 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004382 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004383 mAudioMixer->setParameter(
4384 name,
4385 AudioMixer::TRACK,
4386 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004387 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004388 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004389 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004390 if (reqSampleRate == 0) {
4391 reqSampleRate = mSampleRate;
4392 } else if (reqSampleRate > maxSampleRate) {
4393 reqSampleRate = maxSampleRate;
4394 }
Eric Laurent81784c32012-11-19 14:55:58 -08004395 mAudioMixer->setParameter(
4396 name,
4397 AudioMixer::RESAMPLE,
4398 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004399 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004400
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004401 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004402 mAudioMixer->setParameter(
4403 name,
4404 AudioMixer::TIMESTRETCH,
4405 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004406 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004407
Andy Hung69aed5f2014-02-25 17:24:40 -08004408 /*
4409 * Select the appropriate output buffer for the track.
4410 *
Andy Hung98ef9782014-03-04 14:46:50 -08004411 * Tracks with effects go into their own effects chain buffer
4412 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004413 *
4414 * Other tracks can use mMixerBuffer for higher precision
4415 * channel accumulation. If this buffer is enabled
4416 * (mMixerBufferEnabled true), then selected tracks will accumulate
4417 * into it.
4418 *
4419 */
4420 if (mMixerBufferEnabled
4421 && (track->mainBuffer() == mSinkBuffer
4422 || track->mainBuffer() == mMixerBuffer)) {
4423 mAudioMixer->setParameter(
4424 name,
4425 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004426 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004427 mAudioMixer->setParameter(
4428 name,
4429 AudioMixer::TRACK,
4430 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4431 // TODO: override track->mainBuffer()?
4432 mMixerBufferValid = true;
4433 } else {
4434 mAudioMixer->setParameter(
4435 name,
4436 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004437 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004438 mAudioMixer->setParameter(
4439 name,
4440 AudioMixer::TRACK,
4441 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4442 }
Eric Laurent81784c32012-11-19 14:55:58 -08004443 mAudioMixer->setParameter(
4444 name,
4445 AudioMixer::TRACK,
4446 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4447
4448 // reset retry count
4449 track->mRetryCount = kMaxTrackRetries;
4450
4451 // If one track is ready, set the mixer ready if:
4452 // - the mixer was not ready during previous round OR
4453 // - no other track is not ready
4454 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4455 mixerStatus != MIXER_TRACKS_ENABLED) {
4456 mixerStatus = MIXER_TRACKS_READY;
4457 }
4458 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004459 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004460 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4461 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004462 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004463 } else {
4464 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004465 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004466
Eric Laurent81784c32012-11-19 14:55:58 -08004467 // clear effect chain input buffer if an active track underruns to avoid sending
4468 // previous audio buffer again to effects
4469 chain = getEffectChain_l(track->sessionId());
4470 if (chain != 0) {
4471 chain->clearInputBuffer();
4472 }
4473
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004474 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004475 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4476 track->isStopped() || track->isPaused()) {
4477 // We have consumed all the buffers of this track.
4478 // Remove it from the list of active tracks.
4479 // TODO: use actual buffer filling status instead of latency when available from
4480 // audio HAL
4481 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004482 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004483 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4484 if (track->isStopped()) {
4485 track->reset();
4486 }
4487 tracksToRemove->add(track);
4488 }
4489 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004490 // No buffers for this track. Give it a few chances to
4491 // fill a buffer, then remove it from active list.
4492 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004493 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004494 tracksToRemove->add(track);
4495 // indicate to client process that the track was disabled because of underrun;
4496 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004497 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004498 // If one track is not ready, mark the mixer also not ready if:
4499 // - the mixer was ready during previous round OR
4500 // - no other track is ready
4501 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4502 mixerStatus != MIXER_TRACKS_READY) {
4503 mixerStatus = MIXER_TRACKS_ENABLED;
4504 }
4505 }
4506 mAudioMixer->disable(name);
4507 }
4508
4509 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004510
4511 }
4512
4513 // Push the new FastMixer state if necessary
4514 bool pauseAudioWatchdog = false;
4515 if (didModify) {
4516 state->mFastTracksGen++;
4517 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4518 if (kUseFastMixer == FastMixer_Dynamic &&
4519 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4520 state->mCommand = FastMixerState::COLD_IDLE;
4521 state->mColdFutexAddr = &mFastMixerFutex;
4522 state->mColdGen++;
4523 mFastMixerFutex = 0;
4524 if (kUseFastMixer == FastMixer_Dynamic) {
4525 mNormalSink = mOutputSink;
4526 }
4527 // If we go into cold idle, need to wait for acknowledgement
4528 // so that fast mixer stops doing I/O.
4529 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4530 pauseAudioWatchdog = true;
4531 }
Eric Laurent81784c32012-11-19 14:55:58 -08004532 }
4533 if (sq != NULL) {
4534 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004535 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4536 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4537 // when bringing the output sink into standby.)
4538 //
4539 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4540 //
4541 // This occurs with BT suspend when we idle the FastMixer with
4542 // active tracks, which may be added or removed.
4543 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004544 }
4545#ifdef AUDIO_WATCHDOG
4546 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4547 mAudioWatchdog->pause();
4548 }
4549#endif
4550
4551 // Now perform the deferred reset on fast tracks that have stopped
4552 while (resetMask != 0) {
4553 size_t i = __builtin_ctz(resetMask);
4554 ALOG_ASSERT(i < count);
4555 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004556 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004557 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4558 track->reset();
4559 }
4560
4561 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004562 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004563
Eric Laurent97d547d2014-09-02 14:45:53 -07004564 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4565 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004566 }
4567
4568 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004569 // as long as there are effects we should clear the effects buffer, to avoid
4570 // passing a non-clean buffer to the effect chain
4571 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004572 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004573 // sink or mix buffer must be cleared if all tracks are connected to an
4574 // effect chain as in this case the mixer will not write to the sink or mix buffer
4575 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004576 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4577 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004578 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004579 if (mMixerBufferValid) {
4580 memset(mMixerBuffer, 0, mMixerBufferSize);
4581 // TODO: In testing, mSinkBuffer below need not be cleared because
4582 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4583 // after mixing.
4584 //
4585 // To enforce this guarantee:
4586 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4587 // (mixedTracks == 0 && fastTracks > 0))
4588 // must imply MIXER_TRACKS_READY.
4589 // Later, we may clear buffers regardless, and skip much of this logic.
4590 }
Andy Hung98ef9782014-03-04 14:46:50 -08004591 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004592 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004593 }
4594
4595 // if any fast tracks, then status is ready
4596 mMixerStatusIgnoringFastTracks = mixerStatus;
4597 if (fastTracks > 0) {
4598 mixerStatus = MIXER_TRACKS_READY;
4599 }
4600 return mixerStatus;
4601}
4602
Eric Laurentad7dd962016-09-22 12:38:37 -07004603// trackCountForUid_l() must be called with ThreadBase::mLock held
4604uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4605{
4606 uint32_t trackCount = 0;
4607 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004608 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004609 trackCount++;
4610 }
4611 }
4612 return trackCount;
4613}
4614
Eric Laurent81784c32012-11-19 14:55:58 -08004615// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004616int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004617 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004618{
Eric Laurentad7dd962016-09-22 12:38:37 -07004619 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4620 return -1;
4621 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004622 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004623}
4624
4625// deleteTrackName_l() must be called with ThreadBase::mLock held
4626void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4627{
4628 ALOGV("remove track (%d) and delete from mixer", name);
4629 mAudioMixer->deleteTrackName(name);
4630}
4631
Eric Laurent10351942014-05-08 18:49:52 -07004632// checkForNewParameter_l() must be called with ThreadBase::mLock held
4633bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4634 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004635{
Eric Laurent81784c32012-11-19 14:55:58 -08004636 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004637 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004638
Eric Laurent10351942014-05-08 18:49:52 -07004639 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004640
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004641 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004642
Eric Laurent10351942014-05-08 18:49:52 -07004643 AudioParameter param = AudioParameter(keyValuePair);
4644 int value;
4645 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4646 reconfig = true;
4647 }
4648 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004649 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004650 status = BAD_VALUE;
4651 } else {
4652 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004653 reconfig = true;
4654 }
Eric Laurent10351942014-05-08 18:49:52 -07004655 }
4656 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004657 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004658 status = BAD_VALUE;
4659 } else {
4660 // no need to save value, since it's constant
4661 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004662 }
Eric Laurent10351942014-05-08 18:49:52 -07004663 }
4664 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4665 // do not accept frame count changes if tracks are open as the track buffer
4666 // size depends on frame count and correct behavior would not be guaranteed
4667 // if frame count is changed after track creation
4668 if (!mTracks.isEmpty()) {
4669 status = INVALID_OPERATION;
4670 } else {
4671 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004672 }
Eric Laurent10351942014-05-08 18:49:52 -07004673 }
4674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004675#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004676 // when changing the audio output device, call addBatteryData to notify
4677 // the change
4678 if (mOutDevice != value) {
4679 uint32_t params = 0;
4680 // check whether speaker is on
4681 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4682 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004683 }
Eric Laurent10351942014-05-08 18:49:52 -07004684
4685 audio_devices_t deviceWithoutSpeaker
4686 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4687 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004688 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004689 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4690 }
4691
4692 if (params != 0) {
4693 addBatteryData(params);
4694 }
4695 }
Eric Laurent81784c32012-11-19 14:55:58 -08004696#endif
4697
Eric Laurent10351942014-05-08 18:49:52 -07004698 // forward device change to effects that have requested to be
4699 // aware of attached audio device.
4700 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004701 a2dpDeviceChanged =
4702 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004703 mOutDevice = value;
4704 for (size_t i = 0; i < mEffectChains.size(); i++) {
4705 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004706 }
4707 }
Eric Laurent10351942014-05-08 18:49:52 -07004708 }
Eric Laurent81784c32012-11-19 14:55:58 -08004709
Eric Laurent10351942014-05-08 18:49:52 -07004710 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004711 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004712 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004713 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004714 mStandby = true;
4715 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004716 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004717 }
Eric Laurent10351942014-05-08 18:49:52 -07004718 if (status == NO_ERROR && reconfig) {
4719 readOutputParameters_l();
4720 delete mAudioMixer;
4721 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4722 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004723 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004724 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004725 if (name < 0) {
4726 break;
4727 }
4728 mTracks[i]->mName = name;
4729 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004730 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004731 }
Eric Laurent81784c32012-11-19 14:55:58 -08004732 }
4733
Eric Laurent42537be2016-01-08 17:16:42 -08004734 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004735}
4736
4737
4738void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4739{
Eric Laurent81784c32012-11-19 14:55:58 -08004740 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004741 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004742 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004743 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004744
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004745 if (hasFastMixer()) {
4746 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4747
4748 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4749 // while we are dumping it. It may be inconsistent, but it won't mutate!
4750 // This is a large object so we place it on the heap.
4751 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4752 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4753 copy->dump(fd);
4754 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004755
4756#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004757 // Similar for state queue
4758 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4759 observerCopy.dump(fd);
4760 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4761 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004762#endif
4763
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004764#ifdef AUDIO_WATCHDOG
4765 if (mAudioWatchdog != 0) {
4766 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4767 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4768 wdCopy.dump(fd);
4769 }
4770#endif
4771
4772 } else {
4773 dprintf(fd, " No FastMixer\n");
4774 }
4775
Glenn Kasten46909e72013-02-26 09:20:22 -08004776#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004777 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004778 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004779#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004780
Eric Laurent81784c32012-11-19 14:55:58 -08004781}
4782
4783uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4784{
4785 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4786}
4787
4788uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4789{
4790 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4791}
4792
4793void AudioFlinger::MixerThread::cacheParameters_l()
4794{
4795 PlaybackThread::cacheParameters_l();
4796
4797 // FIXME: Relaxed timing because of a certain device that can't meet latency
4798 // Should be reduced to 2x after the vendor fixes the driver issue
4799 // increase threshold again due to low power audio mode. The way this warning
4800 // threshold is calculated and its usefulness should be reconsidered anyway.
4801 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4802}
4803
4804// ----------------------------------------------------------------------------
4805
4806AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004807 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4808 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004809 // mLeftVolFloat, mRightVolFloat
4810{
4811}
4812
Eric Laurentbfb1b832013-01-07 09:53:42 -08004813AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4814 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004815 ThreadBase::type_t type, bool systemReady)
4816 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004817 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004818 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819{
4820}
4821
Eric Laurent81784c32012-11-19 14:55:58 -08004822AudioFlinger::DirectOutputThread::~DirectOutputThread()
4823{
4824}
4825
Eric Laurent5850c4c2016-11-10 13:04:31 -08004826void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004827{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004828 float left, right;
4829
4830 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4831 left = right = 0;
4832 } else {
4833 float typeVolume = mStreamTypes[track->streamType()].volume;
4834 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004835 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004836
Andy Hung10cbff12017-02-21 17:30:14 -08004837 // Get volumeshaper scaling
4838 std::pair<float /* volume */, bool /* active */>
4839 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004840 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004841 v *= vh.first;
4842 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004843
Glenn Kastenc56f3422014-03-21 17:53:17 -07004844 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4845 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4846 if (left > GAIN_FLOAT_UNITY) {
4847 left = GAIN_FLOAT_UNITY;
4848 }
4849 left *= v;
4850 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4851 if (right > GAIN_FLOAT_UNITY) {
4852 right = GAIN_FLOAT_UNITY;
4853 }
4854 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004855 }
4856
4857 if (lastTrack) {
4858 if (left != mLeftVolFloat || right != mRightVolFloat) {
4859 mLeftVolFloat = left;
4860 mRightVolFloat = right;
4861
4862 // Convert volumes from float to 8.24
4863 uint32_t vl = (uint32_t)(left * (1 << 24));
4864 uint32_t vr = (uint32_t)(right * (1 << 24));
4865
4866 // Delegate volume control to effect in track effect chain if needed
4867 // only one effect chain can be present on DirectOutputThread, so if
4868 // there is one, the track is connected to it
4869 if (!mEffectChains.isEmpty()) {
4870 mEffectChains[0]->setVolume_l(&vl, &vr);
4871 left = (float)vl / (1 << 24);
4872 right = (float)vr / (1 << 24);
4873 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004874 status_t result = mOutput->stream->setVolume(left, right);
4875 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004876 }
4877 }
4878}
4879
Phil Burk43b4dcc2015-06-09 16:53:44 -07004880void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4881{
4882 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004883 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004884
Eric Laurent0f0631e2015-07-06 18:01:25 -07004885 if (previousTrack != 0 && latestTrack != 0) {
4886 if (mType == DIRECT) {
4887 if (previousTrack.get() != latestTrack.get()) {
4888 mFlushPending = true;
4889 }
4890 } else /* mType == OFFLOAD */ {
4891 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4892 mFlushPending = true;
4893 }
4894 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004895 }
4896 PlaybackThread::onAddNewTrack_l();
4897}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004898
Eric Laurent81784c32012-11-19 14:55:58 -08004899AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4900 Vector< sp<Track> > *tracksToRemove
4901)
4902{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004903 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004904 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004905 bool doHwPause = false;
4906 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004907
4908 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004909 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004910 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004911 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004912 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004913 continue;
4914 }
4915
Eric Laurent5850c4c2016-11-10 13:04:31 -08004916 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004917#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004918 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004919#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004920 // Only consider last track started for volume and mixer state control.
4921 // In theory an older track could underrun and restart after the new one starts
4922 // but as we only care about the transition phase between two tracks on a
4923 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004924 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004925 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004926
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004927 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004928 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004929 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004930 doHwPause = true;
4931 mHwPaused = true;
4932 }
4933 tracksToRemove->add(track);
4934 } else if (track->isFlushPending()) {
4935 track->flushAck();
4936 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004937 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004938 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004939 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004941 if (last) {
4942 mLeftVolFloat = mRightVolFloat = -1.0;
4943 if (mHwPaused) {
4944 doHwResume = true;
4945 mHwPaused = false;
4946 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004947 }
4948 }
4949
Eric Laurent81784c32012-11-19 14:55:58 -08004950 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004951 // for all its buffers to be filled before processing it.
4952 // Allow draining the buffer in case the client
4953 // app does not call stop() and relies on underrun to stop:
4954 // hence the test on (track->mRetryCount > 1).
4955 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004956 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004957 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004958 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004959 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004960 minFrames = mNormalFrameCount;
4961 } else {
4962 minFrames = 1;
4963 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004964
Eric Laurentab5cdba2014-06-09 17:22:27 -07004965 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4966 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004967 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004968 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004969
4970 if (track->mFillingUpStatus == Track::FS_FILLED) {
4971 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004972 if (last) {
4973 // make sure processVolume_l() will apply new volume even if 0
4974 mLeftVolFloat = mRightVolFloat = -1.0;
4975 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004976 if (!mHwSupportsPause) {
4977 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004978 }
4979 }
4980
4981 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004982 processVolume_l(track, last);
4983 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004984 sp<Track> previousTrack = mPreviousTrack.promote();
4985 if (previousTrack != 0) {
4986 if (track != previousTrack.get()) {
4987 // Flush any data still being written from last track
4988 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004989 // Invalidate previous track to force a seek when resuming.
4990 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004991 }
4992 }
4993 mPreviousTrack = track;
4994
Eric Laurentd595b7c2013-04-03 17:27:56 -07004995 // reset retry count
4996 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004997 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07004998 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07004999 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005000 doHwResume = true;
5001 mHwPaused = false;
5002 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005003 }
Eric Laurent81784c32012-11-19 14:55:58 -08005004 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005005 // clear effect chain input buffer if the last active track started underruns
5006 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005007 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005008 mEffectChains[0]->clearInputBuffer();
5009 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005010 if (track->isStopping_1()) {
5011 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005012 if (last && mHwPaused) {
5013 doHwResume = true;
5014 mHwPaused = false;
5015 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005016 }
5017 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5018 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005019 // We have consumed all the buffers of this track.
5020 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005021 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005022 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005023 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5024 } else {
5025 audioHALFrames = 0;
5026 }
5027
Andy Hung818e7a32016-02-16 18:08:07 -08005028 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005029 if (mStandby || !last ||
5030 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005031 if (track->isStopping_2()) {
5032 track->mState = TrackBase::STOPPED;
5033 }
Eric Laurent81784c32012-11-19 14:55:58 -08005034 if (track->isStopped()) {
5035 track->reset();
5036 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005037 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005038 }
5039 } else {
5040 // No buffers for this track. Give it a few chances to
5041 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005042 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005043 if (--(track->mRetryCount) <= 0) {
5044 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005045 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005046 // indicate to client process that the track was disabled because of underrun;
5047 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005048 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005049 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005050 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5051 "minFrames = %u, mFormat = %#x",
5052 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005053 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005054 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005055 doHwPause = true;
5056 mHwPaused = true;
5057 }
Eric Laurent81784c32012-11-19 14:55:58 -08005058 }
5059 }
5060 }
5061 }
5062
Eric Laurentd1f69b02014-12-15 14:33:13 -08005063 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005064 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065 for (size_t i = 0; i < mTracks.size(); i++) {
5066 if (mTracks[i]->isFlushPending()) {
5067 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005068 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005069 }
5070 }
5071 }
5072
5073 // make sure the pause/flush/resume sequence is executed in the right order.
5074 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5075 // before flush and then resume HW. This can happen in case of pause/flush/resume
5076 // if resume is received before pause is executed.
5077 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005078 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005079 status_t result = mOutput->stream->pause();
5080 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005081 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005082 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005083 flushHw_l();
5084 }
5085 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005086 status_t result = mOutput->stream->resume();
5087 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005088 }
Eric Laurent81784c32012-11-19 14:55:58 -08005089 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005090 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005091
5092 return mixerStatus;
5093}
5094
5095void AudioFlinger::DirectOutputThread::threadLoop_mix()
5096{
Eric Laurent81784c32012-11-19 14:55:58 -08005097 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005098 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005099 // output audio to hardware
5100 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005101 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005102 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005103 status_t status = mActiveTrack->getNextBuffer(&buffer);
5104 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005105 // no need to pad with 0 for compressed audio
5106 if (audio_has_proportional_frames(mFormat)) {
5107 memset(curBuf, 0, frameCount * mFrameSize);
5108 }
Eric Laurent81784c32012-11-19 14:55:58 -08005109 break;
5110 }
5111 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5112 frameCount -= buffer.frameCount;
5113 curBuf += buffer.frameCount * mFrameSize;
5114 mActiveTrack->releaseBuffer(&buffer);
5115 }
Andy Hung2098f272014-02-27 14:00:06 -08005116 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005117 mSleepTimeUs = 0;
5118 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005119 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005120}
5121
5122void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5123{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005124 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005125 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005126 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005127 return;
5128 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005129 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005130 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005131 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005132 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005133 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005134 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005135 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005136 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005137 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005138 }
5139}
5140
Eric Laurentd1f69b02014-12-15 14:33:13 -08005141void AudioFlinger::DirectOutputThread::threadLoop_exit()
5142{
5143 {
5144 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005145 for (size_t i = 0; i < mTracks.size(); i++) {
5146 if (mTracks[i]->isFlushPending()) {
5147 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005148 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005149 }
5150 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005151 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005152 flushHw_l();
5153 }
5154 }
5155 PlaybackThread::threadLoop_exit();
5156}
5157
5158// must be called with thread mutex locked
5159bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5160{
5161 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005162 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005163
vivek mehta9cd7ad12016-03-17 00:18:29 -07005164 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5165 return !mStandby;
5166 }
5167
Eric Laurentd1f69b02014-12-15 14:33:13 -08005168 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5169 // after a timeout and we will enter standby then.
5170 if (mTracks.size() > 0) {
5171 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005172 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5173 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005174 }
5175
Eric Laurent5cff4032015-05-26 13:49:58 -07005176 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005177}
5178
Eric Laurent81784c32012-11-19 14:55:58 -08005179// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005180int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005181 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005182{
Eric Laurentad7dd962016-09-22 12:38:37 -07005183 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5184 return -1;
5185 }
Eric Laurent81784c32012-11-19 14:55:58 -08005186 return 0;
5187}
5188
5189// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005190void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005191{
5192}
5193
Eric Laurent10351942014-05-08 18:49:52 -07005194// checkForNewParameter_l() must be called with ThreadBase::mLock held
5195bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5196 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005197{
5198 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005199 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005200
Eric Laurent10351942014-05-08 18:49:52 -07005201 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005202
Eric Laurent10351942014-05-08 18:49:52 -07005203 AudioParameter param = AudioParameter(keyValuePair);
5204 int value;
5205 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5206 // forward device change to effects that have requested to be
5207 // aware of attached audio device.
5208 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005209 a2dpDeviceChanged =
5210 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005211 mOutDevice = value;
5212 for (size_t i = 0; i < mEffectChains.size(); i++) {
5213 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005214 }
5215 }
Eric Laurent81784c32012-11-19 14:55:58 -08005216 }
Eric Laurent10351942014-05-08 18:49:52 -07005217 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5218 // do not accept frame count changes if tracks are open as the track buffer
5219 // size depends on frame count and correct behavior would not be garantied
5220 // if frame count is changed after track creation
5221 if (!mTracks.isEmpty()) {
5222 status = INVALID_OPERATION;
5223 } else {
5224 reconfig = true;
5225 }
5226 }
5227 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005228 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005229 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005230 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005231 mStandby = true;
5232 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005233 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005234 }
5235 if (status == NO_ERROR && reconfig) {
5236 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005237 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005238 }
5239 }
5240
Eric Laurent42537be2016-01-08 17:16:42 -08005241 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005242}
5243
5244uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5245{
5246 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005247 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005248 time = PlaybackThread::activeSleepTimeUs();
5249 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005250 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005251 }
5252 return time;
5253}
5254
5255uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5256{
5257 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005258 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005259 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5260 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005261 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005262 }
5263 return time;
5264}
5265
5266uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5267{
5268 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005269 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005270 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5271 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005272 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005273 }
5274 return time;
5275}
5276
5277void AudioFlinger::DirectOutputThread::cacheParameters_l()
5278{
5279 PlaybackThread::cacheParameters_l();
5280
5281 // use shorter standby delay as on normal output to release
5282 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005283 // no delay on outputs with HW A/V sync
5284 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005285 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005286 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005287 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005288 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005289 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005290 }
Eric Laurent81784c32012-11-19 14:55:58 -08005291}
5292
Eric Laurente659ef42014-09-29 13:06:46 -07005293void AudioFlinger::DirectOutputThread::flushHw_l()
5294{
Phil Burk062e67a2015-02-11 13:40:50 -08005295 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005296 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005297 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005298}
5299
Andy Hung10cbff12017-02-21 17:30:14 -08005300int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5301 // If a VolumeShaper is active, we must wake up periodically to update volume.
5302 const int64_t NS_PER_MS = 1000000;
5303 return mVolumeShaperActive ?
5304 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5305}
5306
Eric Laurent81784c32012-11-19 14:55:58 -08005307// ----------------------------------------------------------------------------
5308
Eric Laurentbfb1b832013-01-07 09:53:42 -08005309AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005310 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005312 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005313 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005314 mDrainSequence(0),
5315 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316{
5317}
5318
5319AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5320{
5321}
5322
5323void AudioFlinger::AsyncCallbackThread::onFirstRef()
5324{
5325 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5326}
5327
5328bool AudioFlinger::AsyncCallbackThread::threadLoop()
5329{
5330 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005331 uint32_t writeAckSequence;
5332 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005333 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005334
5335 {
5336 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005337 while (!((mWriteAckSequence & 1) ||
5338 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005339 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005340 exitPending())) {
5341 mWaitWorkCV.wait(mLock);
5342 }
5343
Eric Laurentbfb1b832013-01-07 09:53:42 -08005344 if (exitPending()) {
5345 break;
5346 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005347 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5348 mWriteAckSequence, mDrainSequence);
5349 writeAckSequence = mWriteAckSequence;
5350 mWriteAckSequence &= ~1;
5351 drainSequence = mDrainSequence;
5352 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005353 asyncError = mAsyncError;
5354 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355 }
5356 {
Eric Laurent4de95592013-09-26 15:28:21 -07005357 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5358 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005359 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005360 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005361 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005362 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005363 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005364 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005365 if (asyncError) {
5366 playbackThread->onAsyncError();
5367 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005368 }
5369 }
5370 }
5371 return false;
5372}
5373
5374void AudioFlinger::AsyncCallbackThread::exit()
5375{
5376 ALOGV("AsyncCallbackThread::exit");
5377 Mutex::Autolock _l(mLock);
5378 requestExit();
5379 mWaitWorkCV.broadcast();
5380}
5381
Eric Laurent3b4529e2013-09-05 18:09:19 -07005382void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383{
5384 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005385 // bit 0 is cleared
5386 mWriteAckSequence = sequence << 1;
5387}
5388
5389void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5390{
5391 Mutex::Autolock _l(mLock);
5392 // ignore unexpected callbacks
5393 if (mWriteAckSequence & 2) {
5394 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005395 mWaitWorkCV.signal();
5396 }
5397}
5398
Eric Laurent3b4529e2013-09-05 18:09:19 -07005399void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005400{
5401 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005402 // bit 0 is cleared
5403 mDrainSequence = sequence << 1;
5404}
5405
5406void AudioFlinger::AsyncCallbackThread::resetDraining()
5407{
5408 Mutex::Autolock _l(mLock);
5409 // ignore unexpected callbacks
5410 if (mDrainSequence & 2) {
5411 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005412 mWaitWorkCV.signal();
5413 }
5414}
5415
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005416void AudioFlinger::AsyncCallbackThread::setAsyncError()
5417{
5418 Mutex::Autolock _l(mLock);
5419 mAsyncError = true;
5420 mWaitWorkCV.signal();
5421}
5422
Eric Laurentbfb1b832013-01-07 09:53:42 -08005423
5424// ----------------------------------------------------------------------------
5425AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005426 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5427 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005428 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5429 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430{
Eric Laurentfd477972013-10-25 18:10:40 -07005431 //FIXME: mStandby should be set to true by ThreadBase constructor
5432 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005433 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005434}
5435
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436void AudioFlinger::OffloadThread::threadLoop_exit()
5437{
5438 if (mFlushPending || mHwPaused) {
5439 // If a flush is pending or track was paused, just discard buffered data
5440 flushHw_l();
5441 } else {
5442 mMixerStatus = MIXER_DRAIN_ALL;
5443 threadLoop_drain();
5444 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005445 if (mUseAsyncWrite) {
5446 ALOG_ASSERT(mCallbackThread != 0);
5447 mCallbackThread->exit();
5448 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005449 PlaybackThread::threadLoop_exit();
5450}
5451
5452AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5453 Vector< sp<Track> > *tracksToRemove
5454)
5455{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456 size_t count = mActiveTracks.size();
5457
5458 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005459 bool doHwPause = false;
5460 bool doHwResume = false;
5461
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005462 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005463
Eric Laurentbfb1b832013-01-07 09:53:42 -08005464 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005465 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005466 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005467#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005469#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005470 // Only consider last track started for volume and mixer state control.
5471 // In theory an older track could underrun and restart after the new one starts
5472 // but as we only care about the transition phase between two tracks on a
5473 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005474 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005475 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005476
Haynes Mathew George7844f672014-01-15 12:32:55 -08005477 if (track->isInvalid()) {
5478 ALOGW("An invalidated track shouldn't be in active list");
5479 tracksToRemove->add(track);
5480 continue;
5481 }
5482
5483 if (track->mState == TrackBase::IDLE) {
5484 ALOGW("An idle track shouldn't be in active list");
5485 continue;
5486 }
5487
Eric Laurentbfb1b832013-01-07 09:53:42 -08005488 if (track->isPausing()) {
5489 track->setPaused();
5490 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005491 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005492 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005493 mHwPaused = true;
5494 }
5495 // If we were part way through writing the mixbuffer to
5496 // the HAL we must save this until we resume
5497 // BUG - this will be wrong if a different track is made active,
5498 // in that case we want to discard the pending data in the
5499 // mixbuffer and tell the client to present it again when the
5500 // track is resumed
5501 mPausedWriteLength = mCurrentWriteLength;
5502 mPausedBytesRemaining = mBytesRemaining;
5503 mBytesRemaining = 0; // stop writing
5504 }
5505 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005506 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005507 if (track->isStopping_1()) {
5508 track->mRetryCount = kMaxTrackStopRetriesOffload;
5509 } else {
5510 track->mRetryCount = kMaxTrackRetriesOffload;
5511 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005512 track->flushAck();
5513 if (last) {
5514 mFlushPending = true;
5515 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005516 } else if (track->isResumePending()){
5517 track->resumeAck();
5518 if (last) {
5519 if (mPausedBytesRemaining) {
5520 // Need to continue write that was interrupted
5521 mCurrentWriteLength = mPausedWriteLength;
5522 mBytesRemaining = mPausedBytesRemaining;
5523 mPausedBytesRemaining = 0;
5524 }
5525 if (mHwPaused) {
5526 doHwResume = true;
5527 mHwPaused = false;
5528 // threadLoop_mix() will handle the case that we need to
5529 // resume an interrupted write
5530 }
5531 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005532 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005533
Eric Laurent3df841a2016-07-15 15:15:40 -07005534 mLeftVolFloat = mRightVolFloat = -1.0;
5535
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005536 // Do not handle new data in this iteration even if track->framesReady()
5537 mixerStatus = MIXER_TRACKS_ENABLED;
5538 }
5539 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005540 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005541 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005542 if (track->mFillingUpStatus == Track::FS_FILLED) {
5543 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005544 if (last) {
5545 // make sure processVolume_l() will apply new volume even if 0
5546 mLeftVolFloat = mRightVolFloat = -1.0;
5547 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005548 }
5549
5550 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005551 sp<Track> previousTrack = mPreviousTrack.promote();
5552 if (previousTrack != 0) {
5553 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005554 // Flush any data still being written from last track
5555 mBytesRemaining = 0;
5556 if (mPausedBytesRemaining) {
5557 // Last track was paused so we also need to flush saved
5558 // mixbuffer state and invalidate track so that it will
5559 // re-submit that unwritten data when it is next resumed
5560 mPausedBytesRemaining = 0;
5561 // Invalidate is a bit drastic - would be more efficient
5562 // to have a flag to tell client that some of the
5563 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005564 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005565 }
5566 // flush data already sent to the DSP if changing audio session as audio
5567 // comes from a different source. Also invalidate previous track to force a
5568 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005569 if (previousTrack->sessionId() != track->sessionId()) {
5570 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005571 }
5572 }
5573 }
5574 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005575 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005576 if (track->isStopping_1()) {
5577 track->mRetryCount = kMaxTrackStopRetriesOffload;
5578 } else {
5579 track->mRetryCount = kMaxTrackRetriesOffload;
5580 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005581 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582 mixerStatus = MIXER_TRACKS_READY;
5583 }
5584 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005585 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005586 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005587 if (--(track->mRetryCount) <= 0) {
5588 // Hardware buffer can hold a large amount of audio so we must
5589 // wait for all current track's data to drain before we say
5590 // that the track is stopped.
5591 if (mBytesRemaining == 0) {
5592 // Only start draining when all data in mixbuffer
5593 // has been written
5594 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5595 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5596 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5597 if (last && !mStandby) {
5598 // do not modify drain sequence if we are already draining. This happens
5599 // when resuming from pause after drain.
5600 if ((mDrainSequence & 1) == 0) {
5601 mSleepTimeUs = 0;
5602 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5603 mixerStatus = MIXER_DRAIN_TRACK;
5604 mDrainSequence += 2;
5605 }
5606 if (mHwPaused) {
5607 // It is possible to move from PAUSED to STOPPING_1 without
5608 // a resume so we must ensure hardware is running
5609 doHwResume = true;
5610 mHwPaused = false;
5611 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005612 }
5613 }
Eric Laurente93cc032016-05-05 10:15:10 -07005614 } else if (last) {
5615 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5616 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005617 }
5618 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005619 // Drain has completed or we are in standby, signal presentation complete
5620 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005621 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005622 uint32_t latency = 0;
5623 status_t result = mOutput->stream->getLatency(&latency);
5624 ALOGE_IF(result != OK,
5625 "Error when retrieving output stream latency: %d", result);
5626 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005627 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005628 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005629 track->presentationComplete(framesWritten, audioHALFrames);
5630 track->reset();
5631 tracksToRemove->add(track);
5632 }
5633 } else {
5634 // No buffers for this track. Give it a few chances to
5635 // fill a buffer, then remove it from active list.
5636 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005637 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005638 uint64_t position = 0;
5639 struct timespec unused;
5640 // The running check restarts the retry counter at least once.
5641 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5642 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5643 running = true;
5644 mOffloadUnderrunPosition = position;
5645 }
5646 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005647 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5648 (long long)position, (long long)mOffloadUnderrunPosition);
5649 }
5650 if (running) { // still running, give us more time.
5651 track->mRetryCount = kMaxTrackRetriesOffload;
5652 } else {
5653 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5654 track->name());
5655 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005656 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005657 // it will then automatically call start() when data is available
5658 track->disable();
5659 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005660 } else if (last){
5661 mixerStatus = MIXER_TRACKS_ENABLED;
5662 }
5663 }
5664 }
5665 // compute volume for this track
5666 processVolume_l(track, last);
5667 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005668
Eric Laurentea0fade2013-10-04 16:23:48 -07005669 // make sure the pause/flush/resume sequence is executed in the right order.
5670 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5671 // before flush and then resume HW. This can happen in case of pause/flush/resume
5672 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005673 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005674 status_t result = mOutput->stream->pause();
5675 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005676 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005677 if (mFlushPending) {
5678 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005679 }
Eric Laurentfd477972013-10-25 18:10:40 -07005680 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005681 status_t result = mOutput->stream->resume();
5682 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005683 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005684
Eric Laurentbfb1b832013-01-07 09:53:42 -08005685 // remove all the tracks that need to be...
5686 removeTracks_l(*tracksToRemove);
5687
5688 return mixerStatus;
5689}
5690
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691// must be called with thread mutex locked
5692bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5693{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005694 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5695 mWriteAckSequence, mDrainSequence);
5696 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005697 return true;
5698 }
5699 return false;
5700}
5701
Eric Laurentbfb1b832013-01-07 09:53:42 -08005702bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5703{
5704 Mutex::Autolock _l(mLock);
5705 return waitingAsyncCallback_l();
5706}
5707
5708void AudioFlinger::OffloadThread::flushHw_l()
5709{
Eric Laurente659ef42014-09-29 13:06:46 -07005710 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005711 // Flush anything still waiting in the mixbuffer
5712 mCurrentWriteLength = 0;
5713 mBytesRemaining = 0;
5714 mPausedWriteLength = 0;
5715 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005716 // reset bytes written count to reflect that DSP buffers are empty after flush.
5717 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005718 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005719
Eric Laurentbfb1b832013-01-07 09:53:42 -08005720 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005721 // discard any pending drain or write ack by incrementing sequence
5722 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5723 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005724 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005725 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5726 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005727 }
5728}
5729
Haynes Mathew George05317d22016-05-03 16:34:26 -07005730void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5731{
5732 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005733 if (PlaybackThread::invalidateTracks_l(streamType)) {
5734 mFlushPending = true;
5735 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005736}
5737
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738// ----------------------------------------------------------------------------
5739
Eric Laurent81784c32012-11-19 14:55:58 -08005740AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005741 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005742 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005743 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005744 mWaitTimeMs(UINT_MAX)
5745{
5746 addOutputTrack(mainThread);
5747}
5748
5749AudioFlinger::DuplicatingThread::~DuplicatingThread()
5750{
5751 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5752 mOutputTracks[i]->destroy();
5753 }
5754}
5755
5756void AudioFlinger::DuplicatingThread::threadLoop_mix()
5757{
5758 // mix buffers...
5759 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005760 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005761 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005762 if (mMixerBufferValid) {
5763 memset(mMixerBuffer, 0, mMixerBufferSize);
5764 } else {
5765 memset(mSinkBuffer, 0, mSinkBufferSize);
5766 }
Eric Laurent81784c32012-11-19 14:55:58 -08005767 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005768 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005769 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005770 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005771 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005772}
5773
5774void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5775{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005776 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005777 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005778 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005779 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005780 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005781 }
5782 } else if (mBytesWritten != 0) {
5783 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5784 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005785 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005786 } else {
5787 // flush remaining overflow buffers in output tracks
5788 writeFrames = 0;
5789 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005790 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005791 }
5792}
5793
Eric Laurentbfb1b832013-01-07 09:53:42 -08005794ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005795{
5796 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005797 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005798 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005799 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005800 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005801}
5802
5803void AudioFlinger::DuplicatingThread::threadLoop_standby()
5804{
5805 // DuplicatingThread implements standby by stopping all tracks
5806 for (size_t i = 0; i < outputTracks.size(); i++) {
5807 outputTracks[i]->stop();
5808 }
5809}
5810
5811void AudioFlinger::DuplicatingThread::saveOutputTracks()
5812{
5813 outputTracks = mOutputTracks;
5814}
5815
5816void AudioFlinger::DuplicatingThread::clearOutputTracks()
5817{
5818 outputTracks.clear();
5819}
5820
5821void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5822{
5823 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005824 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5825 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5826 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5827 const size_t frameCount =
5828 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5829 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5830 // from different OutputTracks and their associated MixerThreads (e.g. one may
5831 // nearly empty and the other may be dropping data).
5832
5833 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005834 this,
5835 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005836 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005837 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005838 frameCount,
5839 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005840 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5841 if (status != NO_ERROR) {
5842 ALOGE("addOutputTrack() initCheck failed %d", status);
5843 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005844 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005845 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5846 mOutputTracks.add(outputTrack);
5847 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5848 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005849}
5850
5851void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5852{
5853 Mutex::Autolock _l(mLock);
5854 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5855 if (mOutputTracks[i]->thread() == thread) {
5856 mOutputTracks[i]->destroy();
5857 mOutputTracks.removeAt(i);
5858 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005859 if (thread->getOutput() == mOutput) {
5860 mOutput = NULL;
5861 }
Eric Laurent81784c32012-11-19 14:55:58 -08005862 return;
5863 }
5864 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005865 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005866}
5867
5868// caller must hold mLock
5869void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5870{
5871 mWaitTimeMs = UINT_MAX;
5872 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5873 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5874 if (strong != 0) {
5875 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5876 if (waitTimeMs < mWaitTimeMs) {
5877 mWaitTimeMs = waitTimeMs;
5878 }
5879 }
5880 }
5881}
5882
5883
5884bool AudioFlinger::DuplicatingThread::outputsReady(
5885 const SortedVector< sp<OutputTrack> > &outputTracks)
5886{
5887 for (size_t i = 0; i < outputTracks.size(); i++) {
5888 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5889 if (thread == 0) {
5890 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5891 outputTracks[i].get());
5892 return false;
5893 }
5894 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5895 // see note at standby() declaration
5896 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5897 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5898 thread.get());
5899 return false;
5900 }
5901 }
5902 return true;
5903}
5904
5905uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5906{
5907 return (mWaitTimeMs * 1000) / 2;
5908}
5909
5910void AudioFlinger::DuplicatingThread::cacheParameters_l()
5911{
5912 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5913 updateWaitTime_l();
5914
5915 MixerThread::cacheParameters_l();
5916}
5917
Eric Laurent6acd1d42017-01-04 14:23:29 -08005918
Eric Laurent81784c32012-11-19 14:55:58 -08005919// ----------------------------------------------------------------------------
5920// Record
5921// ----------------------------------------------------------------------------
5922
5923AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5924 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005925 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005926 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005927 audio_devices_t inDevice,
5928 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005929#ifdef TEE_SINK
5930 , const sp<NBAIO_Sink>& teeSink
5931#endif
5932 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005933 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07005934 mInput(input),
5935 mActiveTracks(&this->mLocalLog),
5936 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005937 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005938 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005939#ifdef TEE_SINK
5940 , mTeeSink(teeSink)
5941#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005942 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5943 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005944 // mFastCapture below
5945 , mFastCaptureFutex(0)
5946 // mInputSource
5947 // mPipeSink
5948 // mPipeSource
5949 , mPipeFramesP2(0)
5950 // mPipeMemory
5951 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005952 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07005953 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005954{
Glenn Kastend7dca052015-03-05 16:05:54 -08005955 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5956 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005957
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005958 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005959
5960 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005961 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005962 size_t numCounterOffers = 0;
5963 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005964#if !LOG_NDEBUG
5965 ssize_t index =
5966#else
5967 (void)
5968#endif
5969 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005970 ALOG_ASSERT(index == 0);
5971
5972 // initialize fast capture depending on configuration
5973 bool initFastCapture;
5974 switch (kUseFastCapture) {
5975 case FastCapture_Never:
5976 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005977 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005978 break;
5979 case FastCapture_Always:
5980 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005981 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005982 break;
5983 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005984 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005985 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
5986 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
5987 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005988 break;
5989 // case FastCapture_Dynamic:
5990 }
5991
5992 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005993 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005994 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005995 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5996 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005997 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005998 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005999 const sp<MemoryDealer> roHeap(readOnlyHeap());
6000 sp<IMemory> pipeMemory;
6001 if ((roHeap == 0) ||
6002 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006003 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6004 ALOGE("not enough memory for pipe buffer size=%zu; "
6005 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6006 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6007 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006008 goto failed;
6009 }
6010 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6011 memset(pipeBuffer, 0, pipeSize);
6012 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6013 const NBAIO_Format offers[1] = {format};
6014 size_t numCounterOffers = 0;
6015 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6016 ALOG_ASSERT(index == 0);
6017 mPipeSink = pipe;
6018 PipeReader *pipeReader = new PipeReader(*pipe);
6019 numCounterOffers = 0;
6020 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6021 ALOG_ASSERT(index == 0);
6022 mPipeSource = pipeReader;
6023 mPipeFramesP2 = pipeFramesP2;
6024 mPipeMemory = pipeMemory;
6025
6026 // create fast capture
6027 mFastCapture = new FastCapture();
6028 FastCaptureStateQueue *sq = mFastCapture->sq();
6029#ifdef STATE_QUEUE_DUMP
6030 // FIXME
6031#endif
6032 FastCaptureState *state = sq->begin();
6033 state->mCblk = NULL;
6034 state->mInputSource = mInputSource.get();
6035 state->mInputSourceGen++;
6036 state->mPipeSink = pipe;
6037 state->mPipeSinkGen++;
6038 state->mFrameCount = mFrameCount;
6039 state->mCommand = FastCaptureState::COLD_IDLE;
6040 // already done in constructor initialization list
6041 //mFastCaptureFutex = 0;
6042 state->mColdFutexAddr = &mFastCaptureFutex;
6043 state->mColdGen++;
6044 state->mDumpState = &mFastCaptureDumpState;
6045#ifdef TEE_SINK
6046 // FIXME
6047#endif
6048 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6049 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6050 sq->end();
6051 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6052
6053 // start the fast capture
6054 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6055 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006056 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006057 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006058#ifdef AUDIO_WATCHDOG
6059 // FIXME
6060#endif
6061
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006062 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006063 }
6064failed: ;
6065
6066 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006067}
6068
Eric Laurent81784c32012-11-19 14:55:58 -08006069AudioFlinger::RecordThread::~RecordThread()
6070{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006071 if (mFastCapture != 0) {
6072 FastCaptureStateQueue *sq = mFastCapture->sq();
6073 FastCaptureState *state = sq->begin();
6074 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6075 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6076 if (old == -1) {
6077 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6078 }
6079 }
6080 state->mCommand = FastCaptureState::EXIT;
6081 sq->end();
6082 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6083 mFastCapture->join();
6084 mFastCapture.clear();
6085 }
6086 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006087 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006088 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006089}
6090
6091void AudioFlinger::RecordThread::onFirstRef()
6092{
Glenn Kastend7dca052015-03-05 16:05:54 -08006093 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006094}
6095
Eric Laurent555530a2017-02-07 18:17:24 -08006096void AudioFlinger::RecordThread::preExit()
6097{
6098 ALOGV(" preExit()");
6099 Mutex::Autolock _l(mLock);
6100 for (size_t i = 0; i < mTracks.size(); i++) {
6101 sp<RecordTrack> track = mTracks[i];
6102 track->invalidate();
6103 }
6104 mActiveTracks.clear();
6105 mStartStopCond.broadcast();
6106}
6107
Eric Laurent81784c32012-11-19 14:55:58 -08006108bool AudioFlinger::RecordThread::threadLoop()
6109{
Eric Laurent81784c32012-11-19 14:55:58 -08006110 nsecs_t lastWarning = 0;
6111
6112 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006113
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006114reacquire_wakelock:
6115 sp<RecordTrack> activeTrack;
6116 {
6117 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006118 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006119 }
6120
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006121 // used to request a deferred sleep, to be executed later while mutex is unlocked
6122 uint32_t sleepUs = 0;
6123
6124 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006125 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006126 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006127
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006128 // activeTracks accumulates a copy of a subset of mActiveTracks
6129 Vector< sp<RecordTrack> > activeTracks;
6130
Glenn Kasten735f45f2014-08-18 15:51:59 -07006131 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006132 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006133
Glenn Kasten735f45f2014-08-18 15:51:59 -07006134 // reference to a fast track which is about to be removed
6135 sp<RecordTrack> fastTrackToRemove;
6136
Eric Laurent81784c32012-11-19 14:55:58 -08006137 { // scope for mLock
6138 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006139
Eric Laurent021cf962014-05-13 10:18:14 -07006140 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006141
Eric Laurent000a4192014-01-29 15:17:32 -08006142 // check exitPending here because checkForNewParameters_l() and
6143 // checkForNewParameters_l() can temporarily release mLock
6144 if (exitPending()) {
6145 break;
6146 }
6147
Eric Laurent5c25d562016-07-13 17:17:45 -07006148 // sleep with mutex unlocked
6149 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006150 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006151 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6152 ATRACE_END();
6153 sleepUs = 0;
6154 continue;
6155 }
6156
Glenn Kasten2b806402013-11-20 16:37:38 -08006157 // if no active track(s), then standby and release wakelock
6158 size_t size = mActiveTracks.size();
6159 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006160 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006161 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006162 releaseWakeLock_l();
6163 ALOGV("RecordThread: loop stopping");
6164 // go to sleep
6165 mWaitWorkCV.wait(mLock);
6166 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006167 goto reacquire_wakelock;
6168 }
6169
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006170 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006171 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006172 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006173
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 activeTrack = mActiveTracks[i];
6175 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006176 if (activeTrack->isFastTrack()) {
6177 ALOG_ASSERT(fastTrackToRemove == 0);
6178 fastTrackToRemove = activeTrack;
6179 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006180 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006181 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006183 continue;
6184 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006185
6186 TrackBase::track_state activeTrackState = activeTrack->mState;
6187 switch (activeTrackState) {
6188
6189 case TrackBase::PAUSING:
6190 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006191 doBroadcast = true;
6192 size--;
6193 continue;
6194
6195 case TrackBase::STARTING_1:
6196 sleepUs = 10000;
6197 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006198 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006199 continue;
6200
6201 case TrackBase::STARTING_2:
6202 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006203 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006204 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006205 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006206 break;
6207
6208 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006209 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006210 break;
6211
6212 case TrackBase::IDLE:
6213 i++;
6214 continue;
6215
6216 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006217 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006218 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006219
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006220 activeTracks.add(activeTrack);
6221 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006222
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006223 if (activeTrack->isFastTrack()) {
6224 ALOG_ASSERT(!mFastTrackAvail);
6225 ALOG_ASSERT(fastTrack == 0);
6226 fastTrack = activeTrack;
6227 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006228 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006229
Andy Hungdae27702016-10-31 14:01:16 -07006230 mActiveTracks.updatePowerState(this);
6231
Eric Laurent5c25d562016-07-13 17:17:45 -07006232 if (allStopped) {
6233 standbyIfNotAlreadyInStandby();
6234 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006235 if (doBroadcast) {
6236 mStartStopCond.broadcast();
6237 }
6238
6239 // sleep if there are no active tracks to process
6240 if (activeTracks.size() == 0) {
6241 if (sleepUs == 0) {
6242 sleepUs = kRecordThreadSleepUs;
6243 }
6244 continue;
6245 }
6246 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006247
Eric Laurent81784c32012-11-19 14:55:58 -08006248 lockEffectChains_l(effectChains);
6249 }
6250
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006251 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006252
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006253 size_t size = effectChains.size();
6254 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006255 // thread mutex is not locked, but effect chain is locked
6256 effectChains[i]->process_l();
6257 }
6258
Glenn Kasten735f45f2014-08-18 15:51:59 -07006259 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006260 if (mFastCapture != 0) {
6261 FastCaptureStateQueue *sq = mFastCapture->sq();
6262 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006263 bool didModify = false;
6264 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6266 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6267 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6268 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6269 if (old == -1) {
6270 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6271 }
6272 }
6273 state->mCommand = FastCaptureState::READ_WRITE;
6274#if 0 // FIXME
6275 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006276 FastThreadDumpState::kSamplingNforLowRamDevice :
6277 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006278#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006279 didModify = true;
6280 }
6281 audio_track_cblk_t *cblkOld = state->mCblk;
6282 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6283 if (cblkNew != cblkOld) {
6284 state->mCblk = cblkNew;
6285 // block until acked if removing a fast track
6286 if (cblkOld != NULL) {
6287 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6288 }
6289 didModify = true;
6290 }
6291 sq->end(didModify);
6292 if (didModify) {
6293 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006294#if 0
6295 if (kUseFastCapture == FastCapture_Dynamic) {
6296 mNormalSource = mPipeSource;
6297 }
6298#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006299 }
6300 }
6301
Glenn Kasten735f45f2014-08-18 15:51:59 -07006302 // now run the fast track destructor with thread mutex unlocked
6303 fastTrackToRemove.clear();
6304
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006305 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6306 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6307 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6308 // If destination is non-contiguous, first read past the nominal end of buffer, then
6309 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006310
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006311 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006312 ssize_t framesRead;
6313
6314 // If an NBAIO source is present, use it to read the normal capture's data
6315 if (mPipeSource != 0) {
6316 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006317 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006318 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006319 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006320 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6321 // buffer size or at least for 20ms.
6322 size_t sleepFrames = max(
6323 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6324 if (framesRead <= (ssize_t) sleepFrames) {
6325 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6326 }
6327 if (framesRead < 0) {
6328 status_t status = (status_t) framesRead;
6329 switch (status) {
6330 case OVERRUN:
6331 ALOGW("overrun on read from pipe");
6332 framesRead = 0;
6333 break;
6334 case NEGOTIATE:
6335 ALOGE("re-negotiation is needed");
6336 framesRead = -1; // Will cause an attempt to recover.
6337 break;
6338 default:
6339 ALOGE("unknown error %d on read from pipe", status);
6340 break;
6341 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006342 }
6343 // otherwise use the HAL / AudioStreamIn directly
6344 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006345 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006346 size_t bytesRead;
6347 status_t result = mInput->stream->read(
6348 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006349 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006350 if (result < 0) {
6351 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006352 } else {
6353 framesRead = bytesRead / mFrameSize;
6354 }
6355 }
6356
Andy Hung3f0c9022016-01-15 17:49:46 -08006357 // Update server timestamp with server stats
6358 // systemTime() is optional if the hardware supports timestamps.
6359 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6360 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6361
6362 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006363 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006364 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006365 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006366 if (ret == NO_ERROR) {
6367 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6368 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6369 // Note: In general record buffers should tend to be empty in
6370 // a properly running pipeline.
6371 //
6372 // Also, it is not advantageous to call get_presentation_position during the read
6373 // as the read obtains a lock, preventing the timestamp call from executing.
6374 }
6375 }
6376 // Use this to track timestamp information
6377 // ALOGD("%s", mTimestamp.toString().c_str());
6378
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006379 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006380 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006381 // Force input into standby so that it tries to recover at next read attempt
6382 inputStandBy();
6383 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006384 }
6385 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006386 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006387 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006388 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006389
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006390 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006391 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006392 }
6393 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006394 {
6395 size_t part1 = mRsmpInFramesP2 - rear;
6396 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006397 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006398 (framesRead - part1) * mFrameSize);
6399 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006400 }
6401 rear = mRsmpInRear += framesRead;
6402
6403 size = activeTracks.size();
6404 // loop over each active track
6405 for (size_t i = 0; i < size; i++) {
6406 activeTrack = activeTracks[i];
6407
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006408 // skip fast tracks, as those are handled directly by FastCapture
6409 if (activeTrack->isFastTrack()) {
6410 continue;
6411 }
6412
Andy Hung73c02e42015-03-29 01:13:58 -07006413 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006414 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6415
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006416 enum {
6417 OVERRUN_UNKNOWN,
6418 OVERRUN_TRUE,
6419 OVERRUN_FALSE
6420 } overrun = OVERRUN_UNKNOWN;
6421
6422 // loop over getNextBuffer to handle circular sink
6423 for (;;) {
6424
6425 activeTrack->mSink.frameCount = ~0;
6426 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6427 size_t framesOut = activeTrack->mSink.frameCount;
6428 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6429
Andy Hung73c02e42015-03-29 01:13:58 -07006430 // check available frames and handle overrun conditions
6431 // if the record track isn't draining fast enough.
6432 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006434 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6435 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006436 overrun = OVERRUN_TRUE;
6437 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006438 if (framesOut == 0 || framesIn == 0) {
6439 break;
6440 }
6441
Andy Hung6770c6f2015-04-07 13:43:36 -07006442 // Don't allow framesOut to be larger than what is possible with resampling
6443 // from framesIn.
6444 // This isn't strictly necessary but helps limit buffer resizing in
6445 // RecordBufferConverter. TODO: remove when no longer needed.
6446 framesOut = min(framesOut,
6447 destinationFramesPossible(
6448 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006449 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6450 framesOut = activeTrack->mRecordBufferConverter->convert(
6451 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006452
6453 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6454 overrun = OVERRUN_FALSE;
6455 }
6456
6457 if (activeTrack->mFramesToDrop == 0) {
6458 if (framesOut > 0) {
6459 activeTrack->mSink.frameCount = framesOut;
6460 activeTrack->releaseBuffer(&activeTrack->mSink);
6461 }
6462 } else {
6463 // FIXME could do a partial drop of framesOut
6464 if (activeTrack->mFramesToDrop > 0) {
6465 activeTrack->mFramesToDrop -= framesOut;
6466 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006467 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006468 }
6469 } else {
6470 activeTrack->mFramesToDrop += framesOut;
6471 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6472 activeTrack->mSyncStartEvent->isCancelled()) {
6473 ALOGW("Synced record %s, session %d, trigger session %d",
6474 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6475 activeTrack->sessionId(),
6476 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006477 activeTrack->mSyncStartEvent->triggerSession() :
6478 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006479 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006480 }
6481 }
6482 }
6483
6484 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006485 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006486 }
6487 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006488
6489 switch (overrun) {
6490 case OVERRUN_TRUE:
6491 // client isn't retrieving buffers fast enough
6492 if (!activeTrack->setOverflow()) {
6493 nsecs_t now = systemTime();
6494 // FIXME should lastWarning per track?
6495 if ((now - lastWarning) > kWarningThrottleNs) {
6496 ALOGW("RecordThread: buffer overflow");
6497 lastWarning = now;
6498 }
6499 }
6500 break;
6501 case OVERRUN_FALSE:
6502 activeTrack->clearOverflow();
6503 break;
6504 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006505 break;
6506 }
6507
Andy Hung3f0c9022016-01-15 17:49:46 -08006508 // update frame information and push timestamp out
6509 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006510 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006511 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6512 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006513 }
6514
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006515unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006516 // enable changes in effect chain
6517 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006518 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006519 }
6520
Glenn Kasten93e471f2013-08-19 08:40:07 -07006521 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006522
6523 {
6524 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006525 for (size_t i = 0; i < mTracks.size(); i++) {
6526 sp<RecordTrack> track = mTracks[i];
6527 track->invalidate();
6528 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006529 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006530 mStartStopCond.broadcast();
6531 }
6532
6533 releaseWakeLock();
6534
6535 ALOGV("RecordThread %p exiting", this);
6536 return false;
6537}
6538
Glenn Kasten93e471f2013-08-19 08:40:07 -07006539void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006540{
6541 if (!mStandby) {
6542 inputStandBy();
6543 mStandby = true;
6544 }
6545}
6546
6547void AudioFlinger::RecordThread::inputStandBy()
6548{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006549 // Idle the fast capture if it's currently running
6550 if (mFastCapture != 0) {
6551 FastCaptureStateQueue *sq = mFastCapture->sq();
6552 FastCaptureState *state = sq->begin();
6553 if (!(state->mCommand & FastCaptureState::IDLE)) {
6554 state->mCommand = FastCaptureState::COLD_IDLE;
6555 state->mColdFutexAddr = &mFastCaptureFutex;
6556 state->mColdGen++;
6557 mFastCaptureFutex = 0;
6558 sq->end();
6559 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6560 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6561#if 0
6562 if (kUseFastCapture == FastCapture_Dynamic) {
6563 // FIXME
6564 }
6565#endif
6566#ifdef AUDIO_WATCHDOG
6567 // FIXME
6568#endif
6569 } else {
6570 sq->end(false /*didModify*/);
6571 }
6572 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006573 status_t result = mInput->stream->standby();
6574 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006575
6576 // If going into standby, flush the pipe source.
6577 if (mPipeSource.get() != nullptr) {
6578 const ssize_t flushed = mPipeSource->flush();
6579 if (flushed > 0) {
6580 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6581 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6582 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6583 }
6584 }
Eric Laurent81784c32012-11-19 14:55:58 -08006585}
6586
Glenn Kasten05997e22014-03-13 15:08:33 -07006587// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006588sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006589 const sp<AudioFlinger::Client>& client,
6590 uint32_t sampleRate,
6591 audio_format_t format,
6592 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006593 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006594 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006595 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006596 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006597 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006598 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006599 status_t *status,
6600 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006601{
Glenn Kasten74935e42013-12-19 08:56:45 -08006602 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006603 sp<RecordTrack> track;
6604 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006605 audio_input_flags_t inputFlags = mInput->flags;
6606
6607 // special case for FAST flag considered OK if fast capture is present
6608 if (hasFastCapture()) {
6609 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6610 }
6611
6612 // Check if requested flags are compatible with output stream flags
6613 if ((*flags & inputFlags) != *flags) {
6614 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6615 " input flags (%08x)",
6616 *flags, inputFlags);
6617 *flags = (audio_input_flags_t)(*flags & inputFlags);
6618 }
Eric Laurent81784c32012-11-19 14:55:58 -08006619
Glenn Kasten90e58b12013-07-31 16:16:02 -07006620 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006621 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006622 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006623 // we formerly checked for a callback handler (non-0 tid),
6624 // but that is no longer required for TRANSFER_OBTAIN mode
6625 //
Glenn Kasten74105912014-07-03 12:28:53 -07006626 // frame count is not specified, or is exactly the pipe depth
6627 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006628 // PCM data
6629 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006630 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006631 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006632 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006633 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006634 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006635 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006636 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006637 hasFastCapture() &&
6638 // there are sufficient fast track slots available
6639 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006640 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006641 // check compatibility with audio effects.
6642 Mutex::Autolock _l(mLock);
6643 // Do not accept FAST flag if the session has software effects
6644 sp<EffectChain> chain = getEffectChain_l(sessionId);
6645 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006646 audio_input_flags_t old = *flags;
6647 chain->checkInputFlagCompatibility(flags);
6648 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006649 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6650 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006651 }
6652 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006653 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006654 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6655 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006656 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006657 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6658 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006659 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006660 this, frameCount, mFrameCount, mPipeFramesP2,
6661 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006662 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006663 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006664 }
6665 }
6666
6667 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006668 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006669 // fast track: frame count is exactly the pipe depth
6670 frameCount = mPipeFramesP2;
6671 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6672 *notificationFrames = mFrameCount;
6673 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006674 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6675 // or 20 ms if there is a fast capture
6676 // TODO This could be a roundupRatio inline, and const
6677 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6678 * sampleRate + mSampleRate - 1) / mSampleRate;
6679 // minimum number of notification periods is at least kMinNotifications,
6680 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6681 static const size_t kMinNotifications = 3;
6682 static const uint32_t kMinMs = 30;
6683 // TODO This could be a roundupRatio inline
6684 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6685 // TODO This could be a roundupRatio inline
6686 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6687 maxNotificationFrames;
6688 const size_t minFrameCount = maxNotificationFrames *
6689 max(kMinNotifications, minNotificationsByMs);
6690 frameCount = max(frameCount, minFrameCount);
6691 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6692 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006693 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006694 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006695 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006696
Glenn Kasten15e57982013-09-24 11:52:37 -07006697 lStatus = initCheck();
6698 if (lStatus != NO_ERROR) {
6699 ALOGE("createRecordTrack_l() audio driver not initialized");
6700 goto Exit;
6701 }
Eric Laurent81784c32012-11-19 14:55:58 -08006702
6703 { // scope for mLock
6704 Mutex::Autolock _l(mLock);
6705
6706 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006707 format, channelMask, frameCount,
6708 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006709 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006710
Glenn Kasten03003332013-08-06 15:40:54 -07006711 lStatus = track->initCheck();
6712 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006713 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006714 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006715 goto Exit;
6716 }
6717 mTracks.add(track);
6718
Eric Laurent05067782016-06-01 18:27:28 -07006719 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006720 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6721 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6722 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006723 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006724 }
Eric Laurent81784c32012-11-19 14:55:58 -08006725 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006726
Eric Laurent81784c32012-11-19 14:55:58 -08006727 lStatus = NO_ERROR;
6728
6729Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006730 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006731 return track;
6732}
6733
6734status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6735 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006736 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006737{
6738 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6739 sp<ThreadBase> strongMe = this;
6740 status_t status = NO_ERROR;
6741
6742 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006743 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006744 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006745 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006746 triggerSession,
6747 recordTrack->sessionId(),
6748 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006749 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006750 // Sync event can be cancelled by the trigger session if the track is not in a
6751 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006752 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006753 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006754 } else {
6755 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006756 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006757 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006758 }
6759 }
6760
6761 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006762 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006763 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006764 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6765 if (recordTrack->mState == TrackBase::PAUSING) {
6766 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006767 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006768 } else {
6769 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006770 }
6771 return status;
6772 }
6773
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006774 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6775 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6776 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006777 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006778 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006779 status_t status = NO_ERROR;
6780 if (recordTrack->isExternalTrack()) {
6781 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006782 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006783 mLock.lock();
6784 // FIXME should verify that recordTrack is still in mActiveTracks
6785 if (status != NO_ERROR) {
6786 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006787 recordTrack->clearSyncStartEvent();
6788 ALOGV("RecordThread::start error %d", status);
6789 return status;
6790 }
Eric Laurent81784c32012-11-19 14:55:58 -08006791 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006792 // Catch up with current buffer indices if thread is already running.
6793 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6794 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6795 // see previously buffered data before it called start(), but with greater risk of overrun.
6796
Andy Hung73c02e42015-03-29 01:13:58 -07006797 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006798 // clear any converter state as new data will be discontinuous
6799 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006800 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006801 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006802 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006803 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006804 ALOGV("Record failed to start");
6805 status = BAD_VALUE;
6806 goto startError;
6807 }
Eric Laurent81784c32012-11-19 14:55:58 -08006808 return status;
6809 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006810
Eric Laurent81784c32012-11-19 14:55:58 -08006811startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006812 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006813 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006814 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006815 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006816 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006817 return status;
6818}
6819
Eric Laurent81784c32012-11-19 14:55:58 -08006820void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6821{
6822 sp<SyncEvent> strongEvent = event.promote();
6823
6824 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006825 sp<RefBase> ptr = strongEvent->cookie().promote();
6826 if (ptr != 0) {
6827 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6828 recordTrack->handleSyncStartEvent(strongEvent);
6829 }
Eric Laurent81784c32012-11-19 14:55:58 -08006830 }
6831}
6832
Glenn Kastena8356f62013-07-25 14:37:52 -07006833bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006834 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006835 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006836 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006837 return false;
6838 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006839 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006840 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006841 // signal thread to stop
6842 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006843 // do not wait for mStartStopCond if exiting
6844 if (exitPending()) {
6845 return true;
6846 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006847 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006848 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006849 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006850 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006851 ALOGV("Record stopped OK");
6852 return true;
6853 }
6854 return false;
6855}
6856
Glenn Kasten0f11b512014-01-31 16:18:54 -08006857bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006858{
6859 return false;
6860}
6861
Glenn Kasten0f11b512014-01-31 16:18:54 -08006862status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006863{
6864#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6865 if (!isValidSyncEvent(event)) {
6866 return BAD_VALUE;
6867 }
6868
Glenn Kastend848eb42016-03-08 13:42:11 -08006869 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006870 status_t ret = NAME_NOT_FOUND;
6871
6872 Mutex::Autolock _l(mLock);
6873
6874 for (size_t i = 0; i < mTracks.size(); i++) {
6875 sp<RecordTrack> track = mTracks[i];
6876 if (eventSession == track->sessionId()) {
6877 (void) track->setSyncEvent(event);
6878 ret = NO_ERROR;
6879 }
6880 }
6881 return ret;
6882#else
6883 return BAD_VALUE;
6884#endif
6885}
6886
6887// destroyTrack_l() must be called with ThreadBase::mLock held
6888void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6889{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006890 track->terminate();
6891 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006892 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006893 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006894 removeTrack_l(track);
6895 }
6896}
6897
6898void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6899{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006900 String8 result;
6901 track->appendDump(result, false /* active */);
6902 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
6903
Eric Laurent81784c32012-11-19 14:55:58 -08006904 mTracks.remove(track);
6905 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006906 if (track->isFastTrack()) {
6907 ALOG_ASSERT(!mFastTrackAvail);
6908 mFastTrackAvail = true;
6909 }
Eric Laurent81784c32012-11-19 14:55:58 -08006910}
6911
6912void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6913{
6914 dumpInternals(fd, args);
6915 dumpTracks(fd, args);
6916 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006917 dprintf(fd, " Local log:\n");
6918 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08006919}
6920
6921void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6922{
Glenn Kasten44182c22015-03-05 17:12:23 -08006923 dumpBase(fd, args);
6924
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006925 AudioStreamIn *input = mInput;
6926 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6927 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6928 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006929 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006930 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006931 }
Andy Hungbfa64962017-06-12 14:43:19 -07006932
6933 if (input != nullptr) {
6934 dprintf(fd, " Hal stream dump:\n");
6935 (void)input->stream->dump(fd);
6936 }
6937
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006938 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006939 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006940
Glenn Kasten2f90c512015-12-02 11:40:09 -08006941 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6942 // while we are dumping it. It may be inconsistent, but it won't mutate!
6943 // This is a large object so we place it on the heap.
6944 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6945 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6946 copy->dump(fd);
6947 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006948}
6949
Glenn Kasten0f11b512014-01-31 16:18:54 -08006950void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006951{
Eric Laurent81784c32012-11-19 14:55:58 -08006952 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08006953 size_t numtracks = mTracks.size();
6954 size_t numactive = mActiveTracks.size();
6955 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006956 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006957 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08006958 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006959 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006960 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08006961 RecordTrack::appendDumpHeader(result);
6962 for (size_t i = 0; i < numtracks ; ++i) {
6963 sp<RecordTrack> track = mTracks[i];
6964 if (track != 0) {
6965 bool active = mActiveTracks.indexOf(track) >= 0;
6966 if (active) {
6967 numactiveseen++;
6968 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006969 result.append(prefix);
6970 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08006971 }
Eric Laurent81784c32012-11-19 14:55:58 -08006972 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006973 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006974 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006975 }
6976
Marco Nelissenb2208842014-02-07 14:00:50 -08006977 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006978 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08006979 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006980 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08006981 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006982 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006983 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006984 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006985 result.append(prefix);
6986 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08006987 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006988 }
Eric Laurent81784c32012-11-19 14:55:58 -08006989
6990 }
6991 write(fd, result.string(), result.size());
6992}
6993
Andy Hung73c02e42015-03-29 01:13:58 -07006994
6995void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6996{
6997 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
6998 RecordThread *recordThread = (RecordThread *) threadBase.get();
6999 mRsmpInFront = recordThread->mRsmpInRear;
7000 mRsmpInUnrel = 0;
7001}
7002
7003void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7004 size_t *framesAvailable, bool *hasOverrun)
7005{
7006 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7007 RecordThread *recordThread = (RecordThread *) threadBase.get();
7008 const int32_t rear = recordThread->mRsmpInRear;
7009 const int32_t front = mRsmpInFront;
7010 const ssize_t filled = rear - front;
7011
7012 size_t framesIn;
7013 bool overrun = false;
7014 if (filled < 0) {
7015 // should not happen, but treat like a massive overrun and re-sync
7016 framesIn = 0;
7017 mRsmpInFront = rear;
7018 overrun = true;
7019 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7020 framesIn = (size_t) filled;
7021 } else {
7022 // client is not keeping up with server, but give it latest data
7023 framesIn = recordThread->mRsmpInFrames;
7024 mRsmpInFront = /* front = */ rear - framesIn;
7025 overrun = true;
7026 }
7027 if (framesAvailable != NULL) {
7028 *framesAvailable = framesIn;
7029 }
7030 if (hasOverrun != NULL) {
7031 *hasOverrun = overrun;
7032 }
7033}
7034
Eric Laurent81784c32012-11-19 14:55:58 -08007035// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007036status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007037 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007038{
Andy Hung73c02e42015-03-29 01:13:58 -07007039 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007040 if (threadBase == 0) {
7041 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007042 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007043 return NOT_ENOUGH_DATA;
7044 }
7045 RecordThread *recordThread = (RecordThread *) threadBase.get();
7046 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007047 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007048 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007049 // FIXME should not be P2 (don't want to increase latency)
7050 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007051 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007052 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007053 front &= recordThread->mRsmpInFramesP2 - 1;
7054 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007055 if (part1 > (size_t) filled) {
7056 part1 = filled;
7057 }
7058 size_t ask = buffer->frameCount;
7059 ALOG_ASSERT(ask > 0);
7060 if (part1 > ask) {
7061 part1 = ask;
7062 }
7063 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007064 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007065 buffer->raw = NULL;
7066 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007067 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007068 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007069 }
7070
Andy Hung57446612015-04-19 23:56:46 -07007071 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007072 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007073 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007074 return NO_ERROR;
7075}
7076
7077// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007078void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7079 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007080{
Glenn Kasten85948432013-08-19 12:09:05 -07007081 size_t stepCount = buffer->frameCount;
7082 if (stepCount == 0) {
7083 return;
7084 }
Andy Hung73c02e42015-03-29 01:13:58 -07007085 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7086 mRsmpInUnrel -= stepCount;
7087 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007088 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007089 buffer->frameCount = 0;
7090}
7091
Eric Laurentd8365c52017-07-16 15:27:05 -07007092void AudioFlinger::RecordThread::checkBtNrec()
7093{
7094 Mutex::Autolock _l(mLock);
7095 checkBtNrec_l();
7096}
7097
7098void AudioFlinger::RecordThread::checkBtNrec_l()
7099{
7100 // disable AEC and NS if the device is a BT SCO headset supporting those
7101 // pre processings
7102 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7103 mAudioFlinger->btNrecIsOff();
7104 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7105 for (size_t i = 0; i < mEffectChains.size(); i++) {
7106 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7107 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7108 }
7109 }
7110}
7111
Andy Hung97a893e2015-03-29 01:03:07 -07007112
Eric Laurent10351942014-05-08 18:49:52 -07007113bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7114 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007115{
7116 bool reconfig = false;
7117
Eric Laurent10351942014-05-08 18:49:52 -07007118 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007119
Eric Laurent10351942014-05-08 18:49:52 -07007120 audio_format_t reqFormat = mFormat;
7121 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007122 // 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 -07007123 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7124
7125 AudioParameter param = AudioParameter(keyValuePair);
7126 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007127
7128 // scope for AutoPark extends to end of method
7129 AutoPark<FastCapture> park(mFastCapture);
7130
Eric Laurent10351942014-05-08 18:49:52 -07007131 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7132 // channel count change can be requested. Do we mandate the first client defines the
7133 // HAL sampling rate and channel count or do we allow changes on the fly?
7134 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7135 samplingRate = value;
7136 reconfig = true;
7137 }
7138 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007139 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007140 status = BAD_VALUE;
7141 } else {
7142 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007143 reconfig = true;
7144 }
Eric Laurent10351942014-05-08 18:49:52 -07007145 }
7146 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7147 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007148 if (!audio_is_input_channel(mask) ||
7149 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007150 status = BAD_VALUE;
7151 } else {
7152 channelMask = mask;
7153 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007154 }
Eric Laurent10351942014-05-08 18:49:52 -07007155 }
7156 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7157 // do not accept frame count changes if tracks are open as the track buffer
7158 // size depends on frame count and correct behavior would not be guaranteed
7159 // if frame count is changed after track creation
7160 if (mActiveTracks.size() > 0) {
7161 status = INVALID_OPERATION;
7162 } else {
7163 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007164 }
Eric Laurent10351942014-05-08 18:49:52 -07007165 }
7166 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7167 // forward device change to effects that have requested to be
7168 // aware of attached audio device.
7169 for (size_t i = 0; i < mEffectChains.size(); i++) {
7170 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007171 }
Eric Laurent81784c32012-11-19 14:55:58 -08007172
Eric Laurent10351942014-05-08 18:49:52 -07007173 // store input device and output device but do not forward output device to audio HAL.
7174 // Note that status is ignored by the caller for output device
7175 // (see AudioFlinger::setParameters()
7176 if (audio_is_output_devices(value)) {
7177 mOutDevice = value;
7178 status = BAD_VALUE;
7179 } else {
7180 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007181 if (value != AUDIO_DEVICE_NONE) {
7182 mPrevInDevice = value;
7183 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007184 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007185 }
Eric Laurent10351942014-05-08 18:49:52 -07007186 }
7187 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7188 mAudioSource != (audio_source_t)value) {
7189 // forward device change to effects that have requested to be
7190 // aware of attached audio device.
7191 for (size_t i = 0; i < mEffectChains.size(); i++) {
7192 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007193 }
Eric Laurent10351942014-05-08 18:49:52 -07007194 mAudioSource = (audio_source_t)value;
7195 }
Glenn Kastene198c362013-08-13 09:13:36 -07007196
Eric Laurent10351942014-05-08 18:49:52 -07007197 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007198 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007199 if (status == INVALID_OPERATION) {
7200 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007201 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007202 }
7203 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007204 if (status == BAD_VALUE) {
7205 uint32_t sRate;
7206 audio_channel_mask_t channelMask;
7207 audio_format_t format;
7208 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7209 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7210 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7211 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7212 status = NO_ERROR;
7213 }
Eric Laurent81784c32012-11-19 14:55:58 -08007214 }
Eric Laurent10351942014-05-08 18:49:52 -07007215 if (status == NO_ERROR) {
7216 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007217 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007218 }
7219 }
Eric Laurent81784c32012-11-19 14:55:58 -08007220 }
Eric Laurent10351942014-05-08 18:49:52 -07007221
Eric Laurent81784c32012-11-19 14:55:58 -08007222 return reconfig;
7223}
7224
7225String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7226{
Eric Laurent81784c32012-11-19 14:55:58 -08007227 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007228 if (initCheck() == NO_ERROR) {
7229 String8 out_s8;
7230 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7231 return out_s8;
7232 }
Eric Laurent81784c32012-11-19 14:55:58 -08007233 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007234 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007235}
7236
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007237void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007238 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7239
7240 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007241
7242 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007243 case AUDIO_INPUT_OPENED:
7244 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007245 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007246 desc->mChannelMask = mChannelMask;
7247 desc->mSamplingRate = mSampleRate;
7248 desc->mFormat = mFormat;
7249 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007250 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007251 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007252 break;
7253
Eric Laurent73e26b62015-04-27 16:55:58 -07007254 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007255 default:
7256 break;
7257 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007258 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007259}
7260
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007261void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007262{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007263 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7264 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007265 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007266 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007267 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007268 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7269 result = mInput->stream->getFrameSize(&mFrameSize);
7270 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7271 result = mInput->stream->getBufferSize(&mBufferSize);
7272 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007273 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007274 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7275 "mBufferSize=%lld, mFrameCount=%lld",
7276 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7277 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007278 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007279 // 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 -07007280 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007281 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007282 // A larger value should allow more old data to be read after a track calls start(),
7283 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007284 //
7285 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007286 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007287 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007288 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007289 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007290
7291 // TODO optimize audio capture buffer sizes ...
7292 // Here we calculate the size of the sliding buffer used as a source
7293 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7294 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7295 // be better to have it derived from the pipe depth in the long term.
7296 // The current value is higher than necessary. However it should not add to latency.
7297
Glenn Kasten85948432013-08-19 12:09:05 -07007298 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007299 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7300 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007301 // if posix_memalign fails, will segv here.
7302 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007303
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007304 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7305 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007306}
7307
Glenn Kasten5f972c02014-01-13 09:59:31 -08007308uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007309{
7310 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007311 uint32_t result;
7312 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7313 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007314 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007315 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007316}
7317
Eric Laurent4c415062016-06-17 16:14:16 -07007318// hasAudioSession_l() must be called with ThreadBase::mLock held
7319uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007320{
Eric Laurent81784c32012-11-19 14:55:58 -08007321 uint32_t result = 0;
7322 if (getEffectChain_l(sessionId) != 0) {
7323 result = EFFECT_SESSION;
7324 }
7325
7326 for (size_t i = 0; i < mTracks.size(); ++i) {
7327 if (sessionId == mTracks[i]->sessionId()) {
7328 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007329 if (mTracks[i]->isFastTrack()) {
7330 result |= FAST_SESSION;
7331 }
Eric Laurent81784c32012-11-19 14:55:58 -08007332 break;
7333 }
7334 }
7335
7336 return result;
7337}
7338
Glenn Kastend848eb42016-03-08 13:42:11 -08007339KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007340{
Glenn Kastend848eb42016-03-08 13:42:11 -08007341 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007342 Mutex::Autolock _l(mLock);
7343 for (size_t j = 0; j < mTracks.size(); ++j) {
7344 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007345 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007346 if (ids.indexOfKey(sessionId) < 0) {
7347 ids.add(sessionId, true);
7348 }
7349 }
7350 return ids;
7351}
7352
7353AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7354{
7355 Mutex::Autolock _l(mLock);
7356 AudioStreamIn *input = mInput;
7357 mInput = NULL;
7358 return input;
7359}
7360
7361// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007362sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007363{
7364 if (mInput == NULL) {
7365 return NULL;
7366 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007367 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007368}
7369
7370status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7371{
7372 // only one chain per input thread
7373 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007374 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007375 return INVALID_OPERATION;
7376 }
7377 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007378 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007379 chain->setInBuffer(NULL);
7380 chain->setOutBuffer(NULL);
7381
7382 checkSuspendOnAddEffectChain_l(chain);
7383
Eric Laurent1b928682014-10-02 19:41:47 -07007384 // make sure enabled pre processing effects state is communicated to the HAL as we
7385 // just moved them to a new input stream.
7386 chain->syncHalEffectsState();
7387
Eric Laurent81784c32012-11-19 14:55:58 -08007388 mEffectChains.add(chain);
7389
7390 return NO_ERROR;
7391}
7392
7393size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7394{
7395 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7396 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007397 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007398 chain.get(), mEffectChains.size(), this);
7399 if (mEffectChains.size() == 1) {
7400 mEffectChains.removeAt(0);
7401 }
7402 return 0;
7403}
7404
Eric Laurent1c333e22014-05-20 10:48:17 -07007405status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7406 audio_patch_handle_t *handle)
7407{
7408 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007409
7410 // store new device and send to effects
7411 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007412 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007413 for (size_t i = 0; i < mEffectChains.size(); i++) {
7414 mEffectChains[i]->setDevice_l(mInDevice);
7415 }
7416
Eric Laurentd8365c52017-07-16 15:27:05 -07007417 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007418
7419 // store new source and send to effects
7420 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7421 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007422 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007423 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007424 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007425 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007426
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007427 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007428 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7429 status = hwDevice->createAudioPatch(patch->num_sources,
7430 patch->sources,
7431 patch->num_sinks,
7432 patch->sinks,
7433 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007434 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007435 char *address;
7436 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7437 address = audio_device_address_to_parameter(
7438 patch->sources[0].ext.device.type,
7439 patch->sources[0].ext.device.address);
7440 } else {
7441 address = (char *)calloc(1, 1);
7442 }
7443 AudioParameter param = AudioParameter(String8(address));
7444 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007445 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007446 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007447 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007448 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007449 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007450 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007451 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007452
Eric Laurente8726fe2015-06-26 09:39:24 -07007453 if (mInDevice != mPrevInDevice) {
7454 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7455 mPrevInDevice = mInDevice;
7456 }
Eric Laurent296fb132015-05-01 11:38:42 -07007457
Eric Laurent1c333e22014-05-20 10:48:17 -07007458 return status;
7459}
7460
7461status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7462{
7463 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007464
7465 mInDevice = AUDIO_DEVICE_NONE;
7466
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007467 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007468 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7469 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007470 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007471 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007472 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007473 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007474 }
7475 return status;
7476}
7477
Eric Laurent83b88082014-06-20 18:31:16 -07007478void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7479{
7480 Mutex::Autolock _l(mLock);
7481 mTracks.add(record);
7482}
7483
7484void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7485{
7486 Mutex::Autolock _l(mLock);
7487 destroyTrack_l(record);
7488}
7489
7490void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7491{
7492 ThreadBase::getAudioPortConfig(config);
7493 config->role = AUDIO_PORT_ROLE_SINK;
7494 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7495 config->ext.mix.usecase.source = mAudioSource;
7496}
Eric Laurent1c333e22014-05-20 10:48:17 -07007497
Eric Laurent6acd1d42017-01-04 14:23:29 -08007498// ----------------------------------------------------------------------------
7499// Mmap
7500// ----------------------------------------------------------------------------
7501
7502AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7503 : mThread(thread)
7504{
7505}
7506
7507AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7508{
7509 MmapThread *thread = mThread.get();
7510 // clear our strong reference before disconnecting the thread: the last strong reference
Eric Laurent18b57012017-02-13 16:23:52 -08007511 // will be removed when closeInput/closeOutput is executed upon call from audio policy manager
Eric Laurent6acd1d42017-01-04 14:23:29 -08007512 // and the thread removed from mMMapThreads list causing the thread destruction.
7513 mThread.clear();
7514 if (thread != nullptr) {
7515 thread->disconnect();
7516 }
7517}
7518
7519status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7520 struct audio_mmap_buffer_info *info)
7521{
7522 if (mThread == 0) {
7523 return NO_INIT;
7524 }
7525 return mThread->createMmapBuffer(minSizeFrames, info);
7526}
7527
7528status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7529{
7530 if (mThread == 0) {
7531 return NO_INIT;
7532 }
7533 return mThread->getMmapPosition(position);
7534}
7535
Eric Laurenta54f1282017-07-01 19:39:32 -07007536status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007537 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007538
7539{
7540 if (mThread == 0) {
7541 return NO_INIT;
7542 }
7543 return mThread->start(client, handle);
7544}
7545
7546status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7547{
7548 if (mThread == 0) {
7549 return NO_INIT;
7550 }
7551 return mThread->stop(handle);
7552}
7553
Eric Laurent18b57012017-02-13 16:23:52 -08007554status_t AudioFlinger::MmapThreadHandle::standby()
7555{
7556 if (mThread == 0) {
7557 return NO_INIT;
7558 }
7559 return mThread->standby();
7560}
7561
Eric Laurent6acd1d42017-01-04 14:23:29 -08007562
7563AudioFlinger::MmapThread::MmapThread(
7564 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7565 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7566 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7567 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007568 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7569 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007570{
Eric Laurent18b57012017-02-13 16:23:52 -08007571 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007572 readHalParameters_l();
7573}
7574
7575AudioFlinger::MmapThread::~MmapThread()
7576{
Eric Laurent18b57012017-02-13 16:23:52 -08007577 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007578}
7579
7580void AudioFlinger::MmapThread::onFirstRef()
7581{
7582 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7583}
7584
7585void AudioFlinger::MmapThread::disconnect()
7586{
7587 for (const sp<MmapTrack> &t : mActiveTracks) {
7588 stop(t->portId());
7589 }
7590 // this will cause the destruction of this thread.
7591 if (isOutput()) {
7592 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7593 } else {
7594 AudioSystem::releaseInput(mId, mSessionId);
7595 }
7596}
7597
7598
7599void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7600 audio_stream_type_t streamType __unused,
7601 audio_session_t sessionId,
7602 const sp<MmapStreamCallback>& callback,
7603 audio_port_handle_t portId)
7604{
7605 mAttr = *attr;
7606 mSessionId = sessionId;
7607 mCallback = callback;
7608 mPortId = portId;
7609}
7610
7611status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7612 struct audio_mmap_buffer_info *info)
7613{
7614 if (mHalStream == 0) {
7615 return NO_INIT;
7616 }
Eric Laurent18b57012017-02-13 16:23:52 -08007617 mStandby = true;
7618 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007619 return mHalStream->createMmapBuffer(minSizeFrames, info);
7620}
7621
7622status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7623{
7624 if (mHalStream == 0) {
7625 return NO_INIT;
7626 }
7627 return mHalStream->getMmapPosition(position);
7628}
7629
Eric Laurenta54f1282017-07-01 19:39:32 -07007630status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007631 audio_port_handle_t *handle)
7632{
Eric Laurenta54f1282017-07-01 19:39:32 -07007633 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7634 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007635 if (mHalStream == 0) {
7636 return NO_INIT;
7637 }
7638
7639 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007640
Eric Laurenta54f1282017-07-01 19:39:32 -07007641 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007642 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007643 ret = mHalStream->start();
7644 if (ret != NO_ERROR) {
7645 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7646 return ret;
7647 }
Eric Laurent18b57012017-02-13 16:23:52 -08007648 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007649 return NO_ERROR;
7650 }
7651
7652 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7653
7654 audio_io_handle_t io = mId;
7655 if (isOutput()) {
7656 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7657 config.sample_rate = mSampleRate;
7658 config.channel_mask = mChannelMask;
7659 config.format = mFormat;
7660 audio_stream_type_t stream = streamType();
7661 audio_output_flags_t flags =
7662 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
7663 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7664 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7665 mSessionId,
7666 &stream,
7667 client.clientUid,
7668 &config,
7669 flags,
7670 &deviceId,
7671 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007672 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007673 audio_config_base_t config;
7674 config.sample_rate = mSampleRate;
7675 config.channel_mask = mChannelMask;
7676 config.format = mFormat;
7677 audio_port_handle_t deviceId = AUDIO_PORT_HANDLE_NONE;
7678 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7679 mSessionId,
7680 client.clientPid,
7681 client.clientUid,
7682 &config,
7683 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7684 &deviceId,
7685 &portId);
7686 }
7687 // APM should not chose a different input or output stream for the same set of attributes
7688 // and audo configuration
7689 if (ret != NO_ERROR || io != mId) {
7690 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7691 __FUNCTION__, ret, io, mId);
7692 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007693 }
7694
7695 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007696 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007697 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007698 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007699 }
7700
7701 // abort if start is rejected by audio policy manager
7702 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007703 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007704 if (mActiveTracks.size() != 0) {
7705 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007706 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007707 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007708 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007709 }
Eric Laurent18b57012017-02-13 16:23:52 -08007710 } else {
7711 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007712 }
7713 return PERMISSION_DENIED;
7714 }
7715
Eric Laurenta54f1282017-07-01 19:39:32 -07007716 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7717 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007718
7719 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007720 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007721 if (chain != 0) {
7722 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7723 chain->incTrackCnt();
7724 chain->incActiveTrackCnt();
7725 }
7726
7727 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007728 broadcast_l();
7729
Eric Laurenta54f1282017-07-01 19:39:32 -07007730 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007731
7732 return NO_ERROR;
7733}
7734
7735status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7736{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007737 ALOGV("%s handle %d", __FUNCTION__, handle);
7738
7739 if (mHalStream == 0) {
7740 return NO_INIT;
7741 }
7742
Eric Laurenta54f1282017-07-01 19:39:32 -07007743 if (handle == mPortId) {
7744 mHalStream->stop();
7745 return NO_ERROR;
7746 }
7747
Eric Laurent6acd1d42017-01-04 14:23:29 -08007748 sp<MmapTrack> track;
7749 for (const sp<MmapTrack> &t : mActiveTracks) {
7750 if (handle == t->portId()) {
7751 track = t;
7752 break;
7753 }
7754 }
7755 if (track == 0) {
7756 return BAD_VALUE;
7757 }
7758
7759 mActiveTracks.remove(track);
7760
7761 if (isOutput()) {
7762 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007763 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007764 } else {
7765 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007766 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007767 }
7768
7769 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7770 if (chain != 0) {
7771 chain->decActiveTrackCnt();
7772 chain->decTrackCnt();
7773 }
7774
7775 broadcast_l();
7776
Eric Laurent6acd1d42017-01-04 14:23:29 -08007777 return NO_ERROR;
7778}
7779
Eric Laurent18b57012017-02-13 16:23:52 -08007780status_t AudioFlinger::MmapThread::standby()
7781{
7782 ALOGV("%s", __FUNCTION__);
7783
7784 if (mHalStream == 0) {
7785 return NO_INIT;
7786 }
7787 if (mActiveTracks.size() != 0) {
7788 return INVALID_OPERATION;
7789 }
7790 mHalStream->standby();
7791 mStandby = true;
7792 releaseWakeLock();
7793 return NO_ERROR;
7794}
7795
Eric Laurent6acd1d42017-01-04 14:23:29 -08007796
7797void AudioFlinger::MmapThread::readHalParameters_l()
7798{
7799 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7800 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7801 mFormat = mHALFormat;
7802 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7803 result = mHalStream->getFrameSize(&mFrameSize);
7804 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7805 result = mHalStream->getBufferSize(&mBufferSize);
7806 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7807 mFrameCount = mBufferSize / mFrameSize;
7808}
7809
7810bool AudioFlinger::MmapThread::threadLoop()
7811{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007812 checkSilentMode_l();
7813
7814 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7815
7816 while (!exitPending())
7817 {
7818 Mutex::Autolock _l(mLock);
7819 Vector< sp<EffectChain> > effectChains;
7820
7821 if (mSignalPending) {
7822 // A signal was raised while we were unlocked
7823 mSignalPending = false;
7824 } else {
7825 if (mConfigEvents.isEmpty()) {
7826 // we're about to wait, flush the binder command buffer
7827 IPCThreadState::self()->flushCommands();
7828
7829 if (exitPending()) {
7830 break;
7831 }
7832
Eric Laurent6acd1d42017-01-04 14:23:29 -08007833 // wait until we have something to do...
7834 ALOGV("%s going to sleep", myName.string());
7835 mWaitWorkCV.wait(mLock);
7836 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007837
7838 checkSilentMode_l();
7839
7840 continue;
7841 }
7842 }
7843
7844 processConfigEvents_l();
7845
7846 processVolume_l();
7847
7848 checkInvalidTracks_l();
7849
7850 mActiveTracks.updatePowerState(this);
7851
7852 lockEffectChains_l(effectChains);
7853 for (size_t i = 0; i < effectChains.size(); i ++) {
7854 effectChains[i]->process_l();
7855 }
7856 // enable changes in effect chain
7857 unlockEffectChains(effectChains);
7858 // Effect chains will be actually deleted here if they were removed from
7859 // mEffectChains list during mixing or effects processing
7860 }
7861
7862 threadLoop_exit();
7863
7864 if (!mStandby) {
7865 threadLoop_standby();
7866 mStandby = true;
7867 }
7868
Eric Laurent6acd1d42017-01-04 14:23:29 -08007869 ALOGV("Thread %p type %d exiting", this, mType);
7870 return false;
7871}
7872
7873// checkForNewParameter_l() must be called with ThreadBase::mLock held
7874bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7875 status_t& status)
7876{
7877 AudioParameter param = AudioParameter(keyValuePair);
7878 int value;
7879 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7880 // forward device change to effects that have requested to be
7881 // aware of attached audio device.
7882 if (value != AUDIO_DEVICE_NONE) {
7883 mOutDevice = value;
7884 for (size_t i = 0; i < mEffectChains.size(); i++) {
7885 mEffectChains[i]->setDevice_l(mOutDevice);
7886 }
7887 }
7888 }
7889 status = mHalStream->setParameters(keyValuePair);
7890
7891 return false;
7892}
7893
7894String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7895{
7896 Mutex::Autolock _l(mLock);
7897 String8 out_s8;
7898 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7899 return out_s8;
7900 }
7901 return String8();
7902}
7903
7904void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7905 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7906
7907 desc->mIoHandle = mId;
7908
7909 switch (event) {
7910 case AUDIO_INPUT_OPENED:
7911 case AUDIO_INPUT_CONFIG_CHANGED:
7912 case AUDIO_OUTPUT_OPENED:
7913 case AUDIO_OUTPUT_CONFIG_CHANGED:
7914 desc->mPatch = mPatch;
7915 desc->mChannelMask = mChannelMask;
7916 desc->mSamplingRate = mSampleRate;
7917 desc->mFormat = mFormat;
7918 desc->mFrameCount = mFrameCount;
7919 desc->mFrameCountHAL = mFrameCount;
7920 desc->mLatency = 0;
7921 break;
7922
7923 case AUDIO_INPUT_CLOSED:
7924 case AUDIO_OUTPUT_CLOSED:
7925 default:
7926 break;
7927 }
7928 mAudioFlinger->ioConfigChanged(event, desc, pid);
7929}
7930
7931status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7932 audio_patch_handle_t *handle)
7933{
7934 status_t status = NO_ERROR;
7935
7936 // store new device and send to effects
7937 audio_devices_t type = AUDIO_DEVICE_NONE;
7938 audio_port_handle_t deviceId;
7939 if (isOutput()) {
7940 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7941 type |= patch->sinks[i].ext.device.type;
7942 }
7943 deviceId = patch->sinks[0].id;
7944 } else {
7945 type = patch->sources[0].ext.device.type;
7946 deviceId = patch->sources[0].id;
7947 }
7948
7949 for (size_t i = 0; i < mEffectChains.size(); i++) {
7950 mEffectChains[i]->setDevice_l(type);
7951 }
7952
7953 if (isOutput()) {
7954 mOutDevice = type;
7955 } else {
7956 mInDevice = type;
7957 // store new source and send to effects
7958 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7959 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7960 for (size_t i = 0; i < mEffectChains.size(); i++) {
7961 mEffectChains[i]->setAudioSource_l(mAudioSource);
7962 }
7963 }
7964 }
7965
7966 if (mAudioHwDev->supportsAudioPatches()) {
7967 status = mHalDevice->createAudioPatch(patch->num_sources,
7968 patch->sources,
7969 patch->num_sinks,
7970 patch->sinks,
7971 handle);
7972 } else {
7973 char *address;
7974 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7975 //FIXME: we only support address on first sink with HAL version < 3.0
7976 address = audio_device_address_to_parameter(
7977 patch->sinks[0].ext.device.type,
7978 patch->sinks[0].ext.device.address);
7979 } else {
7980 address = (char *)calloc(1, 1);
7981 }
7982 AudioParameter param = AudioParameter(String8(address));
7983 free(address);
7984 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7985 if (!isOutput()) {
7986 param.addInt(String8(AudioParameter::keyInputSource),
7987 (int)patch->sinks[0].ext.mix.usecase.source);
7988 }
7989 status = mHalStream->setParameters(param.toString());
7990 *handle = AUDIO_PATCH_HANDLE_NONE;
7991 }
7992
7993 if (isOutput() && mPrevOutDevice != mOutDevice) {
7994 mPrevOutDevice = type;
7995 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08007996 sp<MmapStreamCallback> callback = mCallback.promote();
7997 if (callback != 0) {
7998 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007999 }
8000 }
8001 if (!isOutput() && mPrevInDevice != mInDevice) {
8002 mPrevInDevice = type;
8003 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008004 sp<MmapStreamCallback> callback = mCallback.promote();
8005 if (callback != 0) {
8006 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008007 }
8008 }
8009 return status;
8010}
8011
8012status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8013{
8014 status_t status = NO_ERROR;
8015
8016 mInDevice = AUDIO_DEVICE_NONE;
8017
8018 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8019 supportsAudioPatches : false;
8020
8021 if (supportsAudioPatches) {
8022 status = mHalDevice->releaseAudioPatch(handle);
8023 } else {
8024 AudioParameter param;
8025 param.addInt(String8(AudioParameter::keyRouting), 0);
8026 status = mHalStream->setParameters(param.toString());
8027 }
8028 return status;
8029}
8030
8031void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8032{
8033 ThreadBase::getAudioPortConfig(config);
8034 if (isOutput()) {
8035 config->role = AUDIO_PORT_ROLE_SOURCE;
8036 config->ext.mix.hw_module = mAudioHwDev->handle();
8037 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8038 } else {
8039 config->role = AUDIO_PORT_ROLE_SINK;
8040 config->ext.mix.hw_module = mAudioHwDev->handle();
8041 config->ext.mix.usecase.source = mAudioSource;
8042 }
8043}
8044
8045status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8046{
8047 audio_session_t session = chain->sessionId();
8048
8049 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8050 // Attach all tracks with same session ID to this chain.
8051 // indicate all active tracks in the chain
8052 for (const sp<MmapTrack> &track : mActiveTracks) {
8053 if (session == track->sessionId()) {
8054 chain->incTrackCnt();
8055 chain->incActiveTrackCnt();
8056 }
8057 }
8058
8059 chain->setThread(this);
8060 chain->setInBuffer(nullptr);
8061 chain->setOutBuffer(nullptr);
8062 chain->syncHalEffectsState();
8063
8064 mEffectChains.add(chain);
8065 checkSuspendOnAddEffectChain_l(chain);
8066 return NO_ERROR;
8067}
8068
8069size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8070{
8071 audio_session_t session = chain->sessionId();
8072
8073 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8074
8075 for (size_t i = 0; i < mEffectChains.size(); i++) {
8076 if (chain == mEffectChains[i]) {
8077 mEffectChains.removeAt(i);
8078 // detach all active tracks from the chain
8079 // detach all tracks with same session ID from this chain
8080 for (const sp<MmapTrack> &track : mActiveTracks) {
8081 if (session == track->sessionId()) {
8082 chain->decActiveTrackCnt();
8083 chain->decTrackCnt();
8084 }
8085 }
8086 break;
8087 }
8088 }
8089 return mEffectChains.size();
8090}
8091
8092// hasAudioSession_l() must be called with ThreadBase::mLock held
8093uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8094{
8095 uint32_t result = 0;
8096 if (getEffectChain_l(sessionId) != 0) {
8097 result = EFFECT_SESSION;
8098 }
8099
8100 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8101 sp<MmapTrack> track = mActiveTracks[i];
8102 if (sessionId == track->sessionId()) {
8103 result |= TRACK_SESSION;
8104 if (track->isFastTrack()) {
8105 result |= FAST_SESSION;
8106 }
8107 break;
8108 }
8109 }
8110
8111 return result;
8112}
8113
8114void AudioFlinger::MmapThread::threadLoop_standby()
8115{
8116 mHalStream->standby();
8117}
8118
8119void AudioFlinger::MmapThread::threadLoop_exit()
8120{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008121 sp<MmapStreamCallback> callback = mCallback.promote();
8122 if (callback != 0) {
8123 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008124 }
8125}
8126
8127status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8128{
8129 return BAD_VALUE;
8130}
8131
8132bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8133{
8134 return false;
8135}
8136
8137status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8138 const effect_descriptor_t *desc, audio_session_t sessionId)
8139{
8140 // No global effect sessions on mmap threads
8141 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8142 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8143 desc->name, mThreadName);
8144 return BAD_VALUE;
8145 }
8146
8147 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8148 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8149 desc->name);
8150 return BAD_VALUE;
8151 }
8152 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008153 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8154 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008155 return BAD_VALUE;
8156 }
8157
8158 // Only allow effects without processing load or latency
8159 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8160 return BAD_VALUE;
8161 }
8162
8163 return NO_ERROR;
8164
8165}
8166
8167void AudioFlinger::MmapThread::checkInvalidTracks_l()
8168{
8169 for (const sp<MmapTrack> &track : mActiveTracks) {
8170 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008171 sp<MmapStreamCallback> callback = mCallback.promote();
8172 if (callback != 0) {
8173 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008174 }
8175 break;
8176 }
8177 }
8178}
8179
8180void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8181{
8182 dumpInternals(fd, args);
8183 dumpTracks(fd, args);
8184 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008185 dprintf(fd, " Local log:\n");
8186 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008187}
8188
8189void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8190{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008191 dumpBase(fd, args);
8192
8193 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8194 mAttr.content_type, mAttr.usage, mAttr.source);
8195 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8196 if (mActiveTracks.size() == 0) {
8197 dprintf(fd, " No active clients\n");
8198 }
8199}
8200
8201void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8202{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008203 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008204 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008205 dprintf(fd, " %zu Tracks\n", numtracks);
8206 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008207 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008208 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008209 MmapTrack::appendDumpHeader(result);
8210 for (size_t i = 0; i < numtracks ; ++i) {
8211 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008212 result.append(prefix);
8213 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008214 }
8215 } else {
8216 dprintf(fd, "\n");
8217 }
8218 write(fd, result.string(), result.size());
8219}
8220
8221AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8222 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8223 AudioHwDevice *hwDev, AudioStreamOut *output,
8224 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8225 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8226 mStreamType(AUDIO_STREAM_MUSIC),
8227 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8228{
8229 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8230 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8231 mMasterVolume = audioFlinger->masterVolume_l();
8232 mMasterMute = audioFlinger->masterMute_l();
8233 if (mAudioHwDev) {
8234 if (mAudioHwDev->canSetMasterVolume()) {
8235 mMasterVolume = 1.0;
8236 }
8237
8238 if (mAudioHwDev->canSetMasterMute()) {
8239 mMasterMute = false;
8240 }
8241 }
8242}
8243
8244void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8245 audio_stream_type_t streamType,
8246 audio_session_t sessionId,
8247 const sp<MmapStreamCallback>& callback,
8248 audio_port_handle_t portId)
8249{
8250 MmapThread::configure(attr, streamType, sessionId, callback, portId);
8251 mStreamType = streamType;
8252}
8253
8254AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8255{
8256 Mutex::Autolock _l(mLock);
8257 AudioStreamOut *output = mOutput;
8258 mOutput = NULL;
8259 return output;
8260}
8261
8262void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8263{
8264 Mutex::Autolock _l(mLock);
8265 // Don't apply master volume in SW if our HAL can do it for us.
8266 if (mAudioHwDev &&
8267 mAudioHwDev->canSetMasterVolume()) {
8268 mMasterVolume = 1.0;
8269 } else {
8270 mMasterVolume = value;
8271 }
8272}
8273
8274void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8275{
8276 Mutex::Autolock _l(mLock);
8277 // Don't apply master mute in SW if our HAL can do it for us.
8278 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8279 mMasterMute = false;
8280 } else {
8281 mMasterMute = muted;
8282 }
8283}
8284
8285void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8286{
8287 Mutex::Autolock _l(mLock);
8288 if (stream == mStreamType) {
8289 mStreamVolume = value;
8290 broadcast_l();
8291 }
8292}
8293
8294float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8295{
8296 Mutex::Autolock _l(mLock);
8297 if (stream == mStreamType) {
8298 return mStreamVolume;
8299 }
8300 return 0.0f;
8301}
8302
8303void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8304{
8305 Mutex::Autolock _l(mLock);
8306 if (stream == mStreamType) {
8307 mStreamMute= muted;
8308 broadcast_l();
8309 }
8310}
8311
8312void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8313{
8314 Mutex::Autolock _l(mLock);
8315 if (streamType == mStreamType) {
8316 for (const sp<MmapTrack> &track : mActiveTracks) {
8317 track->invalidate();
8318 }
8319 broadcast_l();
8320 }
8321}
8322
8323void AudioFlinger::MmapPlaybackThread::processVolume_l()
8324{
8325 float volume;
8326
8327 if (mMasterMute || mStreamMute) {
8328 volume = 0;
8329 } else {
8330 volume = mMasterVolume * mStreamVolume;
8331 }
8332
8333 if (volume != mHalVolFloat) {
8334 mHalVolFloat = volume;
8335
8336 // Convert volumes from float to 8.24
8337 uint32_t vol = (uint32_t)(volume * (1 << 24));
8338
8339 // Delegate volume control to effect in track effect chain if needed
8340 // only one effect chain can be present on DirectOutputThread, so if
8341 // there is one, the track is connected to it
8342 if (!mEffectChains.isEmpty()) {
8343 mEffectChains[0]->setVolume_l(&vol, &vol);
8344 volume = (float)vol / (1 << 24);
8345 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008346 // Try to use HW volume control and fall back to SW control if not implemented
8347 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8348 sp<MmapStreamCallback> callback = mCallback.promote();
8349 if (callback != 0) {
8350 int channelCount;
8351 if (isOutput()) {
8352 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8353 } else {
8354 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8355 }
8356 Vector<float> values;
8357 for (int i = 0; i < channelCount; i++) {
8358 values.add(volume);
8359 }
8360 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008361 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008362 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008363 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008364 }
8365 }
8366}
8367
8368void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8369{
8370 if (!mMasterMute) {
8371 char value[PROPERTY_VALUE_MAX];
8372 if (property_get("ro.audio.silent", value, "0") > 0) {
8373 char *endptr;
8374 unsigned long ul = strtoul(value, &endptr, 0);
8375 if (*endptr == '\0' && ul != 0) {
8376 ALOGD("Silence is golden");
8377 // The setprop command will not allow a property to be changed after
8378 // the first time it is set, so we don't have to worry about un-muting.
8379 setMasterMute_l(true);
8380 }
8381 }
8382 }
8383}
8384
8385void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8386{
8387 MmapThread::dumpInternals(fd, args);
8388
Glenn Kastend3bb6452016-12-05 18:14:37 -08008389 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8390 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008391 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8392}
8393
8394AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8395 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8396 AudioHwDevice *hwDev, AudioStreamIn *input,
8397 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8398 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8399 mInput(input)
8400{
8401 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8402 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8403}
8404
8405AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8406{
8407 Mutex::Autolock _l(mLock);
8408 AudioStreamIn *input = mInput;
8409 mInput = NULL;
8410 return input;
8411}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008412} // namespace android