blob: 49047af8c8692b2a14f3c4d812fce19def92bd86 [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
Eric Laurent3e4de772017-07-16 16:55:08 -07001172 // always allow effects without processing load or latency
1173 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1174 return NO_ERROR;
1175 }
1176
Eric Laurent4c415062016-06-17 16:14:16 -07001177 switch (mType) {
1178 case MIXER: {
1179 // Reject any effect on mixer multichannel sinks.
1180 // TODO: fix both format and multichannel issues with effects.
1181 if (mChannelCount != FCC_2) {
1182 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1183 " thread %s", desc->name, mChannelCount, mThreadName);
1184 return BAD_VALUE;
1185 }
1186 audio_output_flags_t flags = mOutput->flags;
1187 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1188 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1189 // global effects are applied only to non fast tracks if they are SW
1190 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1191 break;
1192 }
1193 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1194 // only post processing on output stage session
1195 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1196 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1197 " on output stage session", desc->name);
1198 return BAD_VALUE;
1199 }
1200 } else {
1201 // no restriction on effects applied on non fast tracks
1202 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1203 break;
1204 }
1205 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1208 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1209 desc->name);
1210 return BAD_VALUE;
1211 }
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1214 " in fast mode", desc->name);
1215 return BAD_VALUE;
1216 }
1217 }
1218 } break;
1219 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001220 // nothing actionable on offload threads, if the effect:
1221 // - is offloadable: the effect can be created
1222 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1223 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001224 break;
1225 case DIRECT:
1226 // Reject any effect on Direct output threads for now, since the format of
1227 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1228 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1229 desc->name, mThreadName);
1230 return BAD_VALUE;
1231 case DUPLICATING:
1232 // Reject any effect on mixer multichannel sinks.
1233 // TODO: fix both format and multichannel issues with effects.
1234 if (mChannelCount != FCC_2) {
1235 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1236 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1237 return BAD_VALUE;
1238 }
1239 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1240 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1241 " thread %s", desc->name, mThreadName);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1245 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1246 " DUPLICATING thread %s", desc->name, mThreadName);
1247 return BAD_VALUE;
1248 }
1249 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1250 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1251 " DUPLICATING thread %s", desc->name, mThreadName);
1252 return BAD_VALUE;
1253 }
1254 break;
1255 default:
1256 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1257 }
1258
1259 return NO_ERROR;
1260}
1261
Eric Laurent81784c32012-11-19 14:55:58 -08001262// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1263sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1264 const sp<AudioFlinger::Client>& client,
1265 const sp<IEffectClient>& effectClient,
1266 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001267 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001268 effect_descriptor_t *desc,
1269 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001270 status_t *status,
1271 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001272{
1273 sp<EffectModule> effect;
1274 sp<EffectHandle> handle;
1275 status_t lStatus;
1276 sp<EffectChain> chain;
1277 bool chainCreated = false;
1278 bool effectCreated = false;
1279 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001280 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001281
1282 lStatus = initCheck();
1283 if (lStatus != NO_ERROR) {
1284 ALOGW("createEffect_l() Audio driver not initialized.");
1285 goto Exit;
1286 }
1287
Eric Laurent81784c32012-11-19 14:55:58 -08001288 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1289
1290 { // scope for mLock
1291 Mutex::Autolock _l(mLock);
1292
Eric Laurent4c415062016-06-17 16:14:16 -07001293 lStatus = checkEffectCompatibility_l(desc, sessionId);
1294 if (lStatus != NO_ERROR) {
1295 goto Exit;
1296 }
1297
Eric Laurent81784c32012-11-19 14:55:58 -08001298 // check for existing effect chain with the requested audio session
1299 chain = getEffectChain_l(sessionId);
1300 if (chain == 0) {
1301 // create a new chain for this session
1302 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1303 chain = new EffectChain(this, sessionId);
1304 addEffectChain_l(chain);
1305 chain->setStrategy(getStrategyForSession_l(sessionId));
1306 chainCreated = true;
1307 } else {
1308 effect = chain->getEffectFromDesc_l(desc);
1309 }
1310
1311 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1312
1313 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001315 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001316 lStatus = AudioSystem::registerEffect(
1317 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321 effectRegistered = true;
1322 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (lStatus != NO_ERROR) {
1325 goto Exit;
1326 }
1327 effectCreated = true;
1328
1329 effect->setDevice(mOutDevice);
1330 effect->setDevice(mInDevice);
1331 effect->setMode(mAudioFlinger->getMode());
1332 effect->setAudioSource(mAudioSource);
1333 }
1334 // create effect handle and connect it to effect module
1335 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001336 lStatus = handle->initCheck();
1337 if (lStatus == OK) {
1338 lStatus = effect->addHandle(handle.get());
1339 }
Eric Laurent81784c32012-11-19 14:55:58 -08001340 if (enabled != NULL) {
1341 *enabled = (int)effect->isEnabled();
1342 }
1343 }
1344
1345Exit:
1346 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1347 Mutex::Autolock _l(mLock);
1348 if (effectCreated) {
1349 chain->removeEffect_l(effect);
1350 }
1351 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001352 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001353 }
1354 if (chainCreated) {
1355 removeEffectChain_l(chain);
1356 }
1357 handle.clear();
1358 }
1359
Glenn Kasten9156ef32013-08-06 15:39:08 -07001360 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001361 return handle;
1362}
1363
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001364void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1365 bool unpinIfLast)
1366{
1367 bool remove = false;
1368 sp<EffectModule> effect;
1369 {
1370 Mutex::Autolock _l(mLock);
1371
1372 effect = handle->effect().promote();
1373 if (effect == 0) {
1374 return;
1375 }
1376 // restore suspended effects if the disconnected handle was enabled and the last one.
1377 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1378 if (remove) {
1379 removeEffect_l(effect, true);
1380 }
1381 }
1382 if (remove) {
1383 mAudioFlinger->updateOrphanEffectChains(effect);
1384 AudioSystem::unregisterEffect(effect->id());
1385 if (handle->enabled()) {
1386 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1387 }
1388 }
1389}
1390
Glenn Kastend848eb42016-03-08 13:42:11 -08001391sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1392 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001393{
1394 Mutex::Autolock _l(mLock);
1395 return getEffect_l(sessionId, effectId);
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 sp<EffectChain> chain = getEffectChain_l(sessionId);
1402 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1403}
1404
1405// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1406// PlaybackThread::mLock held
1407status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1408{
1409 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001410 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 bool chainCreated = false;
1413
Eric Laurent5baf2af2013-09-12 17:37:00 -07001414 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
1415 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %x",
1416 this, effect->desc().name, effect->desc().flags);
1417
Eric Laurent81784c32012-11-19 14:55:58 -08001418 if (chain == 0) {
1419 // create a new chain for this session
1420 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1421 chain = new EffectChain(this, sessionId);
1422 addEffectChain_l(chain);
1423 chain->setStrategy(getStrategyForSession_l(sessionId));
1424 chainCreated = true;
1425 }
1426 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1427
1428 if (chain->getEffectFromId_l(effect->id()) != 0) {
1429 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1430 this, effect->desc().name, chain.get());
1431 return BAD_VALUE;
1432 }
1433
Eric Laurent5baf2af2013-09-12 17:37:00 -07001434 effect->setOffloaded(mType == OFFLOAD, mId);
1435
Eric Laurent81784c32012-11-19 14:55:58 -08001436 status_t status = chain->addEffect_l(effect);
1437 if (status != NO_ERROR) {
1438 if (chainCreated) {
1439 removeEffectChain_l(chain);
1440 }
1441 return status;
1442 }
1443
1444 effect->setDevice(mOutDevice);
1445 effect->setDevice(mInDevice);
1446 effect->setMode(mAudioFlinger->getMode());
1447 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001448
Eric Laurent81784c32012-11-19 14:55:58 -08001449 return NO_ERROR;
1450}
1451
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001452void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001453
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001454 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t desc = effect->desc();
1456 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1457 detachAuxEffect_l(effect->id());
1458 }
1459
1460 sp<EffectChain> chain = effect->chain().promote();
1461 if (chain != 0) {
1462 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001463 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001464 removeEffectChain_l(chain);
1465 }
1466 } else {
1467 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1468 }
1469}
1470
1471void AudioFlinger::ThreadBase::lockEffectChains_l(
1472 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1473{
1474 effectChains = mEffectChains;
1475 for (size_t i = 0; i < mEffectChains.size(); i++) {
1476 mEffectChains[i]->lock();
1477 }
1478}
1479
1480void AudioFlinger::ThreadBase::unlockEffectChains(
1481 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1482{
1483 for (size_t i = 0; i < effectChains.size(); i++) {
1484 effectChains[i]->unlock();
1485 }
1486}
1487
Glenn Kastend848eb42016-03-08 13:42:11 -08001488sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001489{
1490 Mutex::Autolock _l(mLock);
1491 return getEffectChain_l(sessionId);
1492}
1493
Glenn Kastend848eb42016-03-08 13:42:11 -08001494sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1495 const
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 size_t size = mEffectChains.size();
1498 for (size_t i = 0; i < size; i++) {
1499 if (mEffectChains[i]->sessionId() == sessionId) {
1500 return mEffectChains[i];
1501 }
1502 }
1503 return 0;
1504}
1505
1506void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1507{
1508 Mutex::Autolock _l(mLock);
1509 size_t size = mEffectChains.size();
1510 for (size_t i = 0; i < size; i++) {
1511 mEffectChains[i]->setMode_l(mode);
1512 }
1513}
1514
Eric Laurent83b88082014-06-20 18:31:16 -07001515void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1516{
1517 config->type = AUDIO_PORT_TYPE_MIX;
1518 config->ext.mix.handle = mId;
1519 config->sample_rate = mSampleRate;
1520 config->format = mFormat;
1521 config->channel_mask = mChannelMask;
1522 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1523 AUDIO_PORT_CONFIG_FORMAT;
1524}
1525
Eric Laurent72e3f392015-05-20 14:43:50 -07001526void AudioFlinger::ThreadBase::systemReady()
1527{
1528 Mutex::Autolock _l(mLock);
1529 if (mSystemReady) {
1530 return;
1531 }
1532 mSystemReady = true;
1533
1534 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1535 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1536 }
1537 mPendingConfigEvents.clear();
1538}
1539
Andy Hungdae27702016-10-31 14:01:16 -07001540template <typename T>
1541ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1542 ssize_t index = mActiveTracks.indexOf(track);
1543 if (index >= 0) {
1544 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1545 return index;
1546 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001547 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001548 mActiveTracksGeneration++;
1549 mLatestActiveTrack = track;
1550 ++mBatteryCounter[track->uid()].second;
1551 return mActiveTracks.add(track);
1552}
1553
1554template <typename T>
1555ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1556 ssize_t index = mActiveTracks.remove(track);
1557 if (index < 0) {
1558 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1559 return index;
1560 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001561 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001562 mActiveTracksGeneration++;
1563 --mBatteryCounter[track->uid()].second;
1564 // mLatestActiveTrack is not cleared even if is the same as track.
1565 return index;
1566}
1567
1568template <typename T>
1569void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1570 for (const sp<T> &track : mActiveTracks) {
1571 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001572 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001573 }
1574 mLastActiveTracksGeneration = mActiveTracksGeneration;
1575 mActiveTracks.clear();
1576 mLatestActiveTrack.clear();
1577 mBatteryCounter.clear();
1578}
1579
1580template <typename T>
1581void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1582 sp<ThreadBase> thread, bool force) {
1583 // Updates ActiveTracks client uids to the thread wakelock.
1584 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1585 thread->updateWakeLockUids_l(getWakeLockUids());
1586 mLastActiveTracksGeneration = mActiveTracksGeneration;
1587 }
1588
1589 // Updates BatteryNotifier uids
1590 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1591 const uid_t uid = it->first;
1592 ssize_t &previous = it->second.first;
1593 ssize_t &current = it->second.second;
1594 if (current > 0) {
1595 if (previous == 0) {
1596 BatteryNotifier::getInstance().noteStartAudio(uid);
1597 }
1598 previous = current;
1599 ++it;
1600 } else if (current == 0) {
1601 if (previous > 0) {
1602 BatteryNotifier::getInstance().noteStopAudio(uid);
1603 }
1604 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1605 } else /* (current < 0) */ {
1606 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1607 }
1608 }
1609}
Eric Laurent83b88082014-06-20 18:31:16 -07001610
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001611template <typename T>
1612void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1613 const char *funcName, const sp<T> &track) const {
1614 if (mLocalLog != nullptr) {
1615 String8 result;
1616 track->appendDump(result, false /* active */);
1617 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1618 }
1619}
1620
Eric Laurent6acd1d42017-01-04 14:23:29 -08001621void AudioFlinger::ThreadBase::broadcast_l()
1622{
1623 // Thread could be blocked waiting for async
1624 // so signal it to handle state changes immediately
1625 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1626 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1627 mSignalPending = true;
1628 mWaitWorkCV.broadcast();
1629}
1630
Eric Laurent81784c32012-11-19 14:55:58 -08001631// ----------------------------------------------------------------------------
1632// Playback
1633// ----------------------------------------------------------------------------
1634
1635AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1636 AudioStreamOut* output,
1637 audio_io_handle_t id,
1638 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001639 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001640 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001641 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001642 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001643 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001644 mMixerBuffer(NULL),
1645 mMixerBufferSize(0),
1646 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1647 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001648 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001649 mEffectBuffer(NULL),
1650 mEffectBufferSize(0),
1651 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1652 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001653 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001654 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001655 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001656 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001657 // mStreamTypes[] initialized in constructor body
1658 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001659 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001660 mMixerStatus(MIXER_IDLE),
1661 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001662 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001663 mBytesRemaining(0),
1664 mCurrentWriteLength(0),
1665 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001666 mWriteAckSequence(0),
1667 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001668 mScreenState(AudioFlinger::mScreenState),
1669 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001670 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Andy Hunge10393e2015-06-12 13:59:33 -07001671 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -08001672{
Glenn Kastend7dca052015-03-05 16:05:54 -08001673 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1674 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001675
1676 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1677 // it would be safer to explicitly pass initial masterVolume/masterMute as
1678 // parameter.
1679 //
1680 // If the HAL we are using has support for master volume or master mute,
1681 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1682 // and the mute set to false).
1683 mMasterVolume = audioFlinger->masterVolume_l();
1684 mMasterMute = audioFlinger->masterMute_l();
1685 if (mOutput && mOutput->audioHwDev) {
1686 if (mOutput->audioHwDev->canSetMasterVolume()) {
1687 mMasterVolume = 1.0;
1688 }
1689
1690 if (mOutput->audioHwDev->canSetMasterMute()) {
1691 mMasterMute = false;
1692 }
1693 }
1694
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001695 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001696
Eric Laurent223fd5c2014-11-11 13:43:36 -08001697 // ++ operator does not compile
Glenn Kasten66e46352014-01-16 17:44:23 -08001698 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001699 stream = (audio_stream_type_t) (stream + 1)) {
1700 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1701 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1702 }
Eric Laurent81784c32012-11-19 14:55:58 -08001703}
1704
1705AudioFlinger::PlaybackThread::~PlaybackThread()
1706{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001707 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001708 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001709 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001710 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001711}
1712
1713void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1714{
1715 dumpInternals(fd, args);
1716 dumpTracks(fd, args);
1717 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001718 dprintf(fd, " Local log:\n");
1719 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001720}
1721
Glenn Kasten0f11b512014-01-31 16:18:54 -08001722void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001723{
Eric Laurent81784c32012-11-19 14:55:58 -08001724 String8 result;
1725
Marco Nelissenb2208842014-02-07 14:00:50 -08001726 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001727 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1728 const stream_type_t *st = &mStreamTypes[i];
1729 if (i > 0) {
1730 result.appendFormat(", ");
1731 }
1732 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1733 if (st->mute) {
1734 result.append("M");
1735 }
1736 }
1737 result.append("\n");
1738 write(fd, result.string(), result.length());
1739 result.clear();
1740
Eric Laurent81784c32012-11-19 14:55:58 -08001741 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1742 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001743 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001744 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001745
1746 size_t numtracks = mTracks.size();
1747 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001748 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001749 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001750 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001751 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001752 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001753 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001754 Track::appendDumpHeader(result);
1755 for (size_t i = 0; i < numtracks; ++i) {
1756 sp<Track> track = mTracks[i];
1757 if (track != 0) {
1758 bool active = mActiveTracks.indexOf(track) >= 0;
1759 if (active) {
1760 numactiveseen++;
1761 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001762 result.append(prefix);
1763 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001764 }
1765 }
1766 } else {
1767 result.append("\n");
1768 }
1769 if (numactiveseen != numactive) {
1770 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001771 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001772 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001773 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001774 Track::appendDumpHeader(result);
1775 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001776 sp<Track> track = mActiveTracks[i];
1777 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001778 result.append(prefix);
1779 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001780 }
1781 }
1782 }
1783
1784 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001785}
1786
1787void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1788{
Glenn Kasten44182c22015-03-05 17:12:23 -08001789 dumpBase(fd, args);
1790
Elliott Hughes87cebad2014-05-22 10:14:43 -07001791 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001792 dprintf(fd, " Last write occurred (msecs): %llu\n",
1793 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001794 dprintf(fd, " Total writes: %d\n", mNumWrites);
1795 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1796 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1797 dprintf(fd, " Suspend count: %d\n", mSuspended);
1798 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1799 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1800 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1801 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001802 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001803 AudioStreamOut *output = mOutput;
1804 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001805 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1806 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001807 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1808 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1809 if (mPipeSink.get() != nullptr) {
1810 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1811 }
1812 if (output != nullptr) {
1813 dprintf(fd, " Hal stream dump:\n");
1814 (void)output->stream->dump(fd);
1815 }
Eric Laurent81784c32012-11-19 14:55:58 -08001816}
1817
1818// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001819
1820void AudioFlinger::PlaybackThread::onFirstRef()
1821{
Glenn Kastend7dca052015-03-05 16:05:54 -08001822 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001823}
1824
1825// ThreadBase virtuals
1826void AudioFlinger::PlaybackThread::preExit()
1827{
1828 ALOGV(" preExit()");
1829 // FIXME this is using hard-coded strings but in the future, this functionality will be
1830 // converted to use audio HAL extensions required to support tunneling
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001831 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1832 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001833}
1834
1835// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1836sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1837 const sp<AudioFlinger::Client>& client,
1838 audio_stream_type_t streamType,
1839 uint32_t sampleRate,
1840 audio_format_t format,
1841 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001842 size_t *pFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08001843 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001844 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001845 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001846 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001847 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001848 status_t *status,
1849 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001850{
Glenn Kasten74935e42013-12-19 08:56:45 -08001851 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001852 sp<Track> track;
1853 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001854 audio_output_flags_t outputFlags = mOutput->flags;
1855
1856 // special case for FAST flag considered OK if fast mixer is present
1857 if (hasFastMixer()) {
1858 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1859 }
1860
1861 // Check if requested flags are compatible with output stream flags
1862 if ((*flags & outputFlags) != *flags) {
1863 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1864 *flags, outputFlags);
1865 *flags = (audio_output_flags_t)(*flags & outputFlags);
1866 }
Eric Laurent81784c32012-11-19 14:55:58 -08001867
Eric Laurent81784c32012-11-19 14:55:58 -08001868 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001869 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001870 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001871 // PCM data
1872 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001873 // TODO: extract as a data library function that checks that a computationally
1874 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001875 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001876 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1877 (channelMask == AUDIO_CHANNEL_OUT_MONO
1878 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001879 // hardware sample rate
1880 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001881 // normal mixer has an associated fast mixer
1882 hasFastMixer() &&
1883 // there are sufficient fast track slots available
1884 (mFastTrackAvailMask != 0)
1885 // FIXME test that MixerThread for this fast track has a capable output HAL
1886 // FIXME add a permission test also?
1887 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001888 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1889 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001890 // read the fast track multiplier property the first time it is needed
1891 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1892 if (ok != 0) {
1893 ALOGE("%s pthread_once failed: %d", __func__, ok);
1894 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001895 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001896 }
Eric Laurent4c415062016-06-17 16:14:16 -07001897
1898 // check compatibility with audio effects.
1899 { // scope for mLock
1900 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001901 for (audio_session_t session : {
1902 AUDIO_SESSION_OUTPUT_STAGE,
1903 AUDIO_SESSION_OUTPUT_MIX,
1904 sessionId,
1905 }) {
1906 sp<EffectChain> chain = getEffectChain_l(session);
1907 if (chain.get() != nullptr) {
1908 audio_output_flags_t old = *flags;
1909 chain->checkOutputFlagCompatibility(flags);
1910 if (old != *flags) {
1911 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1912 (int)session, (int)old, (int)*flags);
1913 }
Eric Laurent4c415062016-06-17 16:14:16 -07001914 }
1915 }
1916 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001917 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001918 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1919 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001920 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001921 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1922 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001923 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001924 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001925 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001926 audio_is_linear_pcm(format),
1927 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001928 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001929 }
1930 }
1931 // For normal PCM streaming tracks, update minimum frame count.
1932 // For compatibility with AudioTrack calculation, buffer depth is forced
1933 // to be at least 2 x the normal mixer frame count and cover audio hardware latency.
1934 // This is probably too conservative, but legacy application code may depend on it.
1935 // If you change this calculation, also review the start threshold which is related.
Eric Laurent05067782016-06-01 18:27:28 -07001936 if (!(*flags & AUDIO_OUTPUT_FLAG_FAST)
Phil Burkfdb3c072016-02-09 10:47:02 -08001937 && audio_has_proportional_frames(format) && sharedBuffer == 0) {
Andy Hung8edb8dc2015-03-26 19:13:55 -07001938 // this must match AudioTrack.cpp calculateMinFrameCount().
1939 // TODO: Move to a common library
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001940 uint32_t latencyMs = 0;
1941 lStatus = mOutput->stream->getLatency(&latencyMs);
1942 if (lStatus != OK) {
1943 ALOGE("Error when retrieving output stream latency: %d", lStatus);
1944 goto Exit;
1945 }
Eric Laurent81784c32012-11-19 14:55:58 -08001946 uint32_t minBufCount = latencyMs / ((1000 * mNormalFrameCount) / mSampleRate);
1947 if (minBufCount < 2) {
1948 minBufCount = 2;
1949 }
Andy Hung8edb8dc2015-03-26 19:13:55 -07001950 // For normal mixing tracks, if speed is > 1.0f (normal), AudioTrack
1951 // or the client should compute and pass in a larger buffer request.
Andy Hung0e48d252015-01-26 11:43:15 -08001952 size_t minFrameCount =
Andy Hung8edb8dc2015-03-26 19:13:55 -07001953 minBufCount * sourceFramesNeededWithTimestretch(
1954 sampleRate, mNormalFrameCount,
1955 mSampleRate, AUDIO_TIMESTRETCH_SPEED_NORMAL /*speed*/);
Andy Hung0e48d252015-01-26 11:43:15 -08001956 if (frameCount < minFrameCount) { // including frameCount == 0
Eric Laurent81784c32012-11-19 14:55:58 -08001957 frameCount = minFrameCount;
1958 }
Eric Laurent81784c32012-11-19 14:55:58 -08001959 }
Glenn Kasten74935e42013-12-19 08:56:45 -08001960 *pFrameCount = frameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001961
Glenn Kastenc3df8382014-03-13 15:05:25 -07001962 switch (mType) {
1963
1964 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08001965 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08001966 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001967 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
1968 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08001969 sampleRate, format, channelMask, mOutput, mFormat);
1970 lStatus = BAD_VALUE;
1971 goto Exit;
1972 }
1973 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001974 break;
1975
1976 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08001977 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001978 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
1979 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001980 sampleRate, format, channelMask, mOutput, mFormat);
1981 lStatus = BAD_VALUE;
1982 goto Exit;
1983 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001984 break;
1985
1986 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07001987 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08001988 ALOGE("createTrack_l() Bad parameter: format %#x \""
1989 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08001990 format, mOutput, mFormat);
1991 lStatus = BAD_VALUE;
1992 goto Exit;
1993 }
Andy Hungcd044842014-08-07 11:04:34 -07001994 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08001995 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
1996 lStatus = BAD_VALUE;
1997 goto Exit;
1998 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07001999 break;
2000
Eric Laurent81784c32012-11-19 14:55:58 -08002001 }
2002
2003 lStatus = initCheck();
2004 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002005 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002006 goto Exit;
2007 }
2008
2009 { // scope for mLock
2010 Mutex::Autolock _l(mLock);
2011
2012 // all tracks in same audio session must share the same routing strategy otherwise
2013 // conflicts will happen when tracks are moved from one output to another by audio policy
2014 // manager
2015 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2016 for (size_t i = 0; i < mTracks.size(); ++i) {
2017 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002018 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002019 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2020 if (sessionId == t->sessionId() && strategy != actual) {
2021 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2022 strategy, actual);
2023 lStatus = BAD_VALUE;
2024 goto Exit;
2025 }
2026 }
2027 }
2028
Glenn Kastend79072e2016-01-06 08:41:20 -08002029 track = new Track(this, client, streamType, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002030 channelMask, frameCount,
2031 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002032 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002033
Glenn Kasten03003332013-08-06 15:40:54 -07002034 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2035 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002036 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002037 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002038 goto Exit;
2039 }
2040 mTracks.add(track);
2041
2042 sp<EffectChain> chain = getEffectChain_l(sessionId);
2043 if (chain != 0) {
2044 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2045 track->setMainBuffer(chain->inBuffer());
2046 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2047 chain->incTrackCnt();
2048 }
2049
Eric Laurent05067782016-06-01 18:27:28 -07002050 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002051 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2052 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2053 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002054 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002055 }
2056 }
2057
2058 lStatus = NO_ERROR;
2059
2060Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002061 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002062 return track;
2063}
2064
2065uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2066{
2067 return latency;
2068}
2069
2070uint32_t AudioFlinger::PlaybackThread::latency() const
2071{
2072 Mutex::Autolock _l(mLock);
2073 return latency_l();
2074}
2075uint32_t AudioFlinger::PlaybackThread::latency_l() const
2076{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002077 uint32_t latency;
2078 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2079 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002080 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002081 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002082}
2083
2084void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2085{
2086 Mutex::Autolock _l(mLock);
2087 // Don't apply master volume in SW if our HAL can do it for us.
2088 if (mOutput && mOutput->audioHwDev &&
2089 mOutput->audioHwDev->canSetMasterVolume()) {
2090 mMasterVolume = 1.0;
2091 } else {
2092 mMasterVolume = value;
2093 }
2094}
2095
2096void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2097{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002098 if (isDuplicating()) {
2099 return;
2100 }
Eric Laurent81784c32012-11-19 14:55:58 -08002101 Mutex::Autolock _l(mLock);
2102 // Don't apply master mute in SW if our HAL can do it for us.
2103 if (mOutput && mOutput->audioHwDev &&
2104 mOutput->audioHwDev->canSetMasterMute()) {
2105 mMasterMute = false;
2106 } else {
2107 mMasterMute = muted;
2108 }
2109}
2110
2111void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2112{
2113 Mutex::Autolock _l(mLock);
2114 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002115 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002116}
2117
2118void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2119{
2120 Mutex::Autolock _l(mLock);
2121 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002122 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002123}
2124
2125float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2126{
2127 Mutex::Autolock _l(mLock);
2128 return mStreamTypes[stream].volume;
2129}
2130
2131// addTrack_l() must be called with ThreadBase::mLock held
2132status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2133{
2134 status_t status = ALREADY_EXISTS;
2135
Eric Laurent81784c32012-11-19 14:55:58 -08002136 if (mActiveTracks.indexOf(track) < 0) {
2137 // the track is newly added, make sure it fills up all its
2138 // buffers before playing. This is to ensure the client will
2139 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002140 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002141 TrackBase::track_state state = track->mState;
2142 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002143 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002144 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002145 mLock.lock();
2146 // abort track was stopped/paused while we released the lock
2147 if (state != track->mState) {
2148 if (status == NO_ERROR) {
2149 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002150 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002151 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002152 mLock.lock();
2153 }
2154 return INVALID_OPERATION;
2155 }
2156 // abort if start is rejected by audio policy manager
2157 if (status != NO_ERROR) {
2158 return PERMISSION_DENIED;
2159 }
2160#ifdef ADD_BATTERY_DATA
2161 // to track the speaker usage
2162 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2163#endif
2164 }
2165
Eric Laurent51716182016-02-29 18:00:56 -08002166 // set retry count for buffer fill
2167 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002168 if (track->isStopping_1()) {
2169 track->mRetryCount = kMaxTrackStopRetriesOffload;
2170 } else {
2171 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2172 }
2173 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002174 } else {
2175 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002176 track->mFillingUpStatus =
2177 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002178 }
2179
Eric Laurent81784c32012-11-19 14:55:58 -08002180 track->mResetDone = false;
2181 track->mPresentationCompleteFrames = 0;
2182 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002183 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2184 if (chain != 0) {
2185 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2186 track->sessionId());
2187 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002188 }
2189
2190 status = NO_ERROR;
2191 }
2192
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002193 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002194 return status;
2195}
2196
Eric Laurentbfb1b832013-01-07 09:53:42 -08002197bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002198{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002199 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002200 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002201 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2202 track->mState = TrackBase::STOPPED;
2203 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002204 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002205 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002206 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002207 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002208
2209 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002210}
2211
2212void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2213{
2214 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002215
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002216 String8 result;
2217 track->appendDump(result, false /* active */);
2218 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002219
Eric Laurent81784c32012-11-19 14:55:58 -08002220 mTracks.remove(track);
2221 deleteTrackName_l(track->name());
2222 // redundant as track is about to be destroyed, for dumpsys only
2223 track->mName = -1;
2224 if (track->isFastTrack()) {
2225 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002226 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002227 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2228 mFastTrackAvailMask |= 1 << index;
2229 // redundant as track is about to be destroyed, for dumpsys only
2230 track->mFastIndex = -1;
2231 }
2232 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2233 if (chain != 0) {
2234 chain->decTrackCnt();
2235 }
2236}
2237
2238String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2239{
Eric Laurent81784c32012-11-19 14:55:58 -08002240 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002241 String8 out_s8;
2242 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2243 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002244 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002245 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002246}
2247
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002248void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002249 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2250 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002251
Eric Laurent73e26b62015-04-27 16:55:58 -07002252 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002253
2254 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002255 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002256 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002257 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002258 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002259 desc->mChannelMask = mChannelMask;
2260 desc->mSamplingRate = mSampleRate;
2261 desc->mFormat = mFormat;
2262 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002263 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002264 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002265 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002266 break;
2267
Eric Laurent73e26b62015-04-27 16:55:58 -07002268 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002269 default:
2270 break;
2271 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002272 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002273}
2274
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002275void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002276{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002277 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002278}
2279
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002280void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002281{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002282 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002283}
2284
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002285void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002286{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002287 mCallbackThread->setAsyncError();
2288}
2289
Eric Laurent3b4529e2013-09-05 18:09:19 -07002290void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002291{
2292 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002293 // reject out of sequence requests
2294 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2295 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002296 mWaitWorkCV.signal();
2297 }
2298}
2299
Eric Laurent3b4529e2013-09-05 18:09:19 -07002300void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002301{
2302 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002303 // reject out of sequence requests
2304 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2305 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002306 mWaitWorkCV.signal();
2307 }
2308}
2309
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002310void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002311{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002312 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002313 mSampleRate = mOutput->getSampleRate();
2314 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002315 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002316 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002317 }
Andy Hung9a592762014-07-21 21:56:01 -07002318 if ((mType == MIXER || mType == DUPLICATING)
2319 && !isValidPcmSinkChannelMask(mChannelMask)) {
2320 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2321 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002322 }
Andy Hunge5412692014-05-16 11:25:07 -07002323 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002324
2325 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002326 status_t result = mOutput->stream->getFormat(&mHALFormat);
2327 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002328 // Get format from the shim, which will be different than the HAL format
2329 // if playing compressed audio over HDMI passthrough.
2330 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002331 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002332 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002333 }
Andy Hung6146c082014-03-18 11:56:15 -07002334 if ((mType == MIXER || mType == DUPLICATING)
2335 && !isValidPcmSinkFormat(mFormat)) {
2336 LOG_FATAL("HAL format %#x not supported for mixed output",
2337 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002338 }
Phil Burk062e67a2015-02-11 13:40:50 -08002339 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002340 result = mOutput->stream->getBufferSize(&mBufferSize);
2341 LOG_ALWAYS_FATAL_IF(result != OK,
2342 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002343 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002344 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002345 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002346 mFrameCount);
2347 }
2348
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002349 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2350 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002351 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002352 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002353 }
2354 }
2355
Eric Laurentd1f69b02014-12-15 14:33:13 -08002356 mHwSupportsPause = false;
2357 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002358 bool supportsPause = false, supportsResume = false;
2359 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2360 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002361 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002362 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002363 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002364 } else if (supportsResume) {
2365 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002366 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002367 }
2368 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002369 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2370 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2371 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002372
Andy Hungfbfc3952015-01-15 13:33:51 -08002373 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2374 // For best precision, we use float instead of the associated output
2375 // device format (typically PCM 16 bit).
2376
2377 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2378 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2379 mBufferSize = mFrameSize * mFrameCount;
2380
2381 // TODO: We currently use the associated output device channel mask and sample rate.
2382 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2383 // (if a valid mask) to avoid premature downmix.
2384 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2385 // instead of the output device sample rate to avoid loss of high frequency information.
2386 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2387 }
2388
Andy Hung09a50072014-02-27 14:30:47 -08002389 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002390 double multiplier = 1.0;
2391 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2392 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002393 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2394 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002395
Eric Laurent81784c32012-11-19 14:55:58 -08002396 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2397 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2398 maxNormalFrameCount = maxNormalFrameCount & ~15;
2399 if (maxNormalFrameCount < minNormalFrameCount) {
2400 maxNormalFrameCount = minNormalFrameCount;
2401 }
2402 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2403 if (multiplier <= 1.0) {
2404 multiplier = 1.0;
2405 } else if (multiplier <= 2.0) {
2406 if (2 * mFrameCount <= maxNormalFrameCount) {
2407 multiplier = 2.0;
2408 } else {
2409 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2410 }
2411 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002412 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002413 }
2414 }
2415 mNormalFrameCount = multiplier * mFrameCount;
2416 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002417 if (mType == MIXER || mType == DUPLICATING) {
2418 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2419 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002420 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002421 mNormalFrameCount);
2422
Andy Hung08fb1742015-05-31 23:22:10 -07002423 // Check if we want to throttle the processing to no more than 2x normal rate
2424 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002425 mThreadThrottleTimeMs = 0;
2426 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002427 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2428
Andy Hung010a1a12014-03-13 13:57:33 -07002429 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2430 // Originally this was int16_t[] array, need to remove legacy implications.
2431 free(mSinkBuffer);
2432 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002433 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2434 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2435 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002436 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002437
Andy Hung69aed5f2014-02-25 17:24:40 -08002438 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2439 // drives the output.
2440 free(mMixerBuffer);
2441 mMixerBuffer = NULL;
2442 if (mMixerBufferEnabled) {
2443 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2444 mMixerBufferSize = mNormalFrameCount * mChannelCount
2445 * audio_bytes_per_sample(mMixerBufferFormat);
2446 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2447 }
Andy Hung98ef9782014-03-04 14:46:50 -08002448 free(mEffectBuffer);
2449 mEffectBuffer = NULL;
2450 if (mEffectBufferEnabled) {
2451 mEffectBufferFormat = AUDIO_FORMAT_PCM_16_BIT; // Note: Effects support 16b only
2452 mEffectBufferSize = mNormalFrameCount * mChannelCount
2453 * audio_bytes_per_sample(mEffectBufferFormat);
2454 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2455 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002456
Eric Laurent81784c32012-11-19 14:55:58 -08002457 // force reconfiguration of effect chains and engines to take new buffer size and audio
2458 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002459 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002460 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2461 // matter.
2462 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2463 Vector< sp<EffectChain> > effectChains = mEffectChains;
2464 for (size_t i = 0; i < effectChains.size(); i ++) {
2465 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2466 }
2467}
2468
2469
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002470status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002471{
2472 if (halFrames == NULL || dspFrames == NULL) {
2473 return BAD_VALUE;
2474 }
2475 Mutex::Autolock _l(mLock);
2476 if (initCheck() != NO_ERROR) {
2477 return INVALID_OPERATION;
2478 }
Andy Hung818e7a32016-02-16 18:08:07 -08002479 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002480 *halFrames = framesWritten;
2481
2482 if (isSuspended()) {
2483 // return an estimation of rendered frames when the output is suspended
2484 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002485 *dspFrames = (uint32_t)
2486 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002487 return NO_ERROR;
2488 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002489 status_t status;
2490 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002491 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002492 *dspFrames = (size_t)frames;
2493 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002494 }
2495}
2496
Eric Laurent4c415062016-06-17 16:14:16 -07002497// hasAudioSession_l() must be called with ThreadBase::mLock held
2498uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002499{
Eric Laurent81784c32012-11-19 14:55:58 -08002500 uint32_t result = 0;
2501 if (getEffectChain_l(sessionId) != 0) {
2502 result = EFFECT_SESSION;
2503 }
2504
2505 for (size_t i = 0; i < mTracks.size(); ++i) {
2506 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002507 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002508 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002509 if (track->isFastTrack()) {
2510 result |= FAST_SESSION;
2511 }
Eric Laurent81784c32012-11-19 14:55:58 -08002512 break;
2513 }
2514 }
2515
2516 return result;
2517}
2518
Glenn Kastend848eb42016-03-08 13:42:11 -08002519uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002520{
2521 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2522 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2523 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2524 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2525 }
2526 for (size_t i = 0; i < mTracks.size(); i++) {
2527 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002528 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002529 return AudioSystem::getStrategyForStream(track->streamType());
2530 }
2531 }
2532 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2533}
2534
2535
Phil Burk062e67a2015-02-11 13:40:50 -08002536AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002537{
2538 Mutex::Autolock _l(mLock);
2539 return mOutput;
2540}
2541
Phil Burk062e67a2015-02-11 13:40:50 -08002542AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002543{
2544 Mutex::Autolock _l(mLock);
2545 AudioStreamOut *output = mOutput;
2546 mOutput = NULL;
2547 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2548 // must push a NULL and wait for ack
2549 mOutputSink.clear();
2550 mPipeSink.clear();
2551 mNormalSink.clear();
2552 return output;
2553}
2554
2555// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002556sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002557{
2558 if (mOutput == NULL) {
2559 return NULL;
2560 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002561 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002562}
2563
2564uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2565{
2566 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2567}
2568
2569status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2570{
2571 if (!isValidSyncEvent(event)) {
2572 return BAD_VALUE;
2573 }
2574
2575 Mutex::Autolock _l(mLock);
2576
2577 for (size_t i = 0; i < mTracks.size(); ++i) {
2578 sp<Track> track = mTracks[i];
2579 if (event->triggerSession() == track->sessionId()) {
2580 (void) track->setSyncEvent(event);
2581 return NO_ERROR;
2582 }
2583 }
2584
2585 return NAME_NOT_FOUND;
2586}
2587
2588bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2589{
2590 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2591}
2592
2593void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2594 const Vector< sp<Track> >& tracksToRemove)
2595{
2596 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002597 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002598 for (size_t i = 0 ; i < count ; i++) {
2599 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002600 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002601 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002602 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002603#ifdef ADD_BATTERY_DATA
2604 // to track the speaker usage
2605 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2606#endif
2607 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002608 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002609 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002610 }
Eric Laurent81784c32012-11-19 14:55:58 -08002611 }
2612 }
2613 }
Eric Laurent81784c32012-11-19 14:55:58 -08002614}
2615
2616void AudioFlinger::PlaybackThread::checkSilentMode_l()
2617{
2618 if (!mMasterMute) {
2619 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002620 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2621 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2622 return;
2623 }
Eric Laurent81784c32012-11-19 14:55:58 -08002624 if (property_get("ro.audio.silent", value, "0") > 0) {
2625 char *endptr;
2626 unsigned long ul = strtoul(value, &endptr, 0);
2627 if (*endptr == '\0' && ul != 0) {
2628 ALOGD("Silence is golden");
2629 // The setprop command will not allow a property to be changed after
2630 // the first time it is set, so we don't have to worry about un-muting.
2631 setMasterMute_l(true);
2632 }
2633 }
2634 }
2635}
2636
2637// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002638ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002639{
Eric Laurent81784c32012-11-19 14:55:58 -08002640 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002641 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002642 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002643
2644 // If an NBAIO sink is present, use it to write the normal mixer's submix
2645 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002646
Andy Hung010a1a12014-03-13 13:57:33 -07002647 const size_t count = mBytesRemaining / mFrameSize;
2648
Simon Wilson2d590962012-11-29 15:18:50 -08002649 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002650 // update the setpoint when AudioFlinger::mScreenState changes
2651 uint32_t screenState = AudioFlinger::mScreenState;
2652 if (screenState != mScreenState) {
2653 mScreenState = screenState;
2654 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2655 if (pipe != NULL) {
2656 pipe->setAvgFrames((mScreenState & 1) ?
2657 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2658 }
2659 }
Andy Hung010a1a12014-03-13 13:57:33 -07002660 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002661 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002662 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002663 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002664 } else {
2665 bytesWritten = framesWritten;
2666 }
2667 // otherwise use the HAL / AudioStreamOut directly
2668 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002670
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002672 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2673 mWriteAckSequence += 2;
2674 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002676 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002677 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002678 // FIXME We should have an implementation of timestamps for direct output threads.
2679 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002680 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002681
Eric Laurentbfb1b832013-01-07 09:53:42 -08002682 if (mUseAsyncWrite &&
2683 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2684 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002685 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002686 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002687 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002688 }
Eric Laurent81784c32012-11-19 14:55:58 -08002689 }
2690
Eric Laurent81784c32012-11-19 14:55:58 -08002691 mNumWrites++;
2692 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002693 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002694 return bytesWritten;
2695}
2696
2697void AudioFlinger::PlaybackThread::threadLoop_drain()
2698{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002699 bool supportsDrain = false;
2700 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002701 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2702 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002703 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2704 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002705 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002706 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002707 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002708 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002709 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002710 }
2711}
2712
2713void AudioFlinger::PlaybackThread::threadLoop_exit()
2714{
Eric Laurent275e8e92014-11-30 15:14:47 -08002715 {
2716 Mutex::Autolock _l(mLock);
2717 for (size_t i = 0; i < mTracks.size(); i++) {
2718 sp<Track> track = mTracks[i];
2719 track->invalidate();
2720 }
Andy Hungdae27702016-10-31 14:01:16 -07002721 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2722 // After we exit there are no more track changes sent to BatteryNotifier
2723 // because that requires an active threadLoop.
2724 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2725 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002726 }
Eric Laurent81784c32012-11-19 14:55:58 -08002727}
2728
2729/*
2730The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002731 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002732 - mActiveSleepTimeUs from activeSleepTimeUs()
2733 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002734 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2735 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002736 - maxPeriod from frame count and sample rate (MIXER only)
2737
2738The parameters that affect these derived values are:
2739 - frame count
2740 - frame size
2741 - sample rate
2742 - device type: A2DP or not
2743 - device latency
2744 - format: PCM or not
2745 - active sleep time
2746 - idle sleep time
2747*/
2748
2749void AudioFlinger::PlaybackThread::cacheParameters_l()
2750{
Andy Hung25c2dac2014-02-27 14:56:00 -08002751 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002752 mActiveSleepTimeUs = activeSleepTimeUs();
2753 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002754
2755 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2756 // truncating audio when going to standby.
2757 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2758 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2759 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2760 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2761 }
2762 }
Eric Laurent81784c32012-11-19 14:55:58 -08002763}
2764
Eric Laurent13084622016-05-17 10:51:49 -07002765bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002766{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002767 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002768 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002769 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002770 size_t size = mTracks.size();
2771 for (size_t i = 0; i < size; i++) {
2772 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002773 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002774 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002775 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002776 }
2777 }
Eric Laurent13084622016-05-17 10:51:49 -07002778 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002779}
2780
Haynes Mathew George05317d22016-05-03 16:34:26 -07002781void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2782{
2783 Mutex::Autolock _l(mLock);
2784 invalidateTracks_l(streamType);
2785}
2786
Eric Laurent81784c32012-11-19 14:55:58 -08002787status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2788{
Glenn Kastend848eb42016-03-08 13:42:11 -08002789 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002790 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
2791 status_t result = EffectBufferHalInterface::mirror(
2792 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2793 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2794 &halInBuffer);
2795 if (result != OK) return result;
2796 halOutBuffer = halInBuffer;
2797 int16_t *buffer = reinterpret_cast<int16_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002798
2799 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002800 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002801 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002802 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002803 if (mType != DIRECT) {
2804 size_t numSamples = mNormalFrameCount * mChannelCount;
Mikhail Naganov022b9952017-01-04 16:36:51 -08002805 status_t result = EffectBufferHalInterface::allocate(
2806 numSamples * sizeof(int16_t),
2807 &halInBuffer);
2808 if (result != OK) return result;
2809 buffer = halInBuffer->audioBuffer()->s16;
2810 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2811 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002812 }
2813
2814 // Attach all tracks with same session ID to this chain.
2815 for (size_t i = 0; i < mTracks.size(); ++i) {
2816 sp<Track> track = mTracks[i];
2817 if (session == track->sessionId()) {
2818 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
2819 buffer);
2820 track->setMainBuffer(buffer);
2821 chain->incTrackCnt();
2822 }
2823 }
2824
2825 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07002826 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002827 if (session == track->sessionId()) {
2828 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
2829 chain->incActiveTrackCnt();
2830 }
2831 }
2832 }
Eric Laurentaaa44472014-09-12 17:41:50 -07002833 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08002834 chain->setInBuffer(halInBuffer);
2835 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002836 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08002837 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08002838 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
2839 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08002840 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08002842 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08002843 // Effect chain for other sessions are inserted at beginning of effect
2844 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08002845 // sessions is not important.
2846 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
2847 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
2848 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08002849 size_t size = mEffectChains.size();
2850 size_t i = 0;
2851 for (i = 0; i < size; i++) {
2852 if (mEffectChains[i]->sessionId() < session) {
2853 break;
2854 }
2855 }
2856 mEffectChains.insertAt(chain, i);
2857 checkSuspendOnAddEffectChain_l(chain);
2858
2859 return NO_ERROR;
2860}
2861
2862size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
2863{
Glenn Kastend848eb42016-03-08 13:42:11 -08002864 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08002865
2866 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
2867
2868 for (size_t i = 0; i < mEffectChains.size(); i++) {
2869 if (chain == mEffectChains[i]) {
2870 mEffectChains.removeAt(i);
2871 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07002872 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08002873 if (session == track->sessionId()) {
2874 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
2875 chain.get(), session);
2876 chain->decActiveTrackCnt();
2877 }
2878 }
2879
2880 // detach all tracks with same session ID from this chain
2881 for (size_t i = 0; i < mTracks.size(); ++i) {
2882 sp<Track> track = mTracks[i];
2883 if (session == track->sessionId()) {
Andy Hung010a1a12014-03-13 13:57:33 -07002884 track->setMainBuffer(reinterpret_cast<int16_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08002885 chain->decTrackCnt();
2886 }
2887 }
2888 break;
2889 }
2890 }
2891 return mEffectChains.size();
2892}
2893
2894status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002895 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002896{
2897 Mutex::Autolock _l(mLock);
2898 return attachAuxEffect_l(track, EffectId);
2899}
2900
2901status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002902 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08002903{
2904 status_t status = NO_ERROR;
2905
2906 if (EffectId == 0) {
2907 track->setAuxBuffer(0, NULL);
2908 } else {
2909 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
2910 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
2911 if (effect != 0) {
2912 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
2913 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
2914 } else {
2915 status = INVALID_OPERATION;
2916 }
2917 } else {
2918 status = BAD_VALUE;
2919 }
2920 }
2921 return status;
2922}
2923
2924void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
2925{
2926 for (size_t i = 0; i < mTracks.size(); ++i) {
2927 sp<Track> track = mTracks[i];
2928 if (track->auxEffectId() == effectId) {
2929 attachAuxEffect_l(track, 0);
2930 }
2931 }
2932}
2933
2934bool AudioFlinger::PlaybackThread::threadLoop()
2935{
Glenn Kasten388d5712017-04-07 14:38:41 -07002936 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08002937
Eric Laurent81784c32012-11-19 14:55:58 -08002938 Vector< sp<Track> > tracksToRemove;
2939
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002940 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07002941 nsecs_t lastWriteFinished = -1; // time last server write completed
2942 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08002943
2944 // MIXER
2945 nsecs_t lastWarning = 0;
2946
2947 // DUPLICATING
2948 // FIXME could this be made local to while loop?
2949 writeFrames = 0;
2950
2951 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002952 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08002953
2954 if (mType == MIXER) {
2955 sleepTimeShift = 0;
2956 }
2957
2958 CpuStats cpuStats;
2959 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
2960
2961 acquireWakeLock();
2962
Glenn Kasteneef598c2017-04-03 14:41:13 -07002963 // mNBLogWriter logging APIs can only be called by a single thread, typically the
2964 // thread associated with this PlaybackThread.
2965 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
2966 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002967 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
2968 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07002969 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08002970 const char *logString = NULL;
2971
rago1bb90822017-05-02 18:31:48 -07002972 // Estimated time for next buffer to be written to hal. This is used only on
2973 // suspended mode (for now) to help schedule the wait time until next iteration.
2974 nsecs_t timeLoopNextNs = 0;
2975
Eric Laurent664539d2013-09-23 18:24:31 -07002976 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07002977
Eric Laurent81784c32012-11-19 14:55:58 -08002978 while (!exitPending())
2979 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08002980 // Log merge requests are performed during AudioFlinger binder transactions, but
2981 // that does not cover audio playback. It's requested here for that reason.
2982 mAudioFlinger->requestLogMerge();
2983
Eric Laurent81784c32012-11-19 14:55:58 -08002984 cpuStats.sample(myName);
2985
2986 Vector< sp<EffectChain> > effectChains;
2987
Eric Laurent81784c32012-11-19 14:55:58 -08002988 { // scope for mLock
2989
2990 Mutex::Autolock _l(mLock);
2991
Eric Laurent021cf962014-05-13 10:18:14 -07002992 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07002993
Glenn Kasteneef598c2017-04-03 14:41:13 -07002994 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08002995 if (logString != NULL) {
2996 mNBLogWriter->logTimestamp();
2997 mNBLogWriter->log(logString);
2998 logString = NULL;
2999 }
3000
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003001 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003002 // and associate with the sink frames written out. We need
3003 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003004 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003005 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003006 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003007 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003008 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003009 ExtendedTimestamp timestamp; // use private copy to fetch
3010 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003011
3012 // We keep track of the last valid kernel position in case we are in underrun
3013 // and the normal mixer period is the same as the fast mixer period, or there
3014 // is some error from the HAL.
3015 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3016 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3017 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3018 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3019 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3020
3021 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3022 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3023 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3024 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003025 }
3026
3027 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3028 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003029 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003030 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003031 }
3032
Andy Hung818e7a32016-02-16 18:08:07 -08003033 // copy over kernel info
3034 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003035 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3036 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003037 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3038 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003039 }
3040 // mFramesWritten for non-offloaded tracks are contiguous
3041 // even after standby() is called. This is useful for the track frame
3042 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003043 bool serverLocationUpdate = false;
3044 if (mFramesWritten != lastFramesWritten) {
3045 serverLocationUpdate = true;
3046 lastFramesWritten = mFramesWritten;
3047 }
3048 // Only update timestamps if there is a meaningful change.
3049 // Either the kernel timestamp must be valid or we have written something.
3050 if (kernelLocationUpdate || serverLocationUpdate) {
3051 if (serverLocationUpdate) {
3052 // use the time before we called the HAL write - it is a bit more accurate
3053 // to when the server last read data than the current time here.
3054 //
3055 // If we haven't written anything, mLastWriteTime will be -1
3056 // and we use systemTime().
3057 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3058 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3059 ? systemTime() : mLastWriteTime;
3060 }
Andy Hungdae27702016-10-31 14:01:16 -07003061
3062 for (const sp<Track> &t : mActiveTracks) {
3063 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003064 t->updateTrackFrameInfo(
3065 t->mAudioTrackServerProxy->framesReleased(),
3066 mFramesWritten,
3067 mTimestamp);
3068 }
Andy Hunge10393e2015-06-12 13:59:33 -07003069 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003070 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003071#if 0
3072 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003073 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003074 timespec ts;
3075 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003076 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003077 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003078 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003079 }
3080 ++z;
3081#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003082 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003083 if (mSignalPending) {
3084 // A signal was raised while we were unlocked
3085 mSignalPending = false;
3086 } else if (waitingAsyncCallback_l()) {
3087 if (exitPending()) {
3088 break;
3089 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003090 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003091 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003092 releaseWakeLock_l();
3093 released = true;
3094 }
Andy Hung10cbff12017-02-21 17:30:14 -08003095
3096 const int64_t waitNs = computeWaitTimeNs_l();
3097 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3098 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3099 if (status == TIMED_OUT) {
3100 mSignalPending = true; // if timeout recheck everything
3101 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003103 if (released) {
3104 acquireWakeLock_l();
3105 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003106 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3107 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003108
3109 continue;
3110 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003111 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112 isSuspended()) {
3113 // put audio hardware into standby after short delay
3114 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003115
3116 threadLoop_standby();
3117
3118 mStandby = true;
3119 }
3120
3121 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3122 // we're about to wait, flush the binder command buffer
3123 IPCThreadState::self()->flushCommands();
3124
3125 clearOutputTracks();
3126
3127 if (exitPending()) {
3128 break;
3129 }
3130
3131 releaseWakeLock_l();
3132 // wait until we have something to do...
3133 ALOGV("%s going to sleep", myName.string());
3134 mWaitWorkCV.wait(mLock);
3135 ALOGV("%s waking up", myName.string());
3136 acquireWakeLock_l();
3137
3138 mMixerStatus = MIXER_IDLE;
3139 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3140 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003141 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003142 checkSilentMode_l();
3143
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003144 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3145 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003146 if (mType == MIXER) {
3147 sleepTimeShift = 0;
3148 }
3149
3150 continue;
3151 }
3152 }
Eric Laurent81784c32012-11-19 14:55:58 -08003153 // mMixerStatusIgnoringFastTracks is also updated internally
3154 mMixerStatus = prepareTracks_l(&tracksToRemove);
3155
Andy Hungdae27702016-10-31 14:01:16 -07003156 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003157
Eric Laurent81784c32012-11-19 14:55:58 -08003158 // prevent any changes in effect chain list and in each effect chain
3159 // during mixing and effect process as the audio buffers could be deleted
3160 // or modified if an effect is created or deleted
3161 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003162 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003163
Eric Laurentbfb1b832013-01-07 09:53:42 -08003164 if (mBytesRemaining == 0) {
3165 mCurrentWriteLength = 0;
3166 if (mMixerStatus == MIXER_TRACKS_READY) {
3167 // threadLoop_mix() sets mCurrentWriteLength
3168 threadLoop_mix();
3169 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3170 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003171 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003172 // must be written to HAL
3173 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003174 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003175 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003176 }
3177 }
Andy Hung98ef9782014-03-04 14:46:50 -08003178 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003179 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003180 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3181 // or mSinkBuffer (if there are no effects).
3182 //
3183 // This is done pre-effects computation; if effects change to
3184 // support higher precision, this needs to move.
3185 //
3186 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003187 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003188 if (mMixerBufferValid) {
3189 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3190 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3191
Andy Hung2ddee192015-12-18 17:34:44 -08003192 // mono blend occurs for mixer threads only (not direct or offloaded)
3193 // and is handled here if we're going directly to the sink.
3194 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003195 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3196 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003197 }
3198
Andy Hung98ef9782014-03-04 14:46:50 -08003199 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3200 mNormalFrameCount * mChannelCount);
3201 }
3202
Eric Laurentbfb1b832013-01-07 09:53:42 -08003203 mBytesRemaining = mCurrentWriteLength;
3204 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003205 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3206 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3207 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3208 mBytesWritten += mBytesRemaining;
3209 mFramesWritten += framesRemaining;
3210 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003211 mBytesRemaining = 0;
3212 }
Eric Laurent81784c32012-11-19 14:55:58 -08003213
Eric Laurentbfb1b832013-01-07 09:53:42 -08003214 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003215 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003216 for (size_t i = 0; i < effectChains.size(); i ++) {
3217 effectChains[i]->process_l();
3218 }
Eric Laurent81784c32012-11-19 14:55:58 -08003219 }
3220 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003221 // Process effect chains for offloaded thread even if no audio
3222 // was read from audio track: process only updates effect state
3223 // and thus does have to be synchronized with audio writes but may have
3224 // to be called while waiting for async write callback
3225 if (mType == OFFLOAD) {
3226 for (size_t i = 0; i < effectChains.size(); i ++) {
3227 effectChains[i]->process_l();
3228 }
3229 }
Eric Laurent81784c32012-11-19 14:55:58 -08003230
Andy Hung98ef9782014-03-04 14:46:50 -08003231 // Only if the Effects buffer is enabled and there is data in the
3232 // Effects buffer (buffer valid), we need to
3233 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003234 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003235 if (mEffectBufferValid) {
3236 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003237
3238 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003239 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3240 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003241 }
3242
Andy Hung98ef9782014-03-04 14:46:50 -08003243 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3244 mNormalFrameCount * mChannelCount);
3245 }
3246
Eric Laurent81784c32012-11-19 14:55:58 -08003247 // enable changes in effect chain
3248 unlockEffectChains(effectChains);
3249
Eric Laurentbfb1b832013-01-07 09:53:42 -08003250 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003251 // mSleepTimeUs == 0 means we must write to audio hardware
3252 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003253 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003254 // We save lastWriteFinished here, as previousLastWriteFinished,
3255 // for throttling. On thread start, previousLastWriteFinished will be
3256 // set to -1, which properly results in no throttling after the first write.
3257 nsecs_t previousLastWriteFinished = lastWriteFinished;
3258 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003259 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003260 // FIXME rewrite to reduce number of system calls
3261 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003262 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003263 lastWriteFinished = systemTime();
3264 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003265 if (ret < 0) {
3266 mBytesRemaining = 0;
3267 } else {
3268 mBytesWritten += ret;
3269 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003270 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003271 }
3272 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3273 (mMixerStatus == MIXER_DRAIN_ALL)) {
3274 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003275 }
Andy Hung08fb1742015-05-31 23:22:10 -07003276 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003277 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003278 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003279 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003280 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003281 ATRACE_NAME("underrun");
3282 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003283 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003284 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003286 }
Andy Hung08fb1742015-05-31 23:22:10 -07003287
3288 if (mThreadThrottle
3289 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3290 && ret > 0) { // we wrote something
3291 // Limit MixerThread data processing to no more than twice the
3292 // expected processing rate.
3293 //
3294 // This helps prevent underruns with NuPlayer and other applications
3295 // which may set up buffers that are close to the minimum size, or use
3296 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3297 //
3298 // The throttle smooths out sudden large data drains from the device,
3299 // e.g. when it comes out of standby, which often causes problems with
3300 // (1) mixer threads without a fast mixer (which has its own warm-up)
3301 // (2) minimum buffer sized tracks (even if the track is full,
3302 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003303 //
3304 // Total time spent in last processing cycle equals time spent in
3305 // 1. threadLoop_write, as well as time spent in
3306 // 2. threadLoop_mix (significant for heavy mixing, especially
3307 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003308
Andy Hung69488c42016-05-16 18:43:33 -07003309 // it's OK if deltaMs is an overestimate.
3310 const int32_t deltaMs =
3311 (lastWriteFinished - previousLastWriteFinished) / 1000000;
Andy Hung08fb1742015-05-31 23:22:10 -07003312 const int32_t throttleMs = mHalfBufferMs - deltaMs;
3313 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3314 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003315 // notify of throttle start on verbose log
3316 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3317 "mixer(%p) throttle begin:"
3318 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003319 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003320 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003321 // Throttle must be attributed to the previous mixer loop's write time
3322 // to allow back-to-back throttling.
3323 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003324 } else {
3325 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3326 if (diff > 0) {
3327 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003328 // but prevent spamming for bluetooth
3329 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()),
3330 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003331 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3332 }
Andy Hung08fb1742015-05-31 23:22:10 -07003333 }
3334 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003335 }
Eric Laurent81784c32012-11-19 14:55:58 -08003336
Eric Laurentbfb1b832013-01-07 09:53:42 -08003337 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003338 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003339 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003340 // suspended requires accurate metering of sleep time.
3341 if (isSuspended()) {
3342 // advance by expected sleepTime
3343 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3344 const nsecs_t nowNs = systemTime();
3345
3346 // compute expected next time vs current time.
3347 // (negative deltas are treated as delays).
3348 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3349 if (deltaNs < -kMaxNextBufferDelayNs) {
3350 // Delays longer than the max allowed trigger a reset.
3351 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3352 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3353 timeLoopNextNs = nowNs + deltaNs;
3354 } else if (deltaNs < 0) {
3355 // Delays within the max delay allowed: zero the delta/sleepTime
3356 // to help the system catch up in the next iteration(s)
3357 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3358 deltaNs = 0;
3359 }
3360 // update sleep time (which is >= 0)
3361 mSleepTimeUs = deltaNs / 1000;
3362 }
Eric Laurente93cc032016-05-05 10:15:10 -07003363 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3364 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003365 }
Glenn Kastene7754022014-10-31 12:11:26 -07003366 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003367 }
Eric Laurent81784c32012-11-19 14:55:58 -08003368 }
3369
3370 // Finally let go of removed track(s), without the lock held
3371 // since we can't guarantee the destructors won't acquire that
3372 // same lock. This will also mutate and push a new fast mixer state.
3373 threadLoop_removeTracks(tracksToRemove);
3374 tracksToRemove.clear();
3375
3376 // FIXME I don't understand the need for this here;
3377 // it was in the original code but maybe the
3378 // assignment in saveOutputTracks() makes this unnecessary?
3379 clearOutputTracks();
3380
3381 // Effect chains will be actually deleted here if they were removed from
3382 // mEffectChains list during mixing or effects processing
3383 effectChains.clear();
3384
3385 // FIXME Note that the above .clear() is no longer necessary since effectChains
3386 // is now local to this block, but will keep it for now (at least until merge done).
3387 }
3388
Eric Laurentbfb1b832013-01-07 09:53:42 -08003389 threadLoop_exit();
3390
Eric Laurentcf817a22014-08-04 20:36:31 -07003391 if (!mStandby) {
3392 threadLoop_standby();
3393 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003394 }
3395
3396 releaseWakeLock();
3397
3398 ALOGV("Thread %p type %d exiting", this, mType);
3399 return false;
3400}
3401
Eric Laurentbfb1b832013-01-07 09:53:42 -08003402// removeTracks_l() must be called with ThreadBase::mLock held
3403void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3404{
3405 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003406 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003407 for (size_t i=0 ; i<count ; i++) {
3408 const sp<Track>& track = tracksToRemove.itemAt(i);
3409 mActiveTracks.remove(track);
3410 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3411 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3412 if (chain != 0) {
3413 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3414 track->sessionId());
3415 chain->decActiveTrackCnt();
3416 }
3417 if (track->isTerminated()) {
3418 removeTrack_l(track);
3419 }
3420 }
3421 }
3422
3423}
Eric Laurent81784c32012-11-19 14:55:58 -08003424
Eric Laurentaccc1472013-09-20 09:36:34 -07003425status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3426{
3427 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003428 ExtendedTimestamp ets;
3429 status_t status = mNormalSink->getTimestamp(ets);
3430 if (status == NO_ERROR) {
3431 status = ets.getBestTimestamp(&timestamp);
3432 }
3433 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003434 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003435 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003436 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003437 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003438 timestamp.mPosition = (uint32_t)position64;
3439 return NO_ERROR;
3440 }
3441 }
3442 return INVALID_OPERATION;
3443}
Eric Laurent1c333e22014-05-20 10:48:17 -07003444
Eric Laurent054d9d32015-04-24 08:48:48 -07003445status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3446 audio_patch_handle_t *handle)
3447{
Andy Hungf60abce2016-08-26 11:37:54 -07003448 status_t status;
3449 if (property_get_bool("af.patch_park", false /* default_value */)) {
3450 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3451 // or if HAL does not properly lock against access.
3452 AutoPark<FastMixer> park(mFastMixer);
3453 status = PlaybackThread::createAudioPatch_l(patch, handle);
3454 } else {
3455 status = PlaybackThread::createAudioPatch_l(patch, handle);
3456 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003457 return status;
3458}
3459
Eric Laurent1c333e22014-05-20 10:48:17 -07003460status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3461 audio_patch_handle_t *handle)
3462{
3463 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003464
3465 // store new device and send to effects
3466 audio_devices_t type = AUDIO_DEVICE_NONE;
3467 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3468 type |= patch->sinks[i].ext.device.type;
3469 }
3470
3471#ifdef ADD_BATTERY_DATA
3472 // when changing the audio output device, call addBatteryData to notify
3473 // the change
3474 if (mOutDevice != type) {
3475 uint32_t params = 0;
3476 // check whether speaker is on
3477 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3478 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003479 }
3480
Eric Laurent054d9d32015-04-24 08:48:48 -07003481 audio_devices_t deviceWithoutSpeaker
3482 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3483 // check if any other device (except speaker) is on
3484 if (type & deviceWithoutSpeaker) {
3485 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3486 }
3487
3488 if (params != 0) {
3489 addBatteryData(params);
3490 }
3491 }
3492#endif
3493
3494 for (size_t i = 0; i < mEffectChains.size(); i++) {
3495 mEffectChains[i]->setDevice_l(type);
3496 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003497
3498 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3499 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3500 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003501 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003502 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003503
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003504 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003505 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3506 status = hwDevice->createAudioPatch(patch->num_sources,
3507 patch->sources,
3508 patch->num_sinks,
3509 patch->sinks,
3510 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003511 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003512 char *address;
3513 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3514 //FIXME: we only support address on first sink with HAL version < 3.0
3515 address = audio_device_address_to_parameter(
3516 patch->sinks[0].ext.device.type,
3517 patch->sinks[0].ext.device.address);
3518 } else {
3519 address = (char *)calloc(1, 1);
3520 }
3521 AudioParameter param = AudioParameter(String8(address));
3522 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003523 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003524 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003525 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003526 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003527 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003528 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003529 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3530 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003531 return status;
3532}
3533
Eric Laurent054d9d32015-04-24 08:48:48 -07003534status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3535{
Andy Hungf60abce2016-08-26 11:37:54 -07003536 status_t status;
3537 if (property_get_bool("af.patch_park", false /* default_value */)) {
3538 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3539 // or if HAL does not properly lock against access.
3540 AutoPark<FastMixer> park(mFastMixer);
3541 status = PlaybackThread::releaseAudioPatch_l(handle);
3542 } else {
3543 status = PlaybackThread::releaseAudioPatch_l(handle);
3544 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003545 return status;
3546}
3547
Eric Laurent1c333e22014-05-20 10:48:17 -07003548status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3549{
3550 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003551
3552 mOutDevice = AUDIO_DEVICE_NONE;
3553
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003554 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003555 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3556 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003557 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003558 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003559 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003560 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003561 }
3562 return status;
3563}
3564
Eric Laurent83b88082014-06-20 18:31:16 -07003565void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3566{
3567 Mutex::Autolock _l(mLock);
3568 mTracks.add(track);
3569}
3570
3571void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3572{
3573 Mutex::Autolock _l(mLock);
3574 destroyTrack_l(track);
3575}
3576
3577void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3578{
3579 ThreadBase::getAudioPortConfig(config);
3580 config->role = AUDIO_PORT_ROLE_SOURCE;
3581 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3582 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3583}
3584
Eric Laurent81784c32012-11-19 14:55:58 -08003585// ----------------------------------------------------------------------------
3586
3587AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003588 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3589 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003590 // mAudioMixer below
3591 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003592 mFastMixerFutex(0),
3593 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // mOutputSink below
3595 // mPipeSink below
3596 // mNormalSink below
3597{
3598 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003599 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%d, mFrameSize=%zu, "
3600 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003601 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3602 mNormalFrameCount);
3603 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3604
Andy Hungfbfc3952015-01-15 13:33:51 -08003605 if (type == DUPLICATING) {
3606 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3607 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3608 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3609 return;
3610 }
Eric Laurent81784c32012-11-19 14:55:58 -08003611 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003612 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003613 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003614 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003615#if !LOG_NDEBUG
3616 ssize_t index =
3617#else
3618 (void)
3619#endif
3620 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003621 ALOG_ASSERT(index == 0);
3622
3623 // initialize fast mixer depending on configuration
3624 bool initFastMixer;
3625 switch (kUseFastMixer) {
3626 case FastMixer_Never:
3627 initFastMixer = false;
3628 break;
3629 case FastMixer_Always:
3630 initFastMixer = true;
3631 break;
3632 case FastMixer_Static:
3633 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003634 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3635 // where the period is less than an experimentally determined threshold that can be
3636 // scheduled reliably with CFS. However, the BT A2DP HAL is
3637 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3638 initFastMixer = mFrameCount < mNormalFrameCount
3639 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003640 break;
3641 }
Andy Hungfda69402017-02-15 14:33:12 -08003642 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3643 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3644 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003645 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003646 audio_format_t fastMixerFormat;
3647 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3648 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3649 } else {
3650 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3651 }
3652 if (mFormat != fastMixerFormat) {
3653 // change our Sink format to accept our intermediate precision
3654 mFormat = fastMixerFormat;
3655 free(mSinkBuffer);
3656 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3657 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3658 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3659 }
Eric Laurent81784c32012-11-19 14:55:58 -08003660
3661 // create a MonoPipe to connect our submix to FastMixer
3662 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003663#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003664 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003665#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003666 // adjust format to match that of the Fast Mixer
Glenn Kasten97b7b752014-09-28 13:04:24 -07003667 ALOGV("format changed from %d to %d", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003668 format.mFormat = fastMixerFormat;
3669 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3670
Eric Laurent81784c32012-11-19 14:55:58 -08003671 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3672 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3673 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3674 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3675 const NBAIO_Format offers[1] = {format};
3676 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003677#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003678 ssize_t index =
3679#else
3680 (void)
3681#endif
3682 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003683 ALOG_ASSERT(index == 0);
3684 monoPipe->setAvgFrames((mScreenState & 1) ?
3685 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3686 mPipeSink = monoPipe;
3687
Glenn Kasten46909e72013-02-26 09:20:22 -08003688#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003689 if (mTeeSinkOutputEnabled) {
3690 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003691 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3692 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003693 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003694 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003695 ALOG_ASSERT(index == 0);
3696 mTeeSink = teeSink;
3697 PipeReader *teeSource = new PipeReader(*teeSink);
3698 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003699 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003700 ALOG_ASSERT(index == 0);
3701 mTeeSource = teeSource;
3702 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003703#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003704
3705 // create fast mixer and configure it initially with just one fast track for our submix
3706 mFastMixer = new FastMixer();
3707 FastMixerStateQueue *sq = mFastMixer->sq();
3708#ifdef STATE_QUEUE_DUMP
3709 sq->setObserverDump(&mStateQueueObserverDump);
3710 sq->setMutatorDump(&mStateQueueMutatorDump);
3711#endif
3712 FastMixerState *state = sq->begin();
3713 FastTrack *fastTrack = &state->mFastTracks[0];
3714 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3715 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3716 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003717 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3718 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003719 fastTrack->mGeneration++;
3720 state->mFastTracksGen++;
3721 state->mTrackMask = 1;
3722 // fast mixer will use the HAL output sink
3723 state->mOutputSink = mOutputSink.get();
3724 state->mOutputSinkGen++;
3725 state->mFrameCount = mFrameCount;
3726 state->mCommand = FastMixerState::COLD_IDLE;
3727 // already done in constructor initialization list
3728 //mFastMixerFutex = 0;
3729 state->mColdFutexAddr = &mFastMixerFutex;
3730 state->mColdGen++;
3731 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003732#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003733 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003734#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003735 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3736 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003737 sq->end();
3738 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3739
3740 // start the fast mixer
3741 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3742 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003743 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003744 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003745
3746#ifdef AUDIO_WATCHDOG
3747 // create and start the watchdog
3748 mAudioWatchdog = new AudioWatchdog();
3749 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3750 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3751 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003752 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003753#endif
3754
Eric Laurent81784c32012-11-19 14:55:58 -08003755 }
3756
3757 switch (kUseFastMixer) {
3758 case FastMixer_Never:
3759 case FastMixer_Dynamic:
3760 mNormalSink = mOutputSink;
3761 break;
3762 case FastMixer_Always:
3763 mNormalSink = mPipeSink;
3764 break;
3765 case FastMixer_Static:
3766 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3767 break;
3768 }
3769}
3770
3771AudioFlinger::MixerThread::~MixerThread()
3772{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003773 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003774 FastMixerStateQueue *sq = mFastMixer->sq();
3775 FastMixerState *state = sq->begin();
3776 if (state->mCommand == FastMixerState::COLD_IDLE) {
3777 int32_t old = android_atomic_inc(&mFastMixerFutex);
3778 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003779 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003780 }
3781 }
3782 state->mCommand = FastMixerState::EXIT;
3783 sq->end();
3784 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3785 mFastMixer->join();
3786 // Though the fast mixer thread has exited, it's state queue is still valid.
3787 // We'll use that extract the final state which contains one remaining fast track
3788 // corresponding to our sub-mix.
3789 state = sq->begin();
3790 ALOG_ASSERT(state->mTrackMask == 1);
3791 FastTrack *fastTrack = &state->mFastTracks[0];
3792 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3793 delete fastTrack->mBufferProvider;
3794 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003795 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003796#ifdef AUDIO_WATCHDOG
3797 if (mAudioWatchdog != 0) {
3798 mAudioWatchdog->requestExit();
3799 mAudioWatchdog->requestExitAndWait();
3800 mAudioWatchdog.clear();
3801 }
3802#endif
3803 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003804 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003805 delete mAudioMixer;
3806}
3807
3808
3809uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
3810{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003811 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003812 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3813 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
3814 }
3815 return latency;
3816}
3817
3818
3819void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
3820{
3821 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
3822}
3823
Eric Laurentbfb1b832013-01-07 09:53:42 -08003824ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003825{
3826 // FIXME we should only do one push per cycle; confirm this is true
3827 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003828 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003829 FastMixerStateQueue *sq = mFastMixer->sq();
3830 FastMixerState *state = sq->begin();
3831 if (state->mCommand != FastMixerState::MIX_WRITE &&
3832 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
3833 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07003834
3835 // FIXME workaround for first HAL write being CPU bound on some devices
3836 ATRACE_BEGIN("write");
3837 mOutput->write((char *)mSinkBuffer, 0);
3838 ATRACE_END();
3839
Eric Laurent81784c32012-11-19 14:55:58 -08003840 int32_t old = android_atomic_inc(&mFastMixerFutex);
3841 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003842 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003843 }
3844#ifdef AUDIO_WATCHDOG
3845 if (mAudioWatchdog != 0) {
3846 mAudioWatchdog->resume();
3847 }
3848#endif
3849 }
3850 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08003851#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07003852 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08003853 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08003854#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003855 sq->end();
3856 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3857 if (kUseFastMixer == FastMixer_Dynamic) {
3858 mNormalSink = mPipeSink;
3859 }
3860 } else {
3861 sq->end(false /*didModify*/);
3862 }
3863 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003864 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08003865}
3866
3867void AudioFlinger::MixerThread::threadLoop_standby()
3868{
3869 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003870 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003871 FastMixerStateQueue *sq = mFastMixer->sq();
3872 FastMixerState *state = sq->begin();
3873 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08003874 // Report any frames trapped in the Monopipe
3875 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
3876 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
3877 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
3878 "monoPipeWritten:%lld monoPipeLeft:%lld",
3879 (long long)mFramesWritten, (long long)mSuspendedFrames,
3880 (long long)mPipeSink->framesWritten(), pipeFrames);
3881 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
3882
Eric Laurent81784c32012-11-19 14:55:58 -08003883 state->mCommand = FastMixerState::COLD_IDLE;
3884 state->mColdFutexAddr = &mFastMixerFutex;
3885 state->mColdGen++;
3886 mFastMixerFutex = 0;
3887 sq->end();
3888 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
3889 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
3890 if (kUseFastMixer == FastMixer_Dynamic) {
3891 mNormalSink = mOutputSink;
3892 }
3893#ifdef AUDIO_WATCHDOG
3894 if (mAudioWatchdog != 0) {
3895 mAudioWatchdog->pause();
3896 }
3897#endif
3898 } else {
3899 sq->end(false /*didModify*/);
3900 }
3901 }
3902 PlaybackThread::threadLoop_standby();
3903}
3904
Eric Laurentbfb1b832013-01-07 09:53:42 -08003905bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
3906{
3907 return false;
3908}
3909
3910bool AudioFlinger::PlaybackThread::shouldStandby_l()
3911{
3912 return !mStandby;
3913}
3914
3915bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
3916{
3917 Mutex::Autolock _l(mLock);
3918 return waitingAsyncCallback_l();
3919}
3920
Eric Laurent81784c32012-11-19 14:55:58 -08003921// shared by MIXER and DIRECT, overridden by DUPLICATING
3922void AudioFlinger::PlaybackThread::threadLoop_standby()
3923{
3924 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08003925 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003927 // discard any pending drain or write ack by incrementing sequence
3928 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
3929 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003930 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003931 mCallbackThread->setWriteBlocked(mWriteAckSequence);
3932 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003933 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003934 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003935}
3936
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003937void AudioFlinger::PlaybackThread::onAddNewTrack_l()
3938{
3939 ALOGV("signal playback thread");
3940 broadcast_l();
3941}
3942
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003943void AudioFlinger::PlaybackThread::onAsyncError()
3944{
3945 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
3946 invalidateTracks((audio_stream_type_t)i);
3947 }
3948}
3949
Eric Laurent81784c32012-11-19 14:55:58 -08003950void AudioFlinger::MixerThread::threadLoop_mix()
3951{
Eric Laurent81784c32012-11-19 14:55:58 -08003952 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08003953 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08003954 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003955 // increase sleep time progressively when application underrun condition clears.
3956 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
3957 // that a steady state of alternating ready/not ready conditions keeps the sleep time
3958 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003959 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003960 sleepTimeShift--;
3961 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003962 mSleepTimeUs = 0;
3963 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08003964 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003965
Eric Laurent81784c32012-11-19 14:55:58 -08003966}
3967
3968void AudioFlinger::MixerThread::threadLoop_sleepTime()
3969{
3970 // If no tracks are ready, sleep once for the duration of an output
3971 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003972 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003973 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003974 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
3975 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
3976 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003977 }
3978 // reduce sleep time in case of consecutive application underruns to avoid
3979 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
3980 // duration we would end up writing less data than needed by the audio HAL if
3981 // the condition persists.
3982 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
3983 sleepTimeShift++;
3984 }
3985 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003986 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003987 }
3988 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08003989 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
3990 // before effects processing or output.
3991 if (mMixerBufferValid) {
3992 memset(mMixerBuffer, 0, mMixerBufferSize);
3993 } else {
3994 memset(mSinkBuffer, 0, mSinkBufferSize);
3995 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003996 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003997 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
3998 "anticipated start");
3999 }
4000 // TODO add standby time extension fct of effect tail
4001}
4002
4003// prepareTracks_l() must be called with ThreadBase::mLock held
4004AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4005 Vector< sp<Track> > *tracksToRemove)
4006{
4007
4008 mixer_state mixerStatus = MIXER_IDLE;
4009 // find out which tracks need to be processed
4010 size_t count = mActiveTracks.size();
4011 size_t mixedTracks = 0;
4012 size_t tracksWithEffect = 0;
4013 // counts only _active_ fast tracks
4014 size_t fastTracks = 0;
4015 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4016
4017 float masterVolume = mMasterVolume;
4018 bool masterMute = mMasterMute;
4019
4020 if (masterMute) {
4021 masterVolume = 0;
4022 }
4023 // Delegate master volume control to effect in output mix effect chain if needed
4024 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4025 if (chain != 0) {
4026 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4027 chain->setVolume_l(&v, &v);
4028 masterVolume = (float)((v + (1 << 23)) >> 24);
4029 chain.clear();
4030 }
4031
4032 // prepare a new state to push
4033 FastMixerStateQueue *sq = NULL;
4034 FastMixerState *state = NULL;
4035 bool didModify = false;
4036 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004037 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004038 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004039 sq = mFastMixer->sq();
4040 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004041 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004042 }
4043
Andy Hung69aed5f2014-02-25 17:24:40 -08004044 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004045 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004046
Eric Laurent81784c32012-11-19 14:55:58 -08004047 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004048 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004049
4050 // this const just means the local variable doesn't change
4051 Track* const track = t.get();
4052
4053 // process fast tracks
4054 if (track->isFastTrack()) {
4055
4056 // It's theoretically possible (though unlikely) for a fast track to be created
4057 // and then removed within the same normal mix cycle. This is not a problem, as
4058 // the track never becomes active so it's fast mixer slot is never touched.
4059 // The converse, of removing an (active) track and then creating a new track
4060 // at the identical fast mixer slot within the same normal mix cycle,
4061 // is impossible because the slot isn't marked available until the end of each cycle.
4062 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004063 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004064 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4065 FastTrack *fastTrack = &state->mFastTracks[j];
4066
4067 // Determine whether the track is currently in underrun condition,
4068 // and whether it had a recent underrun.
4069 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4070 FastTrackUnderruns underruns = ftDump->mUnderruns;
4071 uint32_t recentFull = (underruns.mBitFields.mFull -
4072 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4073 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4074 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4075 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4076 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4077 uint32_t recentUnderruns = recentPartial + recentEmpty;
4078 track->mObservedUnderruns = underruns;
4079 // don't count underruns that occur while stopping or pausing
4080 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004081 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4082 recentUnderruns > 0) {
4083 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4084 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004085 } else {
4086 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004087 }
4088
4089 // This is similar to the state machine for normal tracks,
4090 // with a few modifications for fast tracks.
4091 bool isActive = true;
4092 switch (track->mState) {
4093 case TrackBase::STOPPING_1:
4094 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004095 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004096 track->mState = TrackBase::STOPPING_2;
4097 }
4098 break;
4099 case TrackBase::PAUSING:
4100 // ramp down is not yet implemented
4101 track->setPaused();
4102 break;
4103 case TrackBase::RESUMING:
4104 // ramp up is not yet implemented
4105 track->mState = TrackBase::ACTIVE;
4106 break;
4107 case TrackBase::ACTIVE:
4108 if (recentFull > 0 || recentPartial > 0) {
4109 // track has provided at least some frames recently: reset retry count
4110 track->mRetryCount = kMaxTrackRetries;
4111 }
4112 if (recentUnderruns == 0) {
4113 // no recent underruns: stay active
4114 break;
4115 }
4116 // there has recently been an underrun of some kind
4117 if (track->sharedBuffer() == 0) {
4118 // were any of the recent underruns "empty" (no frames available)?
4119 if (recentEmpty == 0) {
4120 // no, then ignore the partial underruns as they are allowed indefinitely
4121 break;
4122 }
4123 // there has recently been an "empty" underrun: decrement the retry counter
4124 if (--(track->mRetryCount) > 0) {
4125 break;
4126 }
4127 // indicate to client process that the track was disabled because of underrun;
4128 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004129 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004130 // remove from active list, but state remains ACTIVE [confusing but true]
4131 isActive = false;
4132 break;
4133 }
4134 // fall through
4135 case TrackBase::STOPPING_2:
4136 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004137 case TrackBase::STOPPED:
4138 case TrackBase::FLUSHED: // flush() while active
4139 // Check for presentation complete if track is inactive
4140 // We have consumed all the buffers of this track.
4141 // This would be incomplete if we auto-paused on underrun
4142 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004143 uint32_t latency = 0;
4144 status_t result = mOutput->stream->getLatency(&latency);
4145 ALOGE_IF(result != OK,
4146 "Error when retrieving output stream latency: %d", result);
4147 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004148 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004149 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4150 // track stays in active list until presentation is complete
4151 break;
4152 }
4153 }
4154 if (track->isStopping_2()) {
4155 track->mState = TrackBase::STOPPED;
4156 }
4157 if (track->isStopped()) {
4158 // Can't reset directly, as fast mixer is still polling this track
4159 // track->reset();
4160 // So instead mark this track as needing to be reset after push with ack
4161 resetMask |= 1 << i;
4162 }
4163 isActive = false;
4164 break;
4165 case TrackBase::IDLE:
4166 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004167 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004168 }
4169
4170 if (isActive) {
4171 // was it previously inactive?
4172 if (!(state->mTrackMask & (1 << j))) {
4173 ExtendedAudioBufferProvider *eabp = track;
4174 VolumeProvider *vp = track;
4175 fastTrack->mBufferProvider = eabp;
4176 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004177 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004178 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004179 fastTrack->mGeneration++;
4180 state->mTrackMask |= 1 << j;
4181 didModify = true;
4182 // no acknowledgement required for newly active tracks
4183 }
4184 // cache the combined master volume and stream type volume for fast mixer; this
4185 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004186 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004187 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004188 track->mCachedVolume = masterVolume
4189 * mStreamTypes[track->streamType()].volume
4190 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004191 ++fastTracks;
4192 } else {
4193 // was it previously active?
4194 if (state->mTrackMask & (1 << j)) {
4195 fastTrack->mBufferProvider = NULL;
4196 fastTrack->mGeneration++;
4197 state->mTrackMask &= ~(1 << j);
4198 didModify = true;
4199 // If any fast tracks were removed, we must wait for acknowledgement
4200 // because we're about to decrement the last sp<> on those tracks.
4201 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4202 } else {
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004203 LOG_ALWAYS_FATAL("fast track %d should have been active; "
4204 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4205 j, track->mState, state->mTrackMask, recentUnderruns,
4206 track->sharedBuffer() != 0);
Eric Laurent81784c32012-11-19 14:55:58 -08004207 }
4208 tracksToRemove->add(track);
4209 // Avoids a misleading display in dumpsys
4210 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4211 }
4212 continue;
4213 }
4214
4215 { // local variable scope to avoid goto warning
4216
4217 audio_track_cblk_t* cblk = track->cblk();
4218
4219 // The first time a track is added we wait
4220 // for all its buffers to be filled before processing it
4221 int name = track->name();
4222 // make sure that we have enough frames to mix one full buffer.
4223 // enforce this condition only once to enable draining the buffer in case the client
4224 // app does not call stop() and relies on underrun to stop:
4225 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4226 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004227 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004228 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004229 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004230
4231 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004232 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004233 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4234 // add frames already consumed but not yet released by the resampler
4235 // because mAudioTrackServerProxy->framesReady() will include these frames
4236 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4237
Eric Laurent81784c32012-11-19 14:55:58 -08004238 uint32_t minFrames = 1;
4239 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4240 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004241 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004242 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004243
4244 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004245 if (ATRACE_ENABLED()) {
4246 // I wish we had formatted trace names
4247 char traceName[16];
4248 strcpy(traceName, "nRdy");
4249 int name = track->name();
4250 if (AudioMixer::TRACK0 <= name &&
4251 name < (int) (AudioMixer::TRACK0 + AudioMixer::MAX_NUM_TRACKS)) {
4252 name -= AudioMixer::TRACK0;
4253 traceName[4] = (name / 10) + '0';
4254 traceName[5] = (name % 10) + '0';
4255 } else {
4256 traceName[4] = '?';
4257 traceName[5] = '?';
4258 }
4259 traceName[6] = '\0';
4260 ATRACE_INT(traceName, framesReady);
4261 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004262 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004263 !track->isPaused() && !track->isTerminated())
4264 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004265 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004266
4267 mixedTracks++;
4268
Andy Hung69aed5f2014-02-25 17:24:40 -08004269 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4270 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004271 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004272 if (track->mainBuffer() != mSinkBuffer &&
4273 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004274 if (mEffectBufferEnabled) {
4275 mEffectBufferValid = true; // Later can set directly.
4276 }
Eric Laurent81784c32012-11-19 14:55:58 -08004277 chain = getEffectChain_l(track->sessionId());
4278 // Delegate volume control to effect in track effect chain if needed
4279 if (chain != 0) {
4280 tracksWithEffect++;
4281 } else {
4282 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4283 "session %d",
4284 name, track->sessionId());
4285 }
4286 }
4287
4288
4289 int param = AudioMixer::VOLUME;
4290 if (track->mFillingUpStatus == Track::FS_FILLED) {
4291 // no ramp for the first volume setting
4292 track->mFillingUpStatus = Track::FS_ACTIVE;
4293 if (track->mState == TrackBase::RESUMING) {
4294 track->mState = TrackBase::ACTIVE;
4295 param = AudioMixer::RAMP_VOLUME;
4296 }
4297 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004298 // FIXME should not make a decision based on mServer
4299 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004300 // If the track is stopped before the first frame was mixed,
4301 // do not apply ramp
4302 param = AudioMixer::RAMP_VOLUME;
4303 }
4304
4305 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004306 uint32_t vl, vr; // in U8.24 integer format
4307 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Glenn Kastene4756fe2012-11-29 13:38:14 -08004308 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004309 vl = vr = 0;
4310 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004311 if (track->isPausing()) {
4312 track->setPaused();
4313 }
4314 } else {
4315
4316 // read original volumes with volume control
4317 float typeVolume = mStreamTypes[track->streamType()].volume;
4318 float v = masterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004319 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004320 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004321 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4322 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004323 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004324 if (vlf > GAIN_FLOAT_UNITY) {
4325 ALOGV("Track left volume out of range: %.3g", vlf);
4326 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004327 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004328 if (vrf > GAIN_FLOAT_UNITY) {
4329 ALOGV("Track right volume out of range: %.3g", vrf);
4330 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004331 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004332 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004333 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004334 // now apply the master volume and stream type volume and shaper volume
4335 vlf *= v * vh;
4336 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004337 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004338 // then derive vl and vr as U8.24 versions for the effect chain
4339 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4340 vl = (uint32_t) (scaleto8_24 * vlf);
4341 vr = (uint32_t) (scaleto8_24 * vrf);
4342 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004343 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004344 // send level comes from shared memory and so may be corrupt
4345 if (sendLevel > MAX_GAIN_INT) {
4346 ALOGV("Track send level out of range: %04X", sendLevel);
4347 sendLevel = MAX_GAIN_INT;
4348 }
Andy Hung6be49402014-05-30 10:42:03 -07004349 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4350 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004351 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352
Eric Laurent81784c32012-11-19 14:55:58 -08004353 // Delegate volume control to effect in track effect chain if needed
4354 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4355 // Do not ramp volume if volume is controlled by effect
4356 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004357 // Update remaining floating point volume levels
4358 vlf = (float)vl / (1 << 24);
4359 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004360 track->mHasVolumeController = true;
4361 } else {
4362 // force no volume ramp when volume controller was just disabled or removed
4363 // from effect chain to avoid volume spike
4364 if (track->mHasVolumeController) {
4365 param = AudioMixer::VOLUME;
4366 }
4367 track->mHasVolumeController = false;
4368 }
4369
Eric Laurent81784c32012-11-19 14:55:58 -08004370 // XXX: these things DON'T need to be done each time
4371 mAudioMixer->setBufferProvider(name, track);
4372 mAudioMixer->enable(name);
4373
Andy Hung6be49402014-05-30 10:42:03 -07004374 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4375 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4376 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004377 mAudioMixer->setParameter(
4378 name,
4379 AudioMixer::TRACK,
4380 AudioMixer::FORMAT, (void *)track->format());
4381 mAudioMixer->setParameter(
4382 name,
4383 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004384 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004385 mAudioMixer->setParameter(
4386 name,
4387 AudioMixer::TRACK,
4388 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004389 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004390 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004391 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004392 if (reqSampleRate == 0) {
4393 reqSampleRate = mSampleRate;
4394 } else if (reqSampleRate > maxSampleRate) {
4395 reqSampleRate = maxSampleRate;
4396 }
Eric Laurent81784c32012-11-19 14:55:58 -08004397 mAudioMixer->setParameter(
4398 name,
4399 AudioMixer::RESAMPLE,
4400 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004401 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004402
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004403 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004404 mAudioMixer->setParameter(
4405 name,
4406 AudioMixer::TIMESTRETCH,
4407 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004408 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004409
Andy Hung69aed5f2014-02-25 17:24:40 -08004410 /*
4411 * Select the appropriate output buffer for the track.
4412 *
Andy Hung98ef9782014-03-04 14:46:50 -08004413 * Tracks with effects go into their own effects chain buffer
4414 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004415 *
4416 * Other tracks can use mMixerBuffer for higher precision
4417 * channel accumulation. If this buffer is enabled
4418 * (mMixerBufferEnabled true), then selected tracks will accumulate
4419 * into it.
4420 *
4421 */
4422 if (mMixerBufferEnabled
4423 && (track->mainBuffer() == mSinkBuffer
4424 || track->mainBuffer() == mMixerBuffer)) {
4425 mAudioMixer->setParameter(
4426 name,
4427 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004428 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004429 mAudioMixer->setParameter(
4430 name,
4431 AudioMixer::TRACK,
4432 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4433 // TODO: override track->mainBuffer()?
4434 mMixerBufferValid = true;
4435 } else {
4436 mAudioMixer->setParameter(
4437 name,
4438 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004439 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_16_BIT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004440 mAudioMixer->setParameter(
4441 name,
4442 AudioMixer::TRACK,
4443 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4444 }
Eric Laurent81784c32012-11-19 14:55:58 -08004445 mAudioMixer->setParameter(
4446 name,
4447 AudioMixer::TRACK,
4448 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4449
4450 // reset retry count
4451 track->mRetryCount = kMaxTrackRetries;
4452
4453 // If one track is ready, set the mixer ready if:
4454 // - the mixer was not ready during previous round OR
4455 // - no other track is not ready
4456 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4457 mixerStatus != MIXER_TRACKS_ENABLED) {
4458 mixerStatus = MIXER_TRACKS_READY;
4459 }
4460 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004461 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004462 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4463 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004464 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004465 } else {
4466 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004467 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004468
Eric Laurent81784c32012-11-19 14:55:58 -08004469 // clear effect chain input buffer if an active track underruns to avoid sending
4470 // previous audio buffer again to effects
4471 chain = getEffectChain_l(track->sessionId());
4472 if (chain != 0) {
4473 chain->clearInputBuffer();
4474 }
4475
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004476 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004477 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4478 track->isStopped() || track->isPaused()) {
4479 // We have consumed all the buffers of this track.
4480 // Remove it from the list of active tracks.
4481 // TODO: use actual buffer filling status instead of latency when available from
4482 // audio HAL
4483 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004484 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004485 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4486 if (track->isStopped()) {
4487 track->reset();
4488 }
4489 tracksToRemove->add(track);
4490 }
4491 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004492 // No buffers for this track. Give it a few chances to
4493 // fill a buffer, then remove it from active list.
4494 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004495 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004496 tracksToRemove->add(track);
4497 // indicate to client process that the track was disabled because of underrun;
4498 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004499 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004500 // If one track is not ready, mark the mixer also not ready if:
4501 // - the mixer was ready during previous round OR
4502 // - no other track is ready
4503 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4504 mixerStatus != MIXER_TRACKS_READY) {
4505 mixerStatus = MIXER_TRACKS_ENABLED;
4506 }
4507 }
4508 mAudioMixer->disable(name);
4509 }
4510
4511 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004512
4513 }
4514
4515 // Push the new FastMixer state if necessary
4516 bool pauseAudioWatchdog = false;
4517 if (didModify) {
4518 state->mFastTracksGen++;
4519 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4520 if (kUseFastMixer == FastMixer_Dynamic &&
4521 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4522 state->mCommand = FastMixerState::COLD_IDLE;
4523 state->mColdFutexAddr = &mFastMixerFutex;
4524 state->mColdGen++;
4525 mFastMixerFutex = 0;
4526 if (kUseFastMixer == FastMixer_Dynamic) {
4527 mNormalSink = mOutputSink;
4528 }
4529 // If we go into cold idle, need to wait for acknowledgement
4530 // so that fast mixer stops doing I/O.
4531 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4532 pauseAudioWatchdog = true;
4533 }
Eric Laurent81784c32012-11-19 14:55:58 -08004534 }
4535 if (sq != NULL) {
4536 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004537 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4538 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4539 // when bringing the output sink into standby.)
4540 //
4541 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4542 //
4543 // This occurs with BT suspend when we idle the FastMixer with
4544 // active tracks, which may be added or removed.
4545 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004546 }
4547#ifdef AUDIO_WATCHDOG
4548 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4549 mAudioWatchdog->pause();
4550 }
4551#endif
4552
4553 // Now perform the deferred reset on fast tracks that have stopped
4554 while (resetMask != 0) {
4555 size_t i = __builtin_ctz(resetMask);
4556 ALOG_ASSERT(i < count);
4557 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004558 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004559 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4560 track->reset();
4561 }
4562
4563 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004565
Eric Laurent97d547d2014-09-02 14:45:53 -07004566 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4567 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004568 }
4569
4570 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004571 // as long as there are effects we should clear the effects buffer, to avoid
4572 // passing a non-clean buffer to the effect chain
4573 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004574 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004575 // sink or mix buffer must be cleared if all tracks are connected to an
4576 // effect chain as in this case the mixer will not write to the sink or mix buffer
4577 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004578 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4579 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004580 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004581 if (mMixerBufferValid) {
4582 memset(mMixerBuffer, 0, mMixerBufferSize);
4583 // TODO: In testing, mSinkBuffer below need not be cleared because
4584 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4585 // after mixing.
4586 //
4587 // To enforce this guarantee:
4588 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4589 // (mixedTracks == 0 && fastTracks > 0))
4590 // must imply MIXER_TRACKS_READY.
4591 // Later, we may clear buffers regardless, and skip much of this logic.
4592 }
Andy Hung98ef9782014-03-04 14:46:50 -08004593 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004594 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004595 }
4596
4597 // if any fast tracks, then status is ready
4598 mMixerStatusIgnoringFastTracks = mixerStatus;
4599 if (fastTracks > 0) {
4600 mixerStatus = MIXER_TRACKS_READY;
4601 }
4602 return mixerStatus;
4603}
4604
Eric Laurentad7dd962016-09-22 12:38:37 -07004605// trackCountForUid_l() must be called with ThreadBase::mLock held
4606uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid)
4607{
4608 uint32_t trackCount = 0;
4609 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004610 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004611 trackCount++;
4612 }
4613 }
4614 return trackCount;
4615}
4616
Eric Laurent81784c32012-11-19 14:55:58 -08004617// getTrackName_l() must be called with ThreadBase::mLock held
Andy Hunge8a1ced2014-05-09 15:02:21 -07004618int AudioFlinger::MixerThread::getTrackName_l(audio_channel_mask_t channelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004619 audio_format_t format, audio_session_t sessionId, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08004620{
Eric Laurentad7dd962016-09-22 12:38:37 -07004621 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
4622 return -1;
4623 }
Andy Hunge8a1ced2014-05-09 15:02:21 -07004624 return mAudioMixer->getTrackName(channelMask, format, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08004625}
4626
4627// deleteTrackName_l() must be called with ThreadBase::mLock held
4628void AudioFlinger::MixerThread::deleteTrackName_l(int name)
4629{
4630 ALOGV("remove track (%d) and delete from mixer", name);
4631 mAudioMixer->deleteTrackName(name);
4632}
4633
Eric Laurent10351942014-05-08 18:49:52 -07004634// checkForNewParameter_l() must be called with ThreadBase::mLock held
4635bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4636 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004637{
Eric Laurent81784c32012-11-19 14:55:58 -08004638 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004639 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004640
Eric Laurent10351942014-05-08 18:49:52 -07004641 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004642
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004643 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004644
Eric Laurent10351942014-05-08 18:49:52 -07004645 AudioParameter param = AudioParameter(keyValuePair);
4646 int value;
4647 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4648 reconfig = true;
4649 }
4650 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004651 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004652 status = BAD_VALUE;
4653 } else {
4654 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004655 reconfig = true;
4656 }
Eric Laurent10351942014-05-08 18:49:52 -07004657 }
4658 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004659 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004660 status = BAD_VALUE;
4661 } else {
4662 // no need to save value, since it's constant
4663 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004664 }
Eric Laurent10351942014-05-08 18:49:52 -07004665 }
4666 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4667 // do not accept frame count changes if tracks are open as the track buffer
4668 // size depends on frame count and correct behavior would not be guaranteed
4669 // if frame count is changed after track creation
4670 if (!mTracks.isEmpty()) {
4671 status = INVALID_OPERATION;
4672 } else {
4673 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004674 }
Eric Laurent10351942014-05-08 18:49:52 -07004675 }
4676 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004677#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004678 // when changing the audio output device, call addBatteryData to notify
4679 // the change
4680 if (mOutDevice != value) {
4681 uint32_t params = 0;
4682 // check whether speaker is on
4683 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4684 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004685 }
Eric Laurent10351942014-05-08 18:49:52 -07004686
4687 audio_devices_t deviceWithoutSpeaker
4688 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4689 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004690 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004691 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4692 }
4693
4694 if (params != 0) {
4695 addBatteryData(params);
4696 }
4697 }
Eric Laurent81784c32012-11-19 14:55:58 -08004698#endif
4699
Eric Laurent10351942014-05-08 18:49:52 -07004700 // forward device change to effects that have requested to be
4701 // aware of attached audio device.
4702 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004703 a2dpDeviceChanged =
4704 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004705 mOutDevice = value;
4706 for (size_t i = 0; i < mEffectChains.size(); i++) {
4707 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004708 }
4709 }
Eric Laurent10351942014-05-08 18:49:52 -07004710 }
Eric Laurent81784c32012-11-19 14:55:58 -08004711
Eric Laurent10351942014-05-08 18:49:52 -07004712 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004713 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004714 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004715 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004716 mStandby = true;
4717 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004718 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004719 }
Eric Laurent10351942014-05-08 18:49:52 -07004720 if (status == NO_ERROR && reconfig) {
4721 readOutputParameters_l();
4722 delete mAudioMixer;
4723 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4724 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hunge8a1ced2014-05-09 15:02:21 -07004725 int name = getTrackName_l(mTracks[i]->mChannelMask,
Eric Laurentad7dd962016-09-22 12:38:37 -07004726 mTracks[i]->mFormat, mTracks[i]->mSessionId, mTracks[i]->uid());
Eric Laurent10351942014-05-08 18:49:52 -07004727 if (name < 0) {
4728 break;
4729 }
4730 mTracks[i]->mName = name;
4731 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004732 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004733 }
Eric Laurent81784c32012-11-19 14:55:58 -08004734 }
4735
Eric Laurent42537be2016-01-08 17:16:42 -08004736 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004737}
4738
4739
4740void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4741{
Eric Laurent81784c32012-11-19 14:55:58 -08004742 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004743 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Elliott Hughes87cebad2014-05-22 10:14:43 -07004744 dprintf(fd, " AudioMixer tracks: 0x%08x\n", mAudioMixer->trackNames());
Andy Hung2ddee192015-12-18 17:34:44 -08004745 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004746
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004747 if (hasFastMixer()) {
4748 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4749
4750 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4751 // while we are dumping it. It may be inconsistent, but it won't mutate!
4752 // This is a large object so we place it on the heap.
4753 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4754 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4755 copy->dump(fd);
4756 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004757
4758#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004759 // Similar for state queue
4760 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
4761 observerCopy.dump(fd);
4762 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
4763 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08004764#endif
4765
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004766#ifdef AUDIO_WATCHDOG
4767 if (mAudioWatchdog != 0) {
4768 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
4769 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
4770 wdCopy.dump(fd);
4771 }
4772#endif
4773
4774 } else {
4775 dprintf(fd, " No FastMixer\n");
4776 }
4777
Glenn Kasten46909e72013-02-26 09:20:22 -08004778#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08004779 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07004780 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08004781#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004782
Eric Laurent81784c32012-11-19 14:55:58 -08004783}
4784
4785uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
4786{
4787 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
4788}
4789
4790uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
4791{
4792 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
4793}
4794
4795void AudioFlinger::MixerThread::cacheParameters_l()
4796{
4797 PlaybackThread::cacheParameters_l();
4798
4799 // FIXME: Relaxed timing because of a certain device that can't meet latency
4800 // Should be reduced to 2x after the vendor fixes the driver issue
4801 // increase threshold again due to low power audio mode. The way this warning
4802 // threshold is calculated and its usefulness should be reconsidered anyway.
4803 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
4804}
4805
4806// ----------------------------------------------------------------------------
4807
4808AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07004809 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
4810 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08004811 // mLeftVolFloat, mRightVolFloat
4812{
4813}
4814
Eric Laurentbfb1b832013-01-07 09:53:42 -08004815AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
4816 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07004817 ThreadBase::type_t type, bool systemReady)
4818 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819 // mLeftVolFloat, mRightVolFloat
Andy Hung10cbff12017-02-21 17:30:14 -08004820 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004821{
4822}
4823
Eric Laurent81784c32012-11-19 14:55:58 -08004824AudioFlinger::DirectOutputThread::~DirectOutputThread()
4825{
4826}
4827
Eric Laurent5850c4c2016-11-10 13:04:31 -08004828void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829{
Eric Laurentbfb1b832013-01-07 09:53:42 -08004830 float left, right;
4831
4832 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
4833 left = right = 0;
4834 } else {
4835 float typeVolume = mStreamTypes[track->streamType()].volume;
4836 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07004837 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004838
Andy Hung10cbff12017-02-21 17:30:14 -08004839 // Get volumeshaper scaling
4840 std::pair<float /* volume */, bool /* active */>
4841 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004842 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08004843 v *= vh.first;
4844 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004845
Glenn Kastenc56f3422014-03-21 17:53:17 -07004846 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4847 left = float_from_gain(gain_minifloat_unpack_left(vlr));
4848 if (left > GAIN_FLOAT_UNITY) {
4849 left = GAIN_FLOAT_UNITY;
4850 }
4851 left *= v;
4852 right = float_from_gain(gain_minifloat_unpack_right(vlr));
4853 if (right > GAIN_FLOAT_UNITY) {
4854 right = GAIN_FLOAT_UNITY;
4855 }
4856 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004857 }
4858
4859 if (lastTrack) {
4860 if (left != mLeftVolFloat || right != mRightVolFloat) {
4861 mLeftVolFloat = left;
4862 mRightVolFloat = right;
4863
4864 // Convert volumes from float to 8.24
4865 uint32_t vl = (uint32_t)(left * (1 << 24));
4866 uint32_t vr = (uint32_t)(right * (1 << 24));
4867
4868 // Delegate volume control to effect in track effect chain if needed
4869 // only one effect chain can be present on DirectOutputThread, so if
4870 // there is one, the track is connected to it
4871 if (!mEffectChains.isEmpty()) {
4872 mEffectChains[0]->setVolume_l(&vl, &vr);
4873 left = (float)vl / (1 << 24);
4874 right = (float)vr / (1 << 24);
4875 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004876 status_t result = mOutput->stream->setVolume(left, right);
4877 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 }
4879 }
4880}
4881
Phil Burk43b4dcc2015-06-09 16:53:44 -07004882void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
4883{
4884 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07004885 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004886
Eric Laurent0f0631e2015-07-06 18:01:25 -07004887 if (previousTrack != 0 && latestTrack != 0) {
4888 if (mType == DIRECT) {
4889 if (previousTrack.get() != latestTrack.get()) {
4890 mFlushPending = true;
4891 }
4892 } else /* mType == OFFLOAD */ {
4893 if (previousTrack->sessionId() != latestTrack->sessionId()) {
4894 mFlushPending = true;
4895 }
4896 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07004897 }
4898 PlaybackThread::onAddNewTrack_l();
4899}
Eric Laurentbfb1b832013-01-07 09:53:42 -08004900
Eric Laurent81784c32012-11-19 14:55:58 -08004901AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
4902 Vector< sp<Track> > *tracksToRemove
4903)
4904{
Eric Laurentd595b7c2013-04-03 17:27:56 -07004905 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08004906 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004907 bool doHwPause = false;
4908 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004909
4910 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07004911 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08004912 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004913 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08004914 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07004915 continue;
4916 }
4917
Eric Laurent5850c4c2016-11-10 13:04:31 -08004918 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004919#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08004920 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004921#endif
Eric Laurentfd477972013-10-25 18:10:40 -07004922 // Only consider last track started for volume and mixer state control.
4923 // In theory an older track could underrun and restart after the new one starts
4924 // but as we only care about the transition phase between two tracks on a
4925 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07004926 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08004927 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08004928
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004929 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004930 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004931 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004932 doHwPause = true;
4933 mHwPaused = true;
4934 }
4935 tracksToRemove->add(track);
4936 } else if (track->isFlushPending()) {
4937 track->flushAck();
4938 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004939 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08004940 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07004941 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08004942 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07004943 if (last) {
4944 mLeftVolFloat = mRightVolFloat = -1.0;
4945 if (mHwPaused) {
4946 doHwResume = true;
4947 mHwPaused = false;
4948 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004949 }
4950 }
4951
Eric Laurent81784c32012-11-19 14:55:58 -08004952 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08004953 // for all its buffers to be filled before processing it.
4954 // Allow draining the buffer in case the client
4955 // app does not call stop() and relies on underrun to stop:
4956 // hence the test on (track->mRetryCount > 1).
4957 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07004958 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08004959 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08004960 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08004961 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004962 minFrames = mNormalFrameCount;
4963 } else {
4964 minFrames = 1;
4965 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004966
Eric Laurentab5cdba2014-06-09 17:22:27 -07004967 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
4968 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08004969 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004970 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08004971
4972 if (track->mFillingUpStatus == Track::FS_FILLED) {
4973 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07004974 if (last) {
4975 // make sure processVolume_l() will apply new volume even if 0
4976 mLeftVolFloat = mRightVolFloat = -1.0;
4977 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004978 if (!mHwSupportsPause) {
4979 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08004980 }
4981 }
4982
4983 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08004984 processVolume_l(track, last);
4985 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07004986 sp<Track> previousTrack = mPreviousTrack.promote();
4987 if (previousTrack != 0) {
4988 if (track != previousTrack.get()) {
4989 // Flush any data still being written from last track
4990 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07004991 // Invalidate previous track to force a seek when resuming.
4992 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07004993 }
4994 }
4995 mPreviousTrack = track;
4996
Eric Laurentd595b7c2013-04-03 17:27:56 -07004997 // reset retry count
4998 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08004999 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005000 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005001 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005002 doHwResume = true;
5003 mHwPaused = false;
5004 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005005 }
Eric Laurent81784c32012-11-19 14:55:58 -08005006 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005007 // clear effect chain input buffer if the last active track started underruns
5008 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005009 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005010 mEffectChains[0]->clearInputBuffer();
5011 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005012 if (track->isStopping_1()) {
5013 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005014 if (last && mHwPaused) {
5015 doHwResume = true;
5016 mHwPaused = false;
5017 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005018 }
5019 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5020 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005021 // We have consumed all the buffers of this track.
5022 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005023 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005024 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005025 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5026 } else {
5027 audioHALFrames = 0;
5028 }
5029
Andy Hung818e7a32016-02-16 18:08:07 -08005030 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005031 if (mStandby || !last ||
5032 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005033 if (track->isStopping_2()) {
5034 track->mState = TrackBase::STOPPED;
5035 }
Eric Laurent81784c32012-11-19 14:55:58 -08005036 if (track->isStopped()) {
5037 track->reset();
5038 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005039 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005040 }
5041 } else {
5042 // No buffers for this track. Give it a few chances to
5043 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005044 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005045 if (--(track->mRetryCount) <= 0) {
5046 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005047 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005048 // indicate to client process that the track was disabled because of underrun;
5049 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005050 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005051 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005052 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5053 "minFrames = %u, mFormat = %#x",
5054 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005055 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005056 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005057 doHwPause = true;
5058 mHwPaused = true;
5059 }
Eric Laurent81784c32012-11-19 14:55:58 -08005060 }
5061 }
5062 }
5063 }
5064
Eric Laurentd1f69b02014-12-15 14:33:13 -08005065 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005066 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005067 for (size_t i = 0; i < mTracks.size(); i++) {
5068 if (mTracks[i]->isFlushPending()) {
5069 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005070 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005071 }
5072 }
5073 }
5074
5075 // make sure the pause/flush/resume sequence is executed in the right order.
5076 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5077 // before flush and then resume HW. This can happen in case of pause/flush/resume
5078 // if resume is received before pause is executed.
5079 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005080 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005081 status_t result = mOutput->stream->pause();
5082 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005083 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005084 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005085 flushHw_l();
5086 }
5087 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005088 status_t result = mOutput->stream->resume();
5089 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005090 }
Eric Laurent81784c32012-11-19 14:55:58 -08005091 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005092 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005093
5094 return mixerStatus;
5095}
5096
5097void AudioFlinger::DirectOutputThread::threadLoop_mix()
5098{
Eric Laurent81784c32012-11-19 14:55:58 -08005099 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005100 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005101 // output audio to hardware
5102 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005103 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005104 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005105 status_t status = mActiveTrack->getNextBuffer(&buffer);
5106 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005107 // no need to pad with 0 for compressed audio
5108 if (audio_has_proportional_frames(mFormat)) {
5109 memset(curBuf, 0, frameCount * mFrameSize);
5110 }
Eric Laurent81784c32012-11-19 14:55:58 -08005111 break;
5112 }
5113 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5114 frameCount -= buffer.frameCount;
5115 curBuf += buffer.frameCount * mFrameSize;
5116 mActiveTrack->releaseBuffer(&buffer);
5117 }
Andy Hung2098f272014-02-27 14:00:06 -08005118 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005119 mSleepTimeUs = 0;
5120 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005121 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005122}
5123
5124void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5125{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005126 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005127 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005128 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005129 return;
5130 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005131 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005132 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005133 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005134 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005135 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005136 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005137 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005138 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005139 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005140 }
5141}
5142
Eric Laurentd1f69b02014-12-15 14:33:13 -08005143void AudioFlinger::DirectOutputThread::threadLoop_exit()
5144{
5145 {
5146 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005147 for (size_t i = 0; i < mTracks.size(); i++) {
5148 if (mTracks[i]->isFlushPending()) {
5149 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005150 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005151 }
5152 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005153 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005154 flushHw_l();
5155 }
5156 }
5157 PlaybackThread::threadLoop_exit();
5158}
5159
5160// must be called with thread mutex locked
5161bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5162{
5163 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005164 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005165
vivek mehta9cd7ad12016-03-17 00:18:29 -07005166 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5167 return !mStandby;
5168 }
5169
Eric Laurentd1f69b02014-12-15 14:33:13 -08005170 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5171 // after a timeout and we will enter standby then.
5172 if (mTracks.size() > 0) {
5173 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005174 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5175 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005176 }
5177
Eric Laurent5cff4032015-05-26 13:49:58 -07005178 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005179}
5180
Eric Laurent81784c32012-11-19 14:55:58 -08005181// getTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005182int AudioFlinger::DirectOutputThread::getTrackName_l(audio_channel_mask_t channelMask __unused,
Eric Laurentad7dd962016-09-22 12:38:37 -07005183 audio_format_t format __unused, audio_session_t sessionId __unused, uid_t uid)
Eric Laurent81784c32012-11-19 14:55:58 -08005184{
Eric Laurentad7dd962016-09-22 12:38:37 -07005185 if (trackCountForUid_l(uid) > (PlaybackThread::kMaxTracksPerUid - 1)) {
5186 return -1;
5187 }
Eric Laurent81784c32012-11-19 14:55:58 -08005188 return 0;
5189}
5190
5191// deleteTrackName_l() must be called with ThreadBase::mLock held
Glenn Kasten0f11b512014-01-31 16:18:54 -08005192void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08005193{
5194}
5195
Eric Laurent10351942014-05-08 18:49:52 -07005196// checkForNewParameter_l() must be called with ThreadBase::mLock held
5197bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5198 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005199{
5200 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005201 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005202
Eric Laurent10351942014-05-08 18:49:52 -07005203 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005204
Eric Laurent10351942014-05-08 18:49:52 -07005205 AudioParameter param = AudioParameter(keyValuePair);
5206 int value;
5207 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5208 // forward device change to effects that have requested to be
5209 // aware of attached audio device.
5210 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005211 a2dpDeviceChanged =
5212 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005213 mOutDevice = value;
5214 for (size_t i = 0; i < mEffectChains.size(); i++) {
5215 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005216 }
5217 }
Eric Laurent81784c32012-11-19 14:55:58 -08005218 }
Eric Laurent10351942014-05-08 18:49:52 -07005219 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5220 // do not accept frame count changes if tracks are open as the track buffer
5221 // size depends on frame count and correct behavior would not be garantied
5222 // if frame count is changed after track creation
5223 if (!mTracks.isEmpty()) {
5224 status = INVALID_OPERATION;
5225 } else {
5226 reconfig = true;
5227 }
5228 }
5229 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005230 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005231 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005232 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005233 mStandby = true;
5234 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005235 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005236 }
5237 if (status == NO_ERROR && reconfig) {
5238 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005239 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005240 }
5241 }
5242
Eric Laurent42537be2016-01-08 17:16:42 -08005243 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005244}
5245
5246uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5247{
5248 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005249 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005250 time = PlaybackThread::activeSleepTimeUs();
5251 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005252 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005253 }
5254 return time;
5255}
5256
5257uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5258{
5259 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005260 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005261 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5262 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005263 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005264 }
5265 return time;
5266}
5267
5268uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5269{
5270 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005271 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005272 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5273 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005274 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005275 }
5276 return time;
5277}
5278
5279void AudioFlinger::DirectOutputThread::cacheParameters_l()
5280{
5281 PlaybackThread::cacheParameters_l();
5282
5283 // use shorter standby delay as on normal output to release
5284 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005285 // no delay on outputs with HW A/V sync
5286 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005287 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005288 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005289 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005290 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005291 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005292 }
Eric Laurent81784c32012-11-19 14:55:58 -08005293}
5294
Eric Laurente659ef42014-09-29 13:06:46 -07005295void AudioFlinger::DirectOutputThread::flushHw_l()
5296{
Phil Burk062e67a2015-02-11 13:40:50 -08005297 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005298 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005299 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005300}
5301
Andy Hung10cbff12017-02-21 17:30:14 -08005302int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5303 // If a VolumeShaper is active, we must wake up periodically to update volume.
5304 const int64_t NS_PER_MS = 1000000;
5305 return mVolumeShaperActive ?
5306 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5307}
5308
Eric Laurent81784c32012-11-19 14:55:58 -08005309// ----------------------------------------------------------------------------
5310
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005312 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005313 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005314 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005315 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005316 mDrainSequence(0),
5317 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005318{
5319}
5320
5321AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5322{
5323}
5324
5325void AudioFlinger::AsyncCallbackThread::onFirstRef()
5326{
5327 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5328}
5329
5330bool AudioFlinger::AsyncCallbackThread::threadLoop()
5331{
5332 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005333 uint32_t writeAckSequence;
5334 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005335 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005336
5337 {
5338 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005339 while (!((mWriteAckSequence & 1) ||
5340 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005341 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005342 exitPending())) {
5343 mWaitWorkCV.wait(mLock);
5344 }
5345
Eric Laurentbfb1b832013-01-07 09:53:42 -08005346 if (exitPending()) {
5347 break;
5348 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005349 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5350 mWriteAckSequence, mDrainSequence);
5351 writeAckSequence = mWriteAckSequence;
5352 mWriteAckSequence &= ~1;
5353 drainSequence = mDrainSequence;
5354 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005355 asyncError = mAsyncError;
5356 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005357 }
5358 {
Eric Laurent4de95592013-09-26 15:28:21 -07005359 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5360 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005361 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005362 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005363 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005364 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005365 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005366 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005367 if (asyncError) {
5368 playbackThread->onAsyncError();
5369 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005370 }
5371 }
5372 }
5373 return false;
5374}
5375
5376void AudioFlinger::AsyncCallbackThread::exit()
5377{
5378 ALOGV("AsyncCallbackThread::exit");
5379 Mutex::Autolock _l(mLock);
5380 requestExit();
5381 mWaitWorkCV.broadcast();
5382}
5383
Eric Laurent3b4529e2013-09-05 18:09:19 -07005384void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005385{
5386 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005387 // bit 0 is cleared
5388 mWriteAckSequence = sequence << 1;
5389}
5390
5391void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5392{
5393 Mutex::Autolock _l(mLock);
5394 // ignore unexpected callbacks
5395 if (mWriteAckSequence & 2) {
5396 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 mWaitWorkCV.signal();
5398 }
5399}
5400
Eric Laurent3b4529e2013-09-05 18:09:19 -07005401void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005402{
5403 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005404 // bit 0 is cleared
5405 mDrainSequence = sequence << 1;
5406}
5407
5408void AudioFlinger::AsyncCallbackThread::resetDraining()
5409{
5410 Mutex::Autolock _l(mLock);
5411 // ignore unexpected callbacks
5412 if (mDrainSequence & 2) {
5413 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005414 mWaitWorkCV.signal();
5415 }
5416}
5417
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005418void AudioFlinger::AsyncCallbackThread::setAsyncError()
5419{
5420 Mutex::Autolock _l(mLock);
5421 mAsyncError = true;
5422 mWaitWorkCV.signal();
5423}
5424
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425
5426// ----------------------------------------------------------------------------
5427AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005428 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5429 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005430 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5431 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432{
Eric Laurentfd477972013-10-25 18:10:40 -07005433 //FIXME: mStandby should be set to true by ThreadBase constructor
5434 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005435 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436}
5437
Eric Laurentbfb1b832013-01-07 09:53:42 -08005438void AudioFlinger::OffloadThread::threadLoop_exit()
5439{
5440 if (mFlushPending || mHwPaused) {
5441 // If a flush is pending or track was paused, just discard buffered data
5442 flushHw_l();
5443 } else {
5444 mMixerStatus = MIXER_DRAIN_ALL;
5445 threadLoop_drain();
5446 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005447 if (mUseAsyncWrite) {
5448 ALOG_ASSERT(mCallbackThread != 0);
5449 mCallbackThread->exit();
5450 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005451 PlaybackThread::threadLoop_exit();
5452}
5453
5454AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5455 Vector< sp<Track> > *tracksToRemove
5456)
5457{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 size_t count = mActiveTracks.size();
5459
5460 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005461 bool doHwPause = false;
5462 bool doHwResume = false;
5463
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005464 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005465
Eric Laurentbfb1b832013-01-07 09:53:42 -08005466 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005467 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005468 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005469#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005470 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005471#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005472 // Only consider last track started for volume and mixer state control.
5473 // In theory an older track could underrun and restart after the new one starts
5474 // but as we only care about the transition phase between two tracks on a
5475 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005476 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005477 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005478
Haynes Mathew George7844f672014-01-15 12:32:55 -08005479 if (track->isInvalid()) {
5480 ALOGW("An invalidated track shouldn't be in active list");
5481 tracksToRemove->add(track);
5482 continue;
5483 }
5484
5485 if (track->mState == TrackBase::IDLE) {
5486 ALOGW("An idle track shouldn't be in active list");
5487 continue;
5488 }
5489
Eric Laurentbfb1b832013-01-07 09:53:42 -08005490 if (track->isPausing()) {
5491 track->setPaused();
5492 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005493 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005494 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005495 mHwPaused = true;
5496 }
5497 // If we were part way through writing the mixbuffer to
5498 // the HAL we must save this until we resume
5499 // BUG - this will be wrong if a different track is made active,
5500 // in that case we want to discard the pending data in the
5501 // mixbuffer and tell the client to present it again when the
5502 // track is resumed
5503 mPausedWriteLength = mCurrentWriteLength;
5504 mPausedBytesRemaining = mBytesRemaining;
5505 mBytesRemaining = 0; // stop writing
5506 }
5507 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005508 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005509 if (track->isStopping_1()) {
5510 track->mRetryCount = kMaxTrackStopRetriesOffload;
5511 } else {
5512 track->mRetryCount = kMaxTrackRetriesOffload;
5513 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005514 track->flushAck();
5515 if (last) {
5516 mFlushPending = true;
5517 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005518 } else if (track->isResumePending()){
5519 track->resumeAck();
5520 if (last) {
5521 if (mPausedBytesRemaining) {
5522 // Need to continue write that was interrupted
5523 mCurrentWriteLength = mPausedWriteLength;
5524 mBytesRemaining = mPausedBytesRemaining;
5525 mPausedBytesRemaining = 0;
5526 }
5527 if (mHwPaused) {
5528 doHwResume = true;
5529 mHwPaused = false;
5530 // threadLoop_mix() will handle the case that we need to
5531 // resume an interrupted write
5532 }
5533 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005534 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005535
Eric Laurent3df841a2016-07-15 15:15:40 -07005536 mLeftVolFloat = mRightVolFloat = -1.0;
5537
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005538 // Do not handle new data in this iteration even if track->framesReady()
5539 mixerStatus = MIXER_TRACKS_ENABLED;
5540 }
5541 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005542 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005543 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005544 if (track->mFillingUpStatus == Track::FS_FILLED) {
5545 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005546 if (last) {
5547 // make sure processVolume_l() will apply new volume even if 0
5548 mLeftVolFloat = mRightVolFloat = -1.0;
5549 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005550 }
5551
5552 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005553 sp<Track> previousTrack = mPreviousTrack.promote();
5554 if (previousTrack != 0) {
5555 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005556 // Flush any data still being written from last track
5557 mBytesRemaining = 0;
5558 if (mPausedBytesRemaining) {
5559 // Last track was paused so we also need to flush saved
5560 // mixbuffer state and invalidate track so that it will
5561 // re-submit that unwritten data when it is next resumed
5562 mPausedBytesRemaining = 0;
5563 // Invalidate is a bit drastic - would be more efficient
5564 // to have a flag to tell client that some of the
5565 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005566 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005567 }
5568 // flush data already sent to the DSP if changing audio session as audio
5569 // comes from a different source. Also invalidate previous track to force a
5570 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005571 if (previousTrack->sessionId() != track->sessionId()) {
5572 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005573 }
5574 }
5575 }
5576 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005577 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005578 if (track->isStopping_1()) {
5579 track->mRetryCount = kMaxTrackStopRetriesOffload;
5580 } else {
5581 track->mRetryCount = kMaxTrackRetriesOffload;
5582 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005583 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005584 mixerStatus = MIXER_TRACKS_READY;
5585 }
5586 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005587 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005588 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005589 if (--(track->mRetryCount) <= 0) {
5590 // Hardware buffer can hold a large amount of audio so we must
5591 // wait for all current track's data to drain before we say
5592 // that the track is stopped.
5593 if (mBytesRemaining == 0) {
5594 // Only start draining when all data in mixbuffer
5595 // has been written
5596 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5597 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5598 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5599 if (last && !mStandby) {
5600 // do not modify drain sequence if we are already draining. This happens
5601 // when resuming from pause after drain.
5602 if ((mDrainSequence & 1) == 0) {
5603 mSleepTimeUs = 0;
5604 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5605 mixerStatus = MIXER_DRAIN_TRACK;
5606 mDrainSequence += 2;
5607 }
5608 if (mHwPaused) {
5609 // It is possible to move from PAUSED to STOPPING_1 without
5610 // a resume so we must ensure hardware is running
5611 doHwResume = true;
5612 mHwPaused = false;
5613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005614 }
5615 }
Eric Laurente93cc032016-05-05 10:15:10 -07005616 } else if (last) {
5617 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5618 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 }
5620 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005621 // Drain has completed or we are in standby, signal presentation complete
5622 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005623 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005624 uint32_t latency = 0;
5625 status_t result = mOutput->stream->getLatency(&latency);
5626 ALOGE_IF(result != OK,
5627 "Error when retrieving output stream latency: %d", result);
5628 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005629 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005630 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005631 track->presentationComplete(framesWritten, audioHALFrames);
5632 track->reset();
5633 tracksToRemove->add(track);
5634 }
5635 } else {
5636 // No buffers for this track. Give it a few chances to
5637 // fill a buffer, then remove it from active list.
5638 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005639 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005640 uint64_t position = 0;
5641 struct timespec unused;
5642 // The running check restarts the retry counter at least once.
5643 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5644 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5645 running = true;
5646 mOffloadUnderrunPosition = position;
5647 }
5648 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005649 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5650 (long long)position, (long long)mOffloadUnderrunPosition);
5651 }
5652 if (running) { // still running, give us more time.
5653 track->mRetryCount = kMaxTrackRetriesOffload;
5654 } else {
5655 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5656 track->name());
5657 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005658 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005659 // it will then automatically call start() when data is available
5660 track->disable();
5661 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005662 } else if (last){
5663 mixerStatus = MIXER_TRACKS_ENABLED;
5664 }
5665 }
5666 }
5667 // compute volume for this track
5668 processVolume_l(track, last);
5669 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005670
Eric Laurentea0fade2013-10-04 16:23:48 -07005671 // make sure the pause/flush/resume sequence is executed in the right order.
5672 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5673 // before flush and then resume HW. This can happen in case of pause/flush/resume
5674 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005675 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005676 status_t result = mOutput->stream->pause();
5677 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005678 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005679 if (mFlushPending) {
5680 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005681 }
Eric Laurentfd477972013-10-25 18:10:40 -07005682 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005683 status_t result = mOutput->stream->resume();
5684 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005685 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005686
Eric Laurentbfb1b832013-01-07 09:53:42 -08005687 // remove all the tracks that need to be...
5688 removeTracks_l(*tracksToRemove);
5689
5690 return mixerStatus;
5691}
5692
Eric Laurentbfb1b832013-01-07 09:53:42 -08005693// must be called with thread mutex locked
5694bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5695{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005696 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5697 mWriteAckSequence, mDrainSequence);
5698 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005699 return true;
5700 }
5701 return false;
5702}
5703
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5705{
5706 Mutex::Autolock _l(mLock);
5707 return waitingAsyncCallback_l();
5708}
5709
5710void AudioFlinger::OffloadThread::flushHw_l()
5711{
Eric Laurente659ef42014-09-29 13:06:46 -07005712 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005713 // Flush anything still waiting in the mixbuffer
5714 mCurrentWriteLength = 0;
5715 mBytesRemaining = 0;
5716 mPausedWriteLength = 0;
5717 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005718 // reset bytes written count to reflect that DSP buffers are empty after flush.
5719 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005720 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005721
Eric Laurentbfb1b832013-01-07 09:53:42 -08005722 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005723 // discard any pending drain or write ack by incrementing sequence
5724 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5725 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005726 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005727 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5728 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005729 }
5730}
5731
Haynes Mathew George05317d22016-05-03 16:34:26 -07005732void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5733{
5734 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005735 if (PlaybackThread::invalidateTracks_l(streamType)) {
5736 mFlushPending = true;
5737 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005738}
5739
Eric Laurentbfb1b832013-01-07 09:53:42 -08005740// ----------------------------------------------------------------------------
5741
Eric Laurent81784c32012-11-19 14:55:58 -08005742AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005743 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005744 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005745 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005746 mWaitTimeMs(UINT_MAX)
5747{
5748 addOutputTrack(mainThread);
5749}
5750
5751AudioFlinger::DuplicatingThread::~DuplicatingThread()
5752{
5753 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5754 mOutputTracks[i]->destroy();
5755 }
5756}
5757
5758void AudioFlinger::DuplicatingThread::threadLoop_mix()
5759{
5760 // mix buffers...
5761 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005762 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005763 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005764 if (mMixerBufferValid) {
5765 memset(mMixerBuffer, 0, mMixerBufferSize);
5766 } else {
5767 memset(mSinkBuffer, 0, mSinkBufferSize);
5768 }
Eric Laurent81784c32012-11-19 14:55:58 -08005769 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005770 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005771 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005772 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005773 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005774}
5775
5776void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
5777{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005778 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005779 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005780 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005781 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005782 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005783 }
5784 } else if (mBytesWritten != 0) {
5785 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
5786 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005787 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005788 } else {
5789 // flush remaining overflow buffers in output tracks
5790 writeFrames = 0;
5791 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005792 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005793 }
5794}
5795
Eric Laurentbfb1b832013-01-07 09:53:42 -08005796ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005797{
5798 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08005799 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005800 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07005801 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08005802 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005803}
5804
5805void AudioFlinger::DuplicatingThread::threadLoop_standby()
5806{
5807 // DuplicatingThread implements standby by stopping all tracks
5808 for (size_t i = 0; i < outputTracks.size(); i++) {
5809 outputTracks[i]->stop();
5810 }
5811}
5812
5813void AudioFlinger::DuplicatingThread::saveOutputTracks()
5814{
5815 outputTracks = mOutputTracks;
5816}
5817
5818void AudioFlinger::DuplicatingThread::clearOutputTracks()
5819{
5820 outputTracks.clear();
5821}
5822
5823void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
5824{
5825 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08005826 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
5827 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
5828 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
5829 const size_t frameCount =
5830 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
5831 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
5832 // from different OutputTracks and their associated MixerThreads (e.g. one may
5833 // nearly empty and the other may be dropping data).
5834
5835 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08005836 this,
5837 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08005838 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08005839 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08005840 frameCount,
5841 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005842 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
5843 if (status != NO_ERROR) {
5844 ALOGE("addOutputTrack() initCheck failed %d", status);
5845 return;
Eric Laurent81784c32012-11-19 14:55:58 -08005846 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07005847 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
5848 mOutputTracks.add(outputTrack);
5849 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
5850 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005851}
5852
5853void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
5854{
5855 Mutex::Autolock _l(mLock);
5856 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5857 if (mOutputTracks[i]->thread() == thread) {
5858 mOutputTracks[i]->destroy();
5859 mOutputTracks.removeAt(i);
5860 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07005861 if (thread->getOutput() == mOutput) {
5862 mOutput = NULL;
5863 }
Eric Laurent81784c32012-11-19 14:55:58 -08005864 return;
5865 }
5866 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07005867 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08005868}
5869
5870// caller must hold mLock
5871void AudioFlinger::DuplicatingThread::updateWaitTime_l()
5872{
5873 mWaitTimeMs = UINT_MAX;
5874 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5875 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
5876 if (strong != 0) {
5877 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
5878 if (waitTimeMs < mWaitTimeMs) {
5879 mWaitTimeMs = waitTimeMs;
5880 }
5881 }
5882 }
5883}
5884
5885
5886bool AudioFlinger::DuplicatingThread::outputsReady(
5887 const SortedVector< sp<OutputTrack> > &outputTracks)
5888{
5889 for (size_t i = 0; i < outputTracks.size(); i++) {
5890 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
5891 if (thread == 0) {
5892 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
5893 outputTracks[i].get());
5894 return false;
5895 }
5896 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5897 // see note at standby() declaration
5898 if (playbackThread->standby() && !playbackThread->isSuspended()) {
5899 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
5900 thread.get());
5901 return false;
5902 }
5903 }
5904 return true;
5905}
5906
5907uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
5908{
5909 return (mWaitTimeMs * 1000) / 2;
5910}
5911
5912void AudioFlinger::DuplicatingThread::cacheParameters_l()
5913{
5914 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
5915 updateWaitTime_l();
5916
5917 MixerThread::cacheParameters_l();
5918}
5919
Eric Laurent6acd1d42017-01-04 14:23:29 -08005920
Eric Laurent81784c32012-11-19 14:55:58 -08005921// ----------------------------------------------------------------------------
5922// Record
5923// ----------------------------------------------------------------------------
5924
5925AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
5926 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08005927 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08005928 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07005929 audio_devices_t inDevice,
5930 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08005931#ifdef TEE_SINK
5932 , const sp<NBAIO_Sink>& teeSink
5933#endif
5934 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07005935 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07005936 mInput(input),
5937 mActiveTracks(&this->mLocalLog),
5938 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07005939 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08005940 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08005941#ifdef TEE_SINK
5942 , mTeeSink(teeSink)
5943#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07005944 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
5945 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005946 // mFastCapture below
5947 , mFastCaptureFutex(0)
5948 // mInputSource
5949 // mPipeSink
5950 // mPipeSource
5951 , mPipeFramesP2(0)
5952 // mPipeMemory
5953 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07005954 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07005955 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005956{
Glenn Kastend7dca052015-03-05 16:05:54 -08005957 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
5958 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08005959
Glenn Kastendeca2ae2014-02-07 10:25:56 -08005960 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005961
5962 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005963 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005964 size_t numCounterOffers = 0;
5965 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005966#if !LOG_NDEBUG
5967 ssize_t index =
5968#else
5969 (void)
5970#endif
5971 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005972 ALOG_ASSERT(index == 0);
5973
5974 // initialize fast capture depending on configuration
5975 bool initFastCapture;
5976 switch (kUseFastCapture) {
5977 case FastCapture_Never:
5978 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005979 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005980 break;
5981 case FastCapture_Always:
5982 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005983 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005984 break;
5985 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07005986 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07005987 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
5988 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
5989 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005990 break;
5991 // case FastCapture_Dynamic:
5992 }
5993
5994 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07005995 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005996 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07005997 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
5998 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07005999 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006000 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006001 const sp<MemoryDealer> roHeap(readOnlyHeap());
6002 sp<IMemory> pipeMemory;
6003 if ((roHeap == 0) ||
6004 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006005 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6006 ALOGE("not enough memory for pipe buffer size=%zu; "
6007 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6008 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6009 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006010 goto failed;
6011 }
6012 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6013 memset(pipeBuffer, 0, pipeSize);
6014 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6015 const NBAIO_Format offers[1] = {format};
6016 size_t numCounterOffers = 0;
6017 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6018 ALOG_ASSERT(index == 0);
6019 mPipeSink = pipe;
6020 PipeReader *pipeReader = new PipeReader(*pipe);
6021 numCounterOffers = 0;
6022 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6023 ALOG_ASSERT(index == 0);
6024 mPipeSource = pipeReader;
6025 mPipeFramesP2 = pipeFramesP2;
6026 mPipeMemory = pipeMemory;
6027
6028 // create fast capture
6029 mFastCapture = new FastCapture();
6030 FastCaptureStateQueue *sq = mFastCapture->sq();
6031#ifdef STATE_QUEUE_DUMP
6032 // FIXME
6033#endif
6034 FastCaptureState *state = sq->begin();
6035 state->mCblk = NULL;
6036 state->mInputSource = mInputSource.get();
6037 state->mInputSourceGen++;
6038 state->mPipeSink = pipe;
6039 state->mPipeSinkGen++;
6040 state->mFrameCount = mFrameCount;
6041 state->mCommand = FastCaptureState::COLD_IDLE;
6042 // already done in constructor initialization list
6043 //mFastCaptureFutex = 0;
6044 state->mColdFutexAddr = &mFastCaptureFutex;
6045 state->mColdGen++;
6046 state->mDumpState = &mFastCaptureDumpState;
6047#ifdef TEE_SINK
6048 // FIXME
6049#endif
6050 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6051 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6052 sq->end();
6053 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6054
6055 // start the fast capture
6056 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6057 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006058 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006059 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006060#ifdef AUDIO_WATCHDOG
6061 // FIXME
6062#endif
6063
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006064 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006065 }
6066failed: ;
6067
6068 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006069}
6070
Eric Laurent81784c32012-11-19 14:55:58 -08006071AudioFlinger::RecordThread::~RecordThread()
6072{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006073 if (mFastCapture != 0) {
6074 FastCaptureStateQueue *sq = mFastCapture->sq();
6075 FastCaptureState *state = sq->begin();
6076 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6077 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6078 if (old == -1) {
6079 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6080 }
6081 }
6082 state->mCommand = FastCaptureState::EXIT;
6083 sq->end();
6084 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6085 mFastCapture->join();
6086 mFastCapture.clear();
6087 }
6088 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006089 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006090 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006091}
6092
6093void AudioFlinger::RecordThread::onFirstRef()
6094{
Glenn Kastend7dca052015-03-05 16:05:54 -08006095 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006096}
6097
Eric Laurent555530a2017-02-07 18:17:24 -08006098void AudioFlinger::RecordThread::preExit()
6099{
6100 ALOGV(" preExit()");
6101 Mutex::Autolock _l(mLock);
6102 for (size_t i = 0; i < mTracks.size(); i++) {
6103 sp<RecordTrack> track = mTracks[i];
6104 track->invalidate();
6105 }
6106 mActiveTracks.clear();
6107 mStartStopCond.broadcast();
6108}
6109
Eric Laurent81784c32012-11-19 14:55:58 -08006110bool AudioFlinger::RecordThread::threadLoop()
6111{
Eric Laurent81784c32012-11-19 14:55:58 -08006112 nsecs_t lastWarning = 0;
6113
6114 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006115
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006116reacquire_wakelock:
6117 sp<RecordTrack> activeTrack;
6118 {
6119 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006120 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006121 }
6122
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006123 // used to request a deferred sleep, to be executed later while mutex is unlocked
6124 uint32_t sleepUs = 0;
6125
6126 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006127 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006128 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006129
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006130 // activeTracks accumulates a copy of a subset of mActiveTracks
6131 Vector< sp<RecordTrack> > activeTracks;
6132
Glenn Kasten735f45f2014-08-18 15:51:59 -07006133 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006134 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006135
Glenn Kasten735f45f2014-08-18 15:51:59 -07006136 // reference to a fast track which is about to be removed
6137 sp<RecordTrack> fastTrackToRemove;
6138
Eric Laurent81784c32012-11-19 14:55:58 -08006139 { // scope for mLock
6140 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006141
Eric Laurent021cf962014-05-13 10:18:14 -07006142 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006143
Eric Laurent000a4192014-01-29 15:17:32 -08006144 // check exitPending here because checkForNewParameters_l() and
6145 // checkForNewParameters_l() can temporarily release mLock
6146 if (exitPending()) {
6147 break;
6148 }
6149
Eric Laurent5c25d562016-07-13 17:17:45 -07006150 // sleep with mutex unlocked
6151 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006152 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006153 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6154 ATRACE_END();
6155 sleepUs = 0;
6156 continue;
6157 }
6158
Glenn Kasten2b806402013-11-20 16:37:38 -08006159 // if no active track(s), then standby and release wakelock
6160 size_t size = mActiveTracks.size();
6161 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006162 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006163 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006164 releaseWakeLock_l();
6165 ALOGV("RecordThread: loop stopping");
6166 // go to sleep
6167 mWaitWorkCV.wait(mLock);
6168 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006169 goto reacquire_wakelock;
6170 }
6171
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006172 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006173 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006174 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006175
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006176 activeTrack = mActiveTracks[i];
6177 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006178 if (activeTrack->isFastTrack()) {
6179 ALOG_ASSERT(fastTrackToRemove == 0);
6180 fastTrackToRemove = activeTrack;
6181 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006182 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006183 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006184 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006185 continue;
6186 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006187
6188 TrackBase::track_state activeTrackState = activeTrack->mState;
6189 switch (activeTrackState) {
6190
6191 case TrackBase::PAUSING:
6192 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006193 doBroadcast = true;
6194 size--;
6195 continue;
6196
6197 case TrackBase::STARTING_1:
6198 sleepUs = 10000;
6199 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006200 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006201 continue;
6202
6203 case TrackBase::STARTING_2:
6204 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006205 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006206 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006207 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006208 break;
6209
6210 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006211 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006212 break;
6213
6214 case TrackBase::IDLE:
6215 i++;
6216 continue;
6217
6218 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006219 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006220 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006221
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006222 activeTracks.add(activeTrack);
6223 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006225 if (activeTrack->isFastTrack()) {
6226 ALOG_ASSERT(!mFastTrackAvail);
6227 ALOG_ASSERT(fastTrack == 0);
6228 fastTrack = activeTrack;
6229 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006230 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006231
Andy Hungdae27702016-10-31 14:01:16 -07006232 mActiveTracks.updatePowerState(this);
6233
Eric Laurent5c25d562016-07-13 17:17:45 -07006234 if (allStopped) {
6235 standbyIfNotAlreadyInStandby();
6236 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006237 if (doBroadcast) {
6238 mStartStopCond.broadcast();
6239 }
6240
6241 // sleep if there are no active tracks to process
6242 if (activeTracks.size() == 0) {
6243 if (sleepUs == 0) {
6244 sleepUs = kRecordThreadSleepUs;
6245 }
6246 continue;
6247 }
6248 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006249
Eric Laurent81784c32012-11-19 14:55:58 -08006250 lockEffectChains_l(effectChains);
6251 }
6252
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006253 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006254
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006255 size_t size = effectChains.size();
6256 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006257 // thread mutex is not locked, but effect chain is locked
6258 effectChains[i]->process_l();
6259 }
6260
Glenn Kasten735f45f2014-08-18 15:51:59 -07006261 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006262 if (mFastCapture != 0) {
6263 FastCaptureStateQueue *sq = mFastCapture->sq();
6264 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006265 bool didModify = false;
6266 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006267 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6268 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6269 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6270 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6271 if (old == -1) {
6272 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6273 }
6274 }
6275 state->mCommand = FastCaptureState::READ_WRITE;
6276#if 0 // FIXME
6277 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006278 FastThreadDumpState::kSamplingNforLowRamDevice :
6279 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006280#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006281 didModify = true;
6282 }
6283 audio_track_cblk_t *cblkOld = state->mCblk;
6284 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6285 if (cblkNew != cblkOld) {
6286 state->mCblk = cblkNew;
6287 // block until acked if removing a fast track
6288 if (cblkOld != NULL) {
6289 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6290 }
6291 didModify = true;
6292 }
6293 sq->end(didModify);
6294 if (didModify) {
6295 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006296#if 0
6297 if (kUseFastCapture == FastCapture_Dynamic) {
6298 mNormalSource = mPipeSource;
6299 }
6300#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006301 }
6302 }
6303
Glenn Kasten735f45f2014-08-18 15:51:59 -07006304 // now run the fast track destructor with thread mutex unlocked
6305 fastTrackToRemove.clear();
6306
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006307 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6308 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6309 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6310 // If destination is non-contiguous, first read past the nominal end of buffer, then
6311 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006312
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006313 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006314 ssize_t framesRead;
6315
6316 // If an NBAIO source is present, use it to read the normal capture's data
6317 if (mPipeSource != 0) {
6318 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006319 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006320 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006321 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006322 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6323 // buffer size or at least for 20ms.
6324 size_t sleepFrames = max(
6325 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6326 if (framesRead <= (ssize_t) sleepFrames) {
6327 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6328 }
6329 if (framesRead < 0) {
6330 status_t status = (status_t) framesRead;
6331 switch (status) {
6332 case OVERRUN:
6333 ALOGW("overrun on read from pipe");
6334 framesRead = 0;
6335 break;
6336 case NEGOTIATE:
6337 ALOGE("re-negotiation is needed");
6338 framesRead = -1; // Will cause an attempt to recover.
6339 break;
6340 default:
6341 ALOGE("unknown error %d on read from pipe", status);
6342 break;
6343 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006344 }
6345 // otherwise use the HAL / AudioStreamIn directly
6346 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006347 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006348 size_t bytesRead;
6349 status_t result = mInput->stream->read(
6350 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006351 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006352 if (result < 0) {
6353 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006354 } else {
6355 framesRead = bytesRead / mFrameSize;
6356 }
6357 }
6358
Andy Hung3f0c9022016-01-15 17:49:46 -08006359 // Update server timestamp with server stats
6360 // systemTime() is optional if the hardware supports timestamps.
6361 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6362 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6363
6364 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006365 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006366 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006367 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006368 if (ret == NO_ERROR) {
6369 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6370 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6371 // Note: In general record buffers should tend to be empty in
6372 // a properly running pipeline.
6373 //
6374 // Also, it is not advantageous to call get_presentation_position during the read
6375 // as the read obtains a lock, preventing the timestamp call from executing.
6376 }
6377 }
6378 // Use this to track timestamp information
6379 // ALOGD("%s", mTimestamp.toString().c_str());
6380
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006381 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006382 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006383 // Force input into standby so that it tries to recover at next read attempt
6384 inputStandBy();
6385 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006386 }
6387 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006388 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006389 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006390 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006391
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006392 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006393 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006394 }
6395 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006396 {
6397 size_t part1 = mRsmpInFramesP2 - rear;
6398 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006399 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006400 (framesRead - part1) * mFrameSize);
6401 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006402 }
6403 rear = mRsmpInRear += framesRead;
6404
6405 size = activeTracks.size();
6406 // loop over each active track
6407 for (size_t i = 0; i < size; i++) {
6408 activeTrack = activeTracks[i];
6409
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006410 // skip fast tracks, as those are handled directly by FastCapture
6411 if (activeTrack->isFastTrack()) {
6412 continue;
6413 }
6414
Andy Hung73c02e42015-03-29 01:13:58 -07006415 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006416 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6417
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006418 enum {
6419 OVERRUN_UNKNOWN,
6420 OVERRUN_TRUE,
6421 OVERRUN_FALSE
6422 } overrun = OVERRUN_UNKNOWN;
6423
6424 // loop over getNextBuffer to handle circular sink
6425 for (;;) {
6426
6427 activeTrack->mSink.frameCount = ~0;
6428 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6429 size_t framesOut = activeTrack->mSink.frameCount;
6430 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6431
Andy Hung73c02e42015-03-29 01:13:58 -07006432 // check available frames and handle overrun conditions
6433 // if the record track isn't draining fast enough.
6434 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006435 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006436 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6437 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006438 overrun = OVERRUN_TRUE;
6439 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006440 if (framesOut == 0 || framesIn == 0) {
6441 break;
6442 }
6443
Andy Hung6770c6f2015-04-07 13:43:36 -07006444 // Don't allow framesOut to be larger than what is possible with resampling
6445 // from framesIn.
6446 // This isn't strictly necessary but helps limit buffer resizing in
6447 // RecordBufferConverter. TODO: remove when no longer needed.
6448 framesOut = min(framesOut,
6449 destinationFramesPossible(
6450 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006451 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6452 framesOut = activeTrack->mRecordBufferConverter->convert(
6453 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006454
6455 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6456 overrun = OVERRUN_FALSE;
6457 }
6458
6459 if (activeTrack->mFramesToDrop == 0) {
6460 if (framesOut > 0) {
6461 activeTrack->mSink.frameCount = framesOut;
6462 activeTrack->releaseBuffer(&activeTrack->mSink);
6463 }
6464 } else {
6465 // FIXME could do a partial drop of framesOut
6466 if (activeTrack->mFramesToDrop > 0) {
6467 activeTrack->mFramesToDrop -= framesOut;
6468 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006469 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006470 }
6471 } else {
6472 activeTrack->mFramesToDrop += framesOut;
6473 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6474 activeTrack->mSyncStartEvent->isCancelled()) {
6475 ALOGW("Synced record %s, session %d, trigger session %d",
6476 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6477 activeTrack->sessionId(),
6478 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006479 activeTrack->mSyncStartEvent->triggerSession() :
6480 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006481 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006482 }
6483 }
6484 }
6485
6486 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006487 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006488 }
6489 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006490
6491 switch (overrun) {
6492 case OVERRUN_TRUE:
6493 // client isn't retrieving buffers fast enough
6494 if (!activeTrack->setOverflow()) {
6495 nsecs_t now = systemTime();
6496 // FIXME should lastWarning per track?
6497 if ((now - lastWarning) > kWarningThrottleNs) {
6498 ALOGW("RecordThread: buffer overflow");
6499 lastWarning = now;
6500 }
6501 }
6502 break;
6503 case OVERRUN_FALSE:
6504 activeTrack->clearOverflow();
6505 break;
6506 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006507 break;
6508 }
6509
Andy Hung3f0c9022016-01-15 17:49:46 -08006510 // update frame information and push timestamp out
6511 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006512 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006513 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6514 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006515 }
6516
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006517unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006518 // enable changes in effect chain
6519 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006520 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006521 }
6522
Glenn Kasten93e471f2013-08-19 08:40:07 -07006523 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006524
6525 {
6526 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006527 for (size_t i = 0; i < mTracks.size(); i++) {
6528 sp<RecordTrack> track = mTracks[i];
6529 track->invalidate();
6530 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006531 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006532 mStartStopCond.broadcast();
6533 }
6534
6535 releaseWakeLock();
6536
6537 ALOGV("RecordThread %p exiting", this);
6538 return false;
6539}
6540
Glenn Kasten93e471f2013-08-19 08:40:07 -07006541void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006542{
6543 if (!mStandby) {
6544 inputStandBy();
6545 mStandby = true;
6546 }
6547}
6548
6549void AudioFlinger::RecordThread::inputStandBy()
6550{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006551 // Idle the fast capture if it's currently running
6552 if (mFastCapture != 0) {
6553 FastCaptureStateQueue *sq = mFastCapture->sq();
6554 FastCaptureState *state = sq->begin();
6555 if (!(state->mCommand & FastCaptureState::IDLE)) {
6556 state->mCommand = FastCaptureState::COLD_IDLE;
6557 state->mColdFutexAddr = &mFastCaptureFutex;
6558 state->mColdGen++;
6559 mFastCaptureFutex = 0;
6560 sq->end();
6561 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6562 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6563#if 0
6564 if (kUseFastCapture == FastCapture_Dynamic) {
6565 // FIXME
6566 }
6567#endif
6568#ifdef AUDIO_WATCHDOG
6569 // FIXME
6570#endif
6571 } else {
6572 sq->end(false /*didModify*/);
6573 }
6574 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006575 status_t result = mInput->stream->standby();
6576 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006577
6578 // If going into standby, flush the pipe source.
6579 if (mPipeSource.get() != nullptr) {
6580 const ssize_t flushed = mPipeSource->flush();
6581 if (flushed > 0) {
6582 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6583 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6584 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6585 }
6586 }
Eric Laurent81784c32012-11-19 14:55:58 -08006587}
6588
Glenn Kasten05997e22014-03-13 15:08:33 -07006589// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006590sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006591 const sp<AudioFlinger::Client>& client,
6592 uint32_t sampleRate,
6593 audio_format_t format,
6594 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006595 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006596 audio_session_t sessionId,
Glenn Kasten7df8c0b2014-07-03 12:23:29 -07006597 size_t *notificationFrames,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006598 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006599 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006600 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006601 status_t *status,
6602 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006603{
Glenn Kasten74935e42013-12-19 08:56:45 -08006604 size_t frameCount = *pFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006605 sp<RecordTrack> track;
6606 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006607 audio_input_flags_t inputFlags = mInput->flags;
6608
6609 // special case for FAST flag considered OK if fast capture is present
6610 if (hasFastCapture()) {
6611 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6612 }
6613
6614 // Check if requested flags are compatible with output stream flags
6615 if ((*flags & inputFlags) != *flags) {
6616 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6617 " input flags (%08x)",
6618 *flags, inputFlags);
6619 *flags = (audio_input_flags_t)(*flags & inputFlags);
6620 }
Eric Laurent81784c32012-11-19 14:55:58 -08006621
Glenn Kasten90e58b12013-07-31 16:16:02 -07006622 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006623 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006624 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006625 // we formerly checked for a callback handler (non-0 tid),
6626 // but that is no longer required for TRANSFER_OBTAIN mode
6627 //
Glenn Kasten74105912014-07-03 12:28:53 -07006628 // frame count is not specified, or is exactly the pipe depth
6629 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006630 // PCM data
6631 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006632 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006633 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006634 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006635 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006636 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006637 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006638 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006639 hasFastCapture() &&
6640 // there are sufficient fast track slots available
6641 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006642 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006643 // check compatibility with audio effects.
6644 Mutex::Autolock _l(mLock);
6645 // Do not accept FAST flag if the session has software effects
6646 sp<EffectChain> chain = getEffectChain_l(sessionId);
6647 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006648 audio_input_flags_t old = *flags;
6649 chain->checkInputFlagCompatibility(flags);
6650 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006651 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6652 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006653 }
6654 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006655 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006656 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6657 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006658 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006659 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6660 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006661 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006662 this, frameCount, mFrameCount, mPipeFramesP2,
6663 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006664 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006665 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006666 }
6667 }
6668
6669 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006670 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006671 // fast track: frame count is exactly the pipe depth
6672 frameCount = mPipeFramesP2;
6673 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
6674 *notificationFrames = mFrameCount;
6675 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006676 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6677 // or 20 ms if there is a fast capture
6678 // TODO This could be a roundupRatio inline, and const
6679 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6680 * sampleRate + mSampleRate - 1) / mSampleRate;
6681 // minimum number of notification periods is at least kMinNotifications,
6682 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6683 static const size_t kMinNotifications = 3;
6684 static const uint32_t kMinMs = 30;
6685 // TODO This could be a roundupRatio inline
6686 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6687 // TODO This could be a roundupRatio inline
6688 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6689 maxNotificationFrames;
6690 const size_t minFrameCount = maxNotificationFrames *
6691 max(kMinNotifications, minNotificationsByMs);
6692 frameCount = max(frameCount, minFrameCount);
6693 if (*notificationFrames == 0 || *notificationFrames > maxNotificationFrames) {
6694 *notificationFrames = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006695 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006696 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006697 *pFrameCount = frameCount;
Glenn Kasten90e58b12013-07-31 16:16:02 -07006698
Glenn Kasten15e57982013-09-24 11:52:37 -07006699 lStatus = initCheck();
6700 if (lStatus != NO_ERROR) {
6701 ALOGE("createRecordTrack_l() audio driver not initialized");
6702 goto Exit;
6703 }
Eric Laurent81784c32012-11-19 14:55:58 -08006704
6705 { // scope for mLock
6706 Mutex::Autolock _l(mLock);
6707
6708 track = new RecordTrack(this, client, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006709 format, channelMask, frameCount,
6710 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006711 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006712
Glenn Kasten03003332013-08-06 15:40:54 -07006713 lStatus = track->initCheck();
6714 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07006715 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08006716 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08006717 goto Exit;
6718 }
6719 mTracks.add(track);
6720
Eric Laurent05067782016-06-01 18:27:28 -07006721 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006722 pid_t callingPid = IPCThreadState::self()->getCallingPid();
6723 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
6724 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006725 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006726 }
Eric Laurent81784c32012-11-19 14:55:58 -08006727 }
Glenn Kasten05997e22014-03-13 15:08:33 -07006728
Eric Laurent81784c32012-11-19 14:55:58 -08006729 lStatus = NO_ERROR;
6730
6731Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07006732 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08006733 return track;
6734}
6735
6736status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
6737 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08006738 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08006739{
6740 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
6741 sp<ThreadBase> strongMe = this;
6742 status_t status = NO_ERROR;
6743
6744 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006745 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006746 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006747 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08006748 triggerSession,
6749 recordTrack->sessionId(),
6750 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006751 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08006752 // Sync event can be cancelled by the trigger session if the track is not in a
6753 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006754 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006755 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08006756 } else {
6757 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006758 recordTrack->mFramesToDrop = -
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006759 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08006760 }
6761 }
6762
6763 {
Glenn Kasten47c20702013-08-13 15:37:35 -07006764 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08006765 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006766 if (mActiveTracks.indexOf(recordTrack) >= 0) {
6767 if (recordTrack->mState == TrackBase::PAUSING) {
6768 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006769 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006770 } else {
6771 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08006772 }
6773 return status;
6774 }
6775
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006776 // TODO consider other ways of handling this, such as changing the state to :STARTING and
6777 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
6778 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006779 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08006780 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006781 status_t status = NO_ERROR;
6782 if (recordTrack->isExternalTrack()) {
6783 mLock.unlock();
Glenn Kastend848eb42016-03-08 13:42:11 -08006784 status = AudioSystem::startInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006785 mLock.lock();
6786 // FIXME should verify that recordTrack is still in mActiveTracks
6787 if (status != NO_ERROR) {
6788 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07006789 recordTrack->clearSyncStartEvent();
6790 ALOGV("RecordThread::start error %d", status);
6791 return status;
6792 }
Eric Laurent81784c32012-11-19 14:55:58 -08006793 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006794 // Catch up with current buffer indices if thread is already running.
6795 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
6796 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
6797 // see previously buffered data before it called start(), but with greater risk of overrun.
6798
Andy Hung73c02e42015-03-29 01:13:58 -07006799 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07006800 // clear any converter state as new data will be discontinuous
6801 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006802 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08006803 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08006804 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08006805 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006806 ALOGV("Record failed to start");
6807 status = BAD_VALUE;
6808 goto startError;
6809 }
Eric Laurent81784c32012-11-19 14:55:58 -08006810 return status;
6811 }
Glenn Kasten7c027242012-12-26 14:43:16 -08006812
Eric Laurent81784c32012-11-19 14:55:58 -08006813startError:
Eric Laurent83b88082014-06-20 18:31:16 -07006814 if (recordTrack->isExternalTrack()) {
Glenn Kastend848eb42016-03-08 13:42:11 -08006815 AudioSystem::stopInput(mId, recordTrack->sessionId());
Eric Laurent83b88082014-06-20 18:31:16 -07006816 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006817 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006818 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08006819 return status;
6820}
6821
Eric Laurent81784c32012-11-19 14:55:58 -08006822void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
6823{
6824 sp<SyncEvent> strongEvent = event.promote();
6825
6826 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08006827 sp<RefBase> ptr = strongEvent->cookie().promote();
6828 if (ptr != 0) {
6829 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
6830 recordTrack->handleSyncStartEvent(strongEvent);
6831 }
Eric Laurent81784c32012-11-19 14:55:58 -08006832 }
6833}
6834
Glenn Kastena8356f62013-07-25 14:37:52 -07006835bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08006836 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07006837 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006838 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08006839 return false;
6840 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006841 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08006842 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07006843 // signal thread to stop
6844 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08006845 // do not wait for mStartStopCond if exiting
6846 if (exitPending()) {
6847 return true;
6848 }
Glenn Kasten47c20702013-08-13 15:37:35 -07006849 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08006850 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08006851 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07006852 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006853 ALOGV("Record stopped OK");
6854 return true;
6855 }
6856 return false;
6857}
6858
Glenn Kasten0f11b512014-01-31 16:18:54 -08006859bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08006860{
6861 return false;
6862}
6863
Glenn Kasten0f11b512014-01-31 16:18:54 -08006864status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006865{
6866#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
6867 if (!isValidSyncEvent(event)) {
6868 return BAD_VALUE;
6869 }
6870
Glenn Kastend848eb42016-03-08 13:42:11 -08006871 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08006872 status_t ret = NAME_NOT_FOUND;
6873
6874 Mutex::Autolock _l(mLock);
6875
6876 for (size_t i = 0; i < mTracks.size(); i++) {
6877 sp<RecordTrack> track = mTracks[i];
6878 if (eventSession == track->sessionId()) {
6879 (void) track->setSyncEvent(event);
6880 ret = NO_ERROR;
6881 }
6882 }
6883 return ret;
6884#else
6885 return BAD_VALUE;
6886#endif
6887}
6888
6889// destroyTrack_l() must be called with ThreadBase::mLock held
6890void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
6891{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006892 track->terminate();
6893 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08006894 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08006895 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006896 removeTrack_l(track);
6897 }
6898}
6899
6900void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
6901{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006902 String8 result;
6903 track->appendDump(result, false /* active */);
6904 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
6905
Eric Laurent81784c32012-11-19 14:55:58 -08006906 mTracks.remove(track);
6907 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006908 if (track->isFastTrack()) {
6909 ALOG_ASSERT(!mFastTrackAvail);
6910 mFastTrackAvail = true;
6911 }
Eric Laurent81784c32012-11-19 14:55:58 -08006912}
6913
6914void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
6915{
6916 dumpInternals(fd, args);
6917 dumpTracks(fd, args);
6918 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006919 dprintf(fd, " Local log:\n");
6920 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08006921}
6922
6923void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
6924{
Glenn Kasten44182c22015-03-05 17:12:23 -08006925 dumpBase(fd, args);
6926
Mikhail Naganov913d06c2016-11-01 12:49:22 -07006927 AudioStreamIn *input = mInput;
6928 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
6929 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
6930 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08006931 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006932 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006933 }
Andy Hungbfa64962017-06-12 14:43:19 -07006934
6935 if (input != nullptr) {
6936 dprintf(fd, " Hal stream dump:\n");
6937 (void)input->stream->dump(fd);
6938 }
6939
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006940 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006941 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08006942
Glenn Kasten2f90c512015-12-02 11:40:09 -08006943 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
6944 // while we are dumping it. It may be inconsistent, but it won't mutate!
6945 // This is a large object so we place it on the heap.
6946 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
6947 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
6948 copy->dump(fd);
6949 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08006950}
6951
Glenn Kasten0f11b512014-01-31 16:18:54 -08006952void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08006953{
Eric Laurent81784c32012-11-19 14:55:58 -08006954 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08006955 size_t numtracks = mTracks.size();
6956 size_t numactive = mActiveTracks.size();
6957 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006958 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006959 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08006960 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006961 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006962 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08006963 RecordTrack::appendDumpHeader(result);
6964 for (size_t i = 0; i < numtracks ; ++i) {
6965 sp<RecordTrack> track = mTracks[i];
6966 if (track != 0) {
6967 bool active = mActiveTracks.indexOf(track) >= 0;
6968 if (active) {
6969 numactiveseen++;
6970 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006971 result.append(prefix);
6972 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08006973 }
Eric Laurent81784c32012-11-19 14:55:58 -08006974 }
Marco Nelissenb2208842014-02-07 14:00:50 -08006975 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07006976 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08006977 }
6978
Marco Nelissenb2208842014-02-07 14:00:50 -08006979 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006980 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08006981 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006982 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08006983 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08006984 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08006985 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08006986 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006987 result.append(prefix);
6988 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08006989 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006990 }
Eric Laurent81784c32012-11-19 14:55:58 -08006991
6992 }
6993 write(fd, result.string(), result.size());
6994}
6995
Andy Hung73c02e42015-03-29 01:13:58 -07006996
6997void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
6998{
6999 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7000 RecordThread *recordThread = (RecordThread *) threadBase.get();
7001 mRsmpInFront = recordThread->mRsmpInRear;
7002 mRsmpInUnrel = 0;
7003}
7004
7005void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7006 size_t *framesAvailable, bool *hasOverrun)
7007{
7008 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7009 RecordThread *recordThread = (RecordThread *) threadBase.get();
7010 const int32_t rear = recordThread->mRsmpInRear;
7011 const int32_t front = mRsmpInFront;
7012 const ssize_t filled = rear - front;
7013
7014 size_t framesIn;
7015 bool overrun = false;
7016 if (filled < 0) {
7017 // should not happen, but treat like a massive overrun and re-sync
7018 framesIn = 0;
7019 mRsmpInFront = rear;
7020 overrun = true;
7021 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7022 framesIn = (size_t) filled;
7023 } else {
7024 // client is not keeping up with server, but give it latest data
7025 framesIn = recordThread->mRsmpInFrames;
7026 mRsmpInFront = /* front = */ rear - framesIn;
7027 overrun = true;
7028 }
7029 if (framesAvailable != NULL) {
7030 *framesAvailable = framesIn;
7031 }
7032 if (hasOverrun != NULL) {
7033 *hasOverrun = overrun;
7034 }
7035}
7036
Eric Laurent81784c32012-11-19 14:55:58 -08007037// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007038status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007039 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007040{
Andy Hung73c02e42015-03-29 01:13:58 -07007041 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007042 if (threadBase == 0) {
7043 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007044 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007045 return NOT_ENOUGH_DATA;
7046 }
7047 RecordThread *recordThread = (RecordThread *) threadBase.get();
7048 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007049 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007050 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007051 // FIXME should not be P2 (don't want to increase latency)
7052 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007053 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007054 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007055 front &= recordThread->mRsmpInFramesP2 - 1;
7056 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007057 if (part1 > (size_t) filled) {
7058 part1 = filled;
7059 }
7060 size_t ask = buffer->frameCount;
7061 ALOG_ASSERT(ask > 0);
7062 if (part1 > ask) {
7063 part1 = ask;
7064 }
7065 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007066 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007067 buffer->raw = NULL;
7068 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007069 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007070 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
7072
Andy Hung57446612015-04-19 23:56:46 -07007073 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007074 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007075 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007076 return NO_ERROR;
7077}
7078
7079// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007080void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7081 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007082{
Glenn Kasten85948432013-08-19 12:09:05 -07007083 size_t stepCount = buffer->frameCount;
7084 if (stepCount == 0) {
7085 return;
7086 }
Andy Hung73c02e42015-03-29 01:13:58 -07007087 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7088 mRsmpInUnrel -= stepCount;
7089 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007090 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007091 buffer->frameCount = 0;
7092}
7093
Eric Laurentd8365c52017-07-16 15:27:05 -07007094void AudioFlinger::RecordThread::checkBtNrec()
7095{
7096 Mutex::Autolock _l(mLock);
7097 checkBtNrec_l();
7098}
7099
7100void AudioFlinger::RecordThread::checkBtNrec_l()
7101{
7102 // disable AEC and NS if the device is a BT SCO headset supporting those
7103 // pre processings
7104 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7105 mAudioFlinger->btNrecIsOff();
7106 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7107 for (size_t i = 0; i < mEffectChains.size(); i++) {
7108 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7109 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7110 }
7111 }
7112}
7113
Andy Hung97a893e2015-03-29 01:03:07 -07007114
Eric Laurent10351942014-05-08 18:49:52 -07007115bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7116 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007117{
7118 bool reconfig = false;
7119
Eric Laurent10351942014-05-08 18:49:52 -07007120 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007121
Eric Laurent10351942014-05-08 18:49:52 -07007122 audio_format_t reqFormat = mFormat;
7123 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007124 // 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 -07007125 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7126
7127 AudioParameter param = AudioParameter(keyValuePair);
7128 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007129
7130 // scope for AutoPark extends to end of method
7131 AutoPark<FastCapture> park(mFastCapture);
7132
Eric Laurent10351942014-05-08 18:49:52 -07007133 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7134 // channel count change can be requested. Do we mandate the first client defines the
7135 // HAL sampling rate and channel count or do we allow changes on the fly?
7136 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7137 samplingRate = value;
7138 reconfig = true;
7139 }
7140 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007141 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007142 status = BAD_VALUE;
7143 } else {
7144 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007145 reconfig = true;
7146 }
Eric Laurent10351942014-05-08 18:49:52 -07007147 }
7148 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7149 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007150 if (!audio_is_input_channel(mask) ||
7151 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007152 status = BAD_VALUE;
7153 } else {
7154 channelMask = mask;
7155 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007156 }
Eric Laurent10351942014-05-08 18:49:52 -07007157 }
7158 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7159 // do not accept frame count changes if tracks are open as the track buffer
7160 // size depends on frame count and correct behavior would not be guaranteed
7161 // if frame count is changed after track creation
7162 if (mActiveTracks.size() > 0) {
7163 status = INVALID_OPERATION;
7164 } else {
7165 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007166 }
Eric Laurent10351942014-05-08 18:49:52 -07007167 }
7168 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7169 // forward device change to effects that have requested to be
7170 // aware of attached audio device.
7171 for (size_t i = 0; i < mEffectChains.size(); i++) {
7172 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007173 }
Eric Laurent81784c32012-11-19 14:55:58 -08007174
Eric Laurent10351942014-05-08 18:49:52 -07007175 // store input device and output device but do not forward output device to audio HAL.
7176 // Note that status is ignored by the caller for output device
7177 // (see AudioFlinger::setParameters()
7178 if (audio_is_output_devices(value)) {
7179 mOutDevice = value;
7180 status = BAD_VALUE;
7181 } else {
7182 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007183 if (value != AUDIO_DEVICE_NONE) {
7184 mPrevInDevice = value;
7185 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007186 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007187 }
Eric Laurent10351942014-05-08 18:49:52 -07007188 }
7189 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7190 mAudioSource != (audio_source_t)value) {
7191 // forward device change to effects that have requested to be
7192 // aware of attached audio device.
7193 for (size_t i = 0; i < mEffectChains.size(); i++) {
7194 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007195 }
Eric Laurent10351942014-05-08 18:49:52 -07007196 mAudioSource = (audio_source_t)value;
7197 }
Glenn Kastene198c362013-08-13 09:13:36 -07007198
Eric Laurent10351942014-05-08 18:49:52 -07007199 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007200 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007201 if (status == INVALID_OPERATION) {
7202 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007203 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007204 }
7205 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007206 if (status == BAD_VALUE) {
7207 uint32_t sRate;
7208 audio_channel_mask_t channelMask;
7209 audio_format_t format;
7210 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7211 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7212 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7213 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7214 status = NO_ERROR;
7215 }
Eric Laurent81784c32012-11-19 14:55:58 -08007216 }
Eric Laurent10351942014-05-08 18:49:52 -07007217 if (status == NO_ERROR) {
7218 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007219 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007220 }
7221 }
Eric Laurent81784c32012-11-19 14:55:58 -08007222 }
Eric Laurent10351942014-05-08 18:49:52 -07007223
Eric Laurent81784c32012-11-19 14:55:58 -08007224 return reconfig;
7225}
7226
7227String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7228{
Eric Laurent81784c32012-11-19 14:55:58 -08007229 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007230 if (initCheck() == NO_ERROR) {
7231 String8 out_s8;
7232 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7233 return out_s8;
7234 }
Eric Laurent81784c32012-11-19 14:55:58 -08007235 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007236 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007237}
7238
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007239void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007240 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7241
7242 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007243
7244 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007245 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007246 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007247 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007248 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007249 desc->mChannelMask = mChannelMask;
7250 desc->mSamplingRate = mSampleRate;
7251 desc->mFormat = mFormat;
7252 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007253 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007254 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007255 break;
7256
Eric Laurent73e26b62015-04-27 16:55:58 -07007257 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007258 default:
7259 break;
7260 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007261 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007262}
7263
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007264void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007265{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007266 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7267 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007268 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007269 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007270 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007271 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7272 result = mInput->stream->getFrameSize(&mFrameSize);
7273 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7274 result = mInput->stream->getBufferSize(&mBufferSize);
7275 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007276 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007277 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7278 "mBufferSize=%lld, mFrameCount=%lld",
7279 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7280 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007281 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007282 // 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 -07007283 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007284 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007285 // A larger value should allow more old data to be read after a track calls start(),
7286 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007287 //
7288 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007289 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007290 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007291 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007292 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007293
7294 // TODO optimize audio capture buffer sizes ...
7295 // Here we calculate the size of the sliding buffer used as a source
7296 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7297 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7298 // be better to have it derived from the pipe depth in the long term.
7299 // The current value is higher than necessary. However it should not add to latency.
7300
Glenn Kasten85948432013-08-19 12:09:05 -07007301 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007302 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7303 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007304 // if posix_memalign fails, will segv here.
7305 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007306
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007307 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7308 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007309}
7310
Glenn Kasten5f972c02014-01-13 09:59:31 -08007311uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007312{
7313 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007314 uint32_t result;
7315 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7316 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007317 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007318 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007319}
7320
Eric Laurent4c415062016-06-17 16:14:16 -07007321// hasAudioSession_l() must be called with ThreadBase::mLock held
7322uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007323{
Eric Laurent81784c32012-11-19 14:55:58 -08007324 uint32_t result = 0;
7325 if (getEffectChain_l(sessionId) != 0) {
7326 result = EFFECT_SESSION;
7327 }
7328
7329 for (size_t i = 0; i < mTracks.size(); ++i) {
7330 if (sessionId == mTracks[i]->sessionId()) {
7331 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007332 if (mTracks[i]->isFastTrack()) {
7333 result |= FAST_SESSION;
7334 }
Eric Laurent81784c32012-11-19 14:55:58 -08007335 break;
7336 }
7337 }
7338
7339 return result;
7340}
7341
Glenn Kastend848eb42016-03-08 13:42:11 -08007342KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007343{
Glenn Kastend848eb42016-03-08 13:42:11 -08007344 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007345 Mutex::Autolock _l(mLock);
7346 for (size_t j = 0; j < mTracks.size(); ++j) {
7347 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007348 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007349 if (ids.indexOfKey(sessionId) < 0) {
7350 ids.add(sessionId, true);
7351 }
7352 }
7353 return ids;
7354}
7355
7356AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7357{
7358 Mutex::Autolock _l(mLock);
7359 AudioStreamIn *input = mInput;
7360 mInput = NULL;
7361 return input;
7362}
7363
7364// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007365sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007366{
7367 if (mInput == NULL) {
7368 return NULL;
7369 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007370 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007371}
7372
7373status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7374{
7375 // only one chain per input thread
7376 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007377 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007378 return INVALID_OPERATION;
7379 }
7380 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007381 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007382 chain->setInBuffer(NULL);
7383 chain->setOutBuffer(NULL);
7384
7385 checkSuspendOnAddEffectChain_l(chain);
7386
Eric Laurent1b928682014-10-02 19:41:47 -07007387 // make sure enabled pre processing effects state is communicated to the HAL as we
7388 // just moved them to a new input stream.
7389 chain->syncHalEffectsState();
7390
Eric Laurent81784c32012-11-19 14:55:58 -08007391 mEffectChains.add(chain);
7392
7393 return NO_ERROR;
7394}
7395
7396size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7397{
7398 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7399 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007400 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007401 chain.get(), mEffectChains.size(), this);
7402 if (mEffectChains.size() == 1) {
7403 mEffectChains.removeAt(0);
7404 }
7405 return 0;
7406}
7407
Eric Laurent1c333e22014-05-20 10:48:17 -07007408status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7409 audio_patch_handle_t *handle)
7410{
7411 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007412
7413 // store new device and send to effects
7414 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007415 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007416 for (size_t i = 0; i < mEffectChains.size(); i++) {
7417 mEffectChains[i]->setDevice_l(mInDevice);
7418 }
7419
Eric Laurentd8365c52017-07-16 15:27:05 -07007420 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007421
7422 // store new source and send to effects
7423 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7424 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007425 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007426 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007427 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007428 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007429
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007430 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007431 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7432 status = hwDevice->createAudioPatch(patch->num_sources,
7433 patch->sources,
7434 patch->num_sinks,
7435 patch->sinks,
7436 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007437 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007438 char *address;
7439 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7440 address = audio_device_address_to_parameter(
7441 patch->sources[0].ext.device.type,
7442 patch->sources[0].ext.device.address);
7443 } else {
7444 address = (char *)calloc(1, 1);
7445 }
7446 AudioParameter param = AudioParameter(String8(address));
7447 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007448 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007449 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007450 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007451 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007452 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007453 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007454 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007455
Eric Laurente8726fe2015-06-26 09:39:24 -07007456 if (mInDevice != mPrevInDevice) {
7457 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7458 mPrevInDevice = mInDevice;
7459 }
Eric Laurent296fb132015-05-01 11:38:42 -07007460
Eric Laurent1c333e22014-05-20 10:48:17 -07007461 return status;
7462}
7463
7464status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7465{
7466 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007467
7468 mInDevice = AUDIO_DEVICE_NONE;
7469
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007470 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007471 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7472 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007473 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007474 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007475 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007476 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007477 }
7478 return status;
7479}
7480
Eric Laurent83b88082014-06-20 18:31:16 -07007481void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7482{
7483 Mutex::Autolock _l(mLock);
7484 mTracks.add(record);
7485}
7486
7487void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7488{
7489 Mutex::Autolock _l(mLock);
7490 destroyTrack_l(record);
7491}
7492
7493void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7494{
7495 ThreadBase::getAudioPortConfig(config);
7496 config->role = AUDIO_PORT_ROLE_SINK;
7497 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7498 config->ext.mix.usecase.source = mAudioSource;
7499}
Eric Laurent1c333e22014-05-20 10:48:17 -07007500
Eric Laurent6acd1d42017-01-04 14:23:29 -08007501// ----------------------------------------------------------------------------
7502// Mmap
7503// ----------------------------------------------------------------------------
7504
7505AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7506 : mThread(thread)
7507{
Phil Burk9fabbf82017-08-03 12:02:00 -07007508 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007509}
7510
7511AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7512{
Phil Burk9fabbf82017-08-03 12:02:00 -07007513 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007514}
7515
7516status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7517 struct audio_mmap_buffer_info *info)
7518{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007519 return mThread->createMmapBuffer(minSizeFrames, info);
7520}
7521
7522status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7523{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007524 return mThread->getMmapPosition(position);
7525}
7526
Eric Laurenta54f1282017-07-01 19:39:32 -07007527status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007528 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007529
7530{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007531 return mThread->start(client, handle);
7532}
7533
7534status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7535{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007536 return mThread->stop(handle);
7537}
7538
Eric Laurent18b57012017-02-13 16:23:52 -08007539status_t AudioFlinger::MmapThreadHandle::standby()
7540{
Eric Laurent18b57012017-02-13 16:23:52 -08007541 return mThread->standby();
7542}
7543
Eric Laurent6acd1d42017-01-04 14:23:29 -08007544
7545AudioFlinger::MmapThread::MmapThread(
7546 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7547 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7548 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7549 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007550 mSessionId(AUDIO_SESSION_NONE),
7551 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007552 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7553 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007554{
Eric Laurent18b57012017-02-13 16:23:52 -08007555 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007556 readHalParameters_l();
7557}
7558
7559AudioFlinger::MmapThread::~MmapThread()
7560{
Eric Laurent18b57012017-02-13 16:23:52 -08007561 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007562}
7563
7564void AudioFlinger::MmapThread::onFirstRef()
7565{
7566 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7567}
7568
7569void AudioFlinger::MmapThread::disconnect()
7570{
7571 for (const sp<MmapTrack> &t : mActiveTracks) {
7572 stop(t->portId());
7573 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007574 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007575 if (isOutput()) {
7576 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7577 } else {
7578 AudioSystem::releaseInput(mId, mSessionId);
7579 }
7580}
7581
7582
7583void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7584 audio_stream_type_t streamType __unused,
7585 audio_session_t sessionId,
7586 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007587 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007588 audio_port_handle_t portId)
7589{
7590 mAttr = *attr;
7591 mSessionId = sessionId;
7592 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007593 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007594 mPortId = portId;
7595}
7596
7597status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7598 struct audio_mmap_buffer_info *info)
7599{
7600 if (mHalStream == 0) {
7601 return NO_INIT;
7602 }
Eric Laurent18b57012017-02-13 16:23:52 -08007603 mStandby = true;
7604 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007605 return mHalStream->createMmapBuffer(minSizeFrames, info);
7606}
7607
7608status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7609{
7610 if (mHalStream == 0) {
7611 return NO_INIT;
7612 }
7613 return mHalStream->getMmapPosition(position);
7614}
7615
Eric Laurenta54f1282017-07-01 19:39:32 -07007616status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007617 audio_port_handle_t *handle)
7618{
Eric Laurenta54f1282017-07-01 19:39:32 -07007619 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7620 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007621 if (mHalStream == 0) {
7622 return NO_INIT;
7623 }
7624
7625 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007626
Eric Laurenta54f1282017-07-01 19:39:32 -07007627 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007628 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007629 ret = mHalStream->start();
7630 if (ret != NO_ERROR) {
7631 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7632 return ret;
7633 }
Eric Laurent18b57012017-02-13 16:23:52 -08007634 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007635 return NO_ERROR;
7636 }
7637
Phil Burk81ad5ec2017-09-01 10:45:41 -07007638 if (!isOutput() && !recordingAllowed(client.packageName, client.clientPid, client.clientUid)) {
7639 return PERMISSION_DENIED;
7640 }
7641
Eric Laurenta54f1282017-07-01 19:39:32 -07007642 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7643
7644 audio_io_handle_t io = mId;
7645 if (isOutput()) {
7646 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7647 config.sample_rate = mSampleRate;
7648 config.channel_mask = mChannelMask;
7649 config.format = mFormat;
7650 audio_stream_type_t stream = streamType();
7651 audio_output_flags_t flags =
7652 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007653 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007654 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7655 mSessionId,
7656 &stream,
7657 client.clientUid,
7658 &config,
7659 flags,
7660 &deviceId,
7661 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007662 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007663 audio_config_base_t config;
7664 config.sample_rate = mSampleRate;
7665 config.channel_mask = mChannelMask;
7666 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007667 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007668 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7669 mSessionId,
7670 client.clientPid,
7671 client.clientUid,
7672 &config,
7673 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7674 &deviceId,
7675 &portId);
7676 }
7677 // APM should not chose a different input or output stream for the same set of attributes
7678 // and audo configuration
7679 if (ret != NO_ERROR || io != mId) {
7680 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
7681 __FUNCTION__, ret, io, mId);
7682 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007683 }
7684
7685 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007686 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007687 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007688 ret = AudioSystem::startInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007689 }
7690
7691 // abort if start is rejected by audio policy manager
7692 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08007693 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007694 if (mActiveTracks.size() != 0) {
7695 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07007696 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007697 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007698 AudioSystem::releaseInput(mId, mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007699 }
Eric Laurent18b57012017-02-13 16:23:52 -08007700 } else {
7701 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007702 }
7703 return PERMISSION_DENIED;
7704 }
7705
Eric Laurenta54f1282017-07-01 19:39:32 -07007706 sp<MmapTrack> track = new MmapTrack(this, mSampleRate, mFormat, mChannelMask, mSessionId,
7707 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007708
7709 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07007710 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007711 if (chain != 0) {
7712 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
7713 chain->incTrackCnt();
7714 chain->incActiveTrackCnt();
7715 }
7716
7717 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007718 broadcast_l();
7719
Eric Laurenta54f1282017-07-01 19:39:32 -07007720 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007721
7722 return NO_ERROR;
7723}
7724
7725status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
7726{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007727 ALOGV("%s handle %d", __FUNCTION__, handle);
7728
7729 if (mHalStream == 0) {
7730 return NO_INIT;
7731 }
7732
Eric Laurenta54f1282017-07-01 19:39:32 -07007733 if (handle == mPortId) {
7734 mHalStream->stop();
7735 return NO_ERROR;
7736 }
7737
Eric Laurent6acd1d42017-01-04 14:23:29 -08007738 sp<MmapTrack> track;
7739 for (const sp<MmapTrack> &t : mActiveTracks) {
7740 if (handle == t->portId()) {
7741 track = t;
7742 break;
7743 }
7744 }
7745 if (track == 0) {
7746 return BAD_VALUE;
7747 }
7748
7749 mActiveTracks.remove(track);
7750
7751 if (isOutput()) {
7752 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007753 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007754 } else {
7755 AudioSystem::stopInput(mId, track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07007756 AudioSystem::releaseInput(mId, track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007757 }
7758
7759 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
7760 if (chain != 0) {
7761 chain->decActiveTrackCnt();
7762 chain->decTrackCnt();
7763 }
7764
7765 broadcast_l();
7766
Eric Laurent6acd1d42017-01-04 14:23:29 -08007767 return NO_ERROR;
7768}
7769
Eric Laurent18b57012017-02-13 16:23:52 -08007770status_t AudioFlinger::MmapThread::standby()
7771{
7772 ALOGV("%s", __FUNCTION__);
7773
7774 if (mHalStream == 0) {
7775 return NO_INIT;
7776 }
7777 if (mActiveTracks.size() != 0) {
7778 return INVALID_OPERATION;
7779 }
7780 mHalStream->standby();
7781 mStandby = true;
7782 releaseWakeLock();
7783 return NO_ERROR;
7784}
7785
Eric Laurent6acd1d42017-01-04 14:23:29 -08007786
7787void AudioFlinger::MmapThread::readHalParameters_l()
7788{
7789 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7790 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
7791 mFormat = mHALFormat;
7792 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7793 result = mHalStream->getFrameSize(&mFrameSize);
7794 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7795 result = mHalStream->getBufferSize(&mBufferSize);
7796 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
7797 mFrameCount = mBufferSize / mFrameSize;
7798}
7799
7800bool AudioFlinger::MmapThread::threadLoop()
7801{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007802 checkSilentMode_l();
7803
7804 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
7805
7806 while (!exitPending())
7807 {
7808 Mutex::Autolock _l(mLock);
7809 Vector< sp<EffectChain> > effectChains;
7810
7811 if (mSignalPending) {
7812 // A signal was raised while we were unlocked
7813 mSignalPending = false;
7814 } else {
7815 if (mConfigEvents.isEmpty()) {
7816 // we're about to wait, flush the binder command buffer
7817 IPCThreadState::self()->flushCommands();
7818
7819 if (exitPending()) {
7820 break;
7821 }
7822
Eric Laurent6acd1d42017-01-04 14:23:29 -08007823 // wait until we have something to do...
7824 ALOGV("%s going to sleep", myName.string());
7825 mWaitWorkCV.wait(mLock);
7826 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08007827
7828 checkSilentMode_l();
7829
7830 continue;
7831 }
7832 }
7833
7834 processConfigEvents_l();
7835
7836 processVolume_l();
7837
7838 checkInvalidTracks_l();
7839
7840 mActiveTracks.updatePowerState(this);
7841
7842 lockEffectChains_l(effectChains);
7843 for (size_t i = 0; i < effectChains.size(); i ++) {
7844 effectChains[i]->process_l();
7845 }
7846 // enable changes in effect chain
7847 unlockEffectChains(effectChains);
7848 // Effect chains will be actually deleted here if they were removed from
7849 // mEffectChains list during mixing or effects processing
7850 }
7851
7852 threadLoop_exit();
7853
7854 if (!mStandby) {
7855 threadLoop_standby();
7856 mStandby = true;
7857 }
7858
Eric Laurent6acd1d42017-01-04 14:23:29 -08007859 ALOGV("Thread %p type %d exiting", this, mType);
7860 return false;
7861}
7862
7863// checkForNewParameter_l() must be called with ThreadBase::mLock held
7864bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
7865 status_t& status)
7866{
7867 AudioParameter param = AudioParameter(keyValuePair);
7868 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07007869 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007870 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007871 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007872 // forward device change to effects that have requested to be
7873 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07007874 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007875 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07007876 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007877 }
7878 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007879 if (audio_is_output_devices(device)) {
7880 mOutDevice = device;
7881 if (!isOutput()) {
7882 sendToHal = false;
7883 }
7884 } else {
7885 mInDevice = device;
7886 if (device != AUDIO_DEVICE_NONE) {
7887 mPrevInDevice = value;
7888 }
7889 // TODO: implement and call checkBtNrec_l();
7890 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007891 }
Eric Laurente6e9a482017-07-25 19:26:02 -07007892 if (sendToHal) {
7893 status = mHalStream->setParameters(keyValuePair);
7894 } else {
7895 status = NO_ERROR;
7896 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08007897
7898 return false;
7899}
7900
7901String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
7902{
7903 Mutex::Autolock _l(mLock);
7904 String8 out_s8;
7905 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
7906 return out_s8;
7907 }
7908 return String8();
7909}
7910
7911void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
7912 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7913
7914 desc->mIoHandle = mId;
7915
7916 switch (event) {
7917 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007918 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08007919 case AUDIO_INPUT_CONFIG_CHANGED:
7920 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007921 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08007922 case AUDIO_OUTPUT_CONFIG_CHANGED:
7923 desc->mPatch = mPatch;
7924 desc->mChannelMask = mChannelMask;
7925 desc->mSamplingRate = mSampleRate;
7926 desc->mFormat = mFormat;
7927 desc->mFrameCount = mFrameCount;
7928 desc->mFrameCountHAL = mFrameCount;
7929 desc->mLatency = 0;
7930 break;
7931
7932 case AUDIO_INPUT_CLOSED:
7933 case AUDIO_OUTPUT_CLOSED:
7934 default:
7935 break;
7936 }
7937 mAudioFlinger->ioConfigChanged(event, desc, pid);
7938}
7939
7940status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
7941 audio_patch_handle_t *handle)
7942{
7943 status_t status = NO_ERROR;
7944
7945 // store new device and send to effects
7946 audio_devices_t type = AUDIO_DEVICE_NONE;
7947 audio_port_handle_t deviceId;
7948 if (isOutput()) {
7949 for (unsigned int i = 0; i < patch->num_sinks; i++) {
7950 type |= patch->sinks[i].ext.device.type;
7951 }
7952 deviceId = patch->sinks[0].id;
7953 } else {
7954 type = patch->sources[0].ext.device.type;
7955 deviceId = patch->sources[0].id;
7956 }
7957
7958 for (size_t i = 0; i < mEffectChains.size(); i++) {
7959 mEffectChains[i]->setDevice_l(type);
7960 }
7961
7962 if (isOutput()) {
7963 mOutDevice = type;
7964 } else {
7965 mInDevice = type;
7966 // store new source and send to effects
7967 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7968 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
7969 for (size_t i = 0; i < mEffectChains.size(); i++) {
7970 mEffectChains[i]->setAudioSource_l(mAudioSource);
7971 }
7972 }
7973 }
7974
7975 if (mAudioHwDev->supportsAudioPatches()) {
7976 status = mHalDevice->createAudioPatch(patch->num_sources,
7977 patch->sources,
7978 patch->num_sinks,
7979 patch->sinks,
7980 handle);
7981 } else {
7982 char *address;
7983 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
7984 //FIXME: we only support address on first sink with HAL version < 3.0
7985 address = audio_device_address_to_parameter(
7986 patch->sinks[0].ext.device.type,
7987 patch->sinks[0].ext.device.address);
7988 } else {
7989 address = (char *)calloc(1, 1);
7990 }
7991 AudioParameter param = AudioParameter(String8(address));
7992 free(address);
7993 param.addInt(String8(AudioParameter::keyRouting), (int)type);
7994 if (!isOutput()) {
7995 param.addInt(String8(AudioParameter::keyInputSource),
7996 (int)patch->sinks[0].ext.mix.usecase.source);
7997 }
7998 status = mHalStream->setParameters(param.toString());
7999 *handle = AUDIO_PATCH_HANDLE_NONE;
8000 }
8001
8002 if (isOutput() && mPrevOutDevice != mOutDevice) {
8003 mPrevOutDevice = type;
8004 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008005 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008006 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008007 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008008 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008009 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008010 }
8011 if (!isOutput() && mPrevInDevice != mInDevice) {
8012 mPrevInDevice = type;
8013 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008014 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008015 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008016 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008017 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008018 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008019 }
8020 return status;
8021}
8022
8023status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8024{
8025 status_t status = NO_ERROR;
8026
8027 mInDevice = AUDIO_DEVICE_NONE;
8028
8029 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8030 supportsAudioPatches : false;
8031
8032 if (supportsAudioPatches) {
8033 status = mHalDevice->releaseAudioPatch(handle);
8034 } else {
8035 AudioParameter param;
8036 param.addInt(String8(AudioParameter::keyRouting), 0);
8037 status = mHalStream->setParameters(param.toString());
8038 }
8039 return status;
8040}
8041
8042void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8043{
8044 ThreadBase::getAudioPortConfig(config);
8045 if (isOutput()) {
8046 config->role = AUDIO_PORT_ROLE_SOURCE;
8047 config->ext.mix.hw_module = mAudioHwDev->handle();
8048 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8049 } else {
8050 config->role = AUDIO_PORT_ROLE_SINK;
8051 config->ext.mix.hw_module = mAudioHwDev->handle();
8052 config->ext.mix.usecase.source = mAudioSource;
8053 }
8054}
8055
8056status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8057{
8058 audio_session_t session = chain->sessionId();
8059
8060 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8061 // Attach all tracks with same session ID to this chain.
8062 // indicate all active tracks in the chain
8063 for (const sp<MmapTrack> &track : mActiveTracks) {
8064 if (session == track->sessionId()) {
8065 chain->incTrackCnt();
8066 chain->incActiveTrackCnt();
8067 }
8068 }
8069
8070 chain->setThread(this);
8071 chain->setInBuffer(nullptr);
8072 chain->setOutBuffer(nullptr);
8073 chain->syncHalEffectsState();
8074
8075 mEffectChains.add(chain);
8076 checkSuspendOnAddEffectChain_l(chain);
8077 return NO_ERROR;
8078}
8079
8080size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8081{
8082 audio_session_t session = chain->sessionId();
8083
8084 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8085
8086 for (size_t i = 0; i < mEffectChains.size(); i++) {
8087 if (chain == mEffectChains[i]) {
8088 mEffectChains.removeAt(i);
8089 // detach all active tracks from the chain
8090 // detach all tracks with same session ID from this chain
8091 for (const sp<MmapTrack> &track : mActiveTracks) {
8092 if (session == track->sessionId()) {
8093 chain->decActiveTrackCnt();
8094 chain->decTrackCnt();
8095 }
8096 }
8097 break;
8098 }
8099 }
8100 return mEffectChains.size();
8101}
8102
8103// hasAudioSession_l() must be called with ThreadBase::mLock held
8104uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8105{
8106 uint32_t result = 0;
8107 if (getEffectChain_l(sessionId) != 0) {
8108 result = EFFECT_SESSION;
8109 }
8110
8111 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8112 sp<MmapTrack> track = mActiveTracks[i];
8113 if (sessionId == track->sessionId()) {
8114 result |= TRACK_SESSION;
8115 if (track->isFastTrack()) {
8116 result |= FAST_SESSION;
8117 }
8118 break;
8119 }
8120 }
8121
8122 return result;
8123}
8124
8125void AudioFlinger::MmapThread::threadLoop_standby()
8126{
8127 mHalStream->standby();
8128}
8129
8130void AudioFlinger::MmapThread::threadLoop_exit()
8131{
Phil Burk7f6b40d2017-02-09 13:18:38 -08008132 sp<MmapStreamCallback> callback = mCallback.promote();
8133 if (callback != 0) {
8134 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008135 }
8136}
8137
8138status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8139{
8140 return BAD_VALUE;
8141}
8142
8143bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8144{
8145 return false;
8146}
8147
8148status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8149 const effect_descriptor_t *desc, audio_session_t sessionId)
8150{
8151 // No global effect sessions on mmap threads
8152 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8153 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8154 desc->name, mThreadName);
8155 return BAD_VALUE;
8156 }
8157
8158 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8159 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8160 desc->name);
8161 return BAD_VALUE;
8162 }
8163 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008164 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8165 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008166 return BAD_VALUE;
8167 }
8168
8169 // Only allow effects without processing load or latency
8170 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8171 return BAD_VALUE;
8172 }
8173
8174 return NO_ERROR;
8175
8176}
8177
8178void AudioFlinger::MmapThread::checkInvalidTracks_l()
8179{
8180 for (const sp<MmapTrack> &track : mActiveTracks) {
8181 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008182 sp<MmapStreamCallback> callback = mCallback.promote();
8183 if (callback != 0) {
8184 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008185 }
8186 break;
8187 }
8188 }
8189}
8190
8191void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8192{
8193 dumpInternals(fd, args);
8194 dumpTracks(fd, args);
8195 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008196 dprintf(fd, " Local log:\n");
8197 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008198}
8199
8200void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8201{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008202 dumpBase(fd, args);
8203
8204 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8205 mAttr.content_type, mAttr.usage, mAttr.source);
8206 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8207 if (mActiveTracks.size() == 0) {
8208 dprintf(fd, " No active clients\n");
8209 }
8210}
8211
8212void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8213{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008214 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008215 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008216 dprintf(fd, " %zu Tracks\n", numtracks);
8217 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008218 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008219 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008220 MmapTrack::appendDumpHeader(result);
8221 for (size_t i = 0; i < numtracks ; ++i) {
8222 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008223 result.append(prefix);
8224 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008225 }
8226 } else {
8227 dprintf(fd, "\n");
8228 }
8229 write(fd, result.string(), result.size());
8230}
8231
8232AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8233 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8234 AudioHwDevice *hwDev, AudioStreamOut *output,
8235 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8236 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8237 mStreamType(AUDIO_STREAM_MUSIC),
8238 mStreamVolume(1.0), mStreamMute(false), mOutput(output)
8239{
8240 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8241 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8242 mMasterVolume = audioFlinger->masterVolume_l();
8243 mMasterMute = audioFlinger->masterMute_l();
8244 if (mAudioHwDev) {
8245 if (mAudioHwDev->canSetMasterVolume()) {
8246 mMasterVolume = 1.0;
8247 }
8248
8249 if (mAudioHwDev->canSetMasterMute()) {
8250 mMasterMute = false;
8251 }
8252 }
8253}
8254
8255void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8256 audio_stream_type_t streamType,
8257 audio_session_t sessionId,
8258 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008259 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008260 audio_port_handle_t portId)
8261{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008262 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008263 mStreamType = streamType;
8264}
8265
8266AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8267{
8268 Mutex::Autolock _l(mLock);
8269 AudioStreamOut *output = mOutput;
8270 mOutput = NULL;
8271 return output;
8272}
8273
8274void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8275{
8276 Mutex::Autolock _l(mLock);
8277 // Don't apply master volume in SW if our HAL can do it for us.
8278 if (mAudioHwDev &&
8279 mAudioHwDev->canSetMasterVolume()) {
8280 mMasterVolume = 1.0;
8281 } else {
8282 mMasterVolume = value;
8283 }
8284}
8285
8286void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8287{
8288 Mutex::Autolock _l(mLock);
8289 // Don't apply master mute in SW if our HAL can do it for us.
8290 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8291 mMasterMute = false;
8292 } else {
8293 mMasterMute = muted;
8294 }
8295}
8296
8297void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8298{
8299 Mutex::Autolock _l(mLock);
8300 if (stream == mStreamType) {
8301 mStreamVolume = value;
8302 broadcast_l();
8303 }
8304}
8305
8306float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8307{
8308 Mutex::Autolock _l(mLock);
8309 if (stream == mStreamType) {
8310 return mStreamVolume;
8311 }
8312 return 0.0f;
8313}
8314
8315void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8316{
8317 Mutex::Autolock _l(mLock);
8318 if (stream == mStreamType) {
8319 mStreamMute= muted;
8320 broadcast_l();
8321 }
8322}
8323
8324void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8325{
8326 Mutex::Autolock _l(mLock);
8327 if (streamType == mStreamType) {
8328 for (const sp<MmapTrack> &track : mActiveTracks) {
8329 track->invalidate();
8330 }
8331 broadcast_l();
8332 }
8333}
8334
8335void AudioFlinger::MmapPlaybackThread::processVolume_l()
8336{
8337 float volume;
8338
8339 if (mMasterMute || mStreamMute) {
8340 volume = 0;
8341 } else {
8342 volume = mMasterVolume * mStreamVolume;
8343 }
8344
8345 if (volume != mHalVolFloat) {
8346 mHalVolFloat = volume;
8347
8348 // Convert volumes from float to 8.24
8349 uint32_t vol = (uint32_t)(volume * (1 << 24));
8350
8351 // Delegate volume control to effect in track effect chain if needed
8352 // only one effect chain can be present on DirectOutputThread, so if
8353 // there is one, the track is connected to it
8354 if (!mEffectChains.isEmpty()) {
8355 mEffectChains[0]->setVolume_l(&vol, &vol);
8356 volume = (float)vol / (1 << 24);
8357 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008358 // Try to use HW volume control and fall back to SW control if not implemented
8359 if (mOutput->stream->setVolume(volume, volume) != NO_ERROR) {
8360 sp<MmapStreamCallback> callback = mCallback.promote();
8361 if (callback != 0) {
8362 int channelCount;
8363 if (isOutput()) {
8364 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8365 } else {
8366 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8367 }
8368 Vector<float> values;
8369 for (int i = 0; i < channelCount; i++) {
8370 values.add(volume);
8371 }
8372 callback->onVolumeChanged(mChannelMask, values);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008373 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008374 ALOGW("Could not set MMAP stream volume: no volume callback!");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008375 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008376 }
8377 }
8378}
8379
8380void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8381{
8382 if (!mMasterMute) {
8383 char value[PROPERTY_VALUE_MAX];
8384 if (property_get("ro.audio.silent", value, "0") > 0) {
8385 char *endptr;
8386 unsigned long ul = strtoul(value, &endptr, 0);
8387 if (*endptr == '\0' && ul != 0) {
8388 ALOGD("Silence is golden");
8389 // The setprop command will not allow a property to be changed after
8390 // the first time it is set, so we don't have to worry about un-muting.
8391 setMasterMute_l(true);
8392 }
8393 }
8394 }
8395}
8396
8397void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8398{
8399 MmapThread::dumpInternals(fd, args);
8400
Glenn Kastend3bb6452016-12-05 18:14:37 -08008401 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8402 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008403 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8404}
8405
8406AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8407 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8408 AudioHwDevice *hwDev, AudioStreamIn *input,
8409 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8410 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8411 mInput(input)
8412{
8413 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8414 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8415}
8416
8417AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8418{
8419 Mutex::Autolock _l(mLock);
8420 AudioStreamIn *input = mInput;
8421 mInput = NULL;
8422 return input;
8423}
Glenn Kasten63238ef2015-03-02 15:50:29 -08008424} // namespace android