blob: 5fc422e5ac43d32985a41f5cf0c03d6697bbf2ef [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
Kevin Rocard7588ff42018-01-08 11:11:30 -080059#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070060#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080061
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070064#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070065#include <mediautils/SchedulingPolicyService.h>
66#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080067
Eric Laurent81784c32012-11-19 14:55:58 -080068#ifdef ADD_BATTERY_DATA
69#include <media/IMediaPlayerService.h>
70#include <media/IMediaDeathNotifier.h>
71#endif
72
Eric Laurent81784c32012-11-19 14:55:58 -080073#ifdef DEBUG_CPU_USAGE
74#include <cpustats/CentralTendencyStatistics.h>
75#include <cpustats/ThreadCpuUsage.h>
76#endif
77
Glenn Kastenc05b8d72016-03-24 09:48:17 -070078#include "AutoPark.h"
79
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080080#include <pthread.h>
81#include "TypedLogger.h"
82
Eric Laurent81784c32012-11-19 14:55:58 -080083// ----------------------------------------------------------------------------
84
85// Note: the following macro is used for extremely verbose logging message. In
86// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
87// 0; but one side effect of this is to turn all LOGV's as well. Some messages
88// are so verbose that we want to suppress them even when we have ALOG_ASSERT
89// turned on. Do not uncomment the #def below unless you really know what you
90// are doing and want to see all of the extremely verbose messages.
91//#define VERY_VERY_VERBOSE_LOGGING
92#ifdef VERY_VERY_VERBOSE_LOGGING
93#define ALOGVV ALOGV
94#else
95#define ALOGVV(a...) do { } while(0)
96#endif
97
Andy Hung6770c6f2015-04-07 13:43:36 -070098// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070099#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700100template <typename T>
101static inline T min(const T& a, const T& b)
102{
103 return a < b ? a : b;
104}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700105
Eric Laurent81784c32012-11-19 14:55:58 -0800106namespace android {
107
108// retry counts for buffer fill timeout
109// 50 * ~20msecs = 1 second
110static const int8_t kMaxTrackRetries = 50;
111static const int8_t kMaxTrackStartupRetries = 50;
112// allow less retry attempts on direct output thread.
113// direct outputs can be a scarce resource in audio hardware and should
114// be released as quickly as possible.
115static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700116
Eric Laurent51716182016-02-29 18:00:56 -0800117
Eric Laurent81784c32012-11-19 14:55:58 -0800118
119// don't warn about blocked writes or record buffer overflows more often than this
120static const nsecs_t kWarningThrottleNs = seconds(5);
121
122// RecordThread loop sleep time upon application overrun or audio HAL read error
123static const int kRecordThreadSleepUs = 5000;
124
Eric Laurent10351942014-05-08 18:49:52 -0700125// maximum time to wait in sendConfigEvent_l() for a status to be received
126static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128// minimum sleep time for the mixer thread loop when tracks are active but in underrun
129static const uint32_t kMinThreadSleepTimeUs = 5000;
130// maximum divider applied to the active sleep time in the mixer thread loop
131static const uint32_t kMaxThreadSleepTimeShift = 2;
132
Andy Hung09a50072014-02-27 14:30:47 -0800133// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800135static const uint32_t kMinNormalSinkBufferSizeMs = 20;
136// maximum normal sink buffer size
137static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800138
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
140// FIXME This should be based on experimentally observed scheduling jitter
141static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
142
Eric Laurent972a1732013-09-04 09:42:59 -0700143// Offloaded output thread standby delay: allows track transition without going to standby
144static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
145
Eric Laurent51716182016-02-29 18:00:56 -0800146// Direct output thread minimum sleep time in idle or active(underrun) state
147static const nsecs_t kDirectMinSleepTimeUs = 10000;
148
Glenn Kasten1b291842016-07-18 14:55:21 -0700149// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
150// balance between power consumption and latency, and allows threads to be scheduled reliably
151// by the CFS scheduler.
152// FIXME Express other hardcoded references to 20ms with references to this constant and move
153// it appropriately.
154#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800155
Eric Laurent81784c32012-11-19 14:55:58 -0800156// Whether to use fast mixer
157static const enum {
158 FastMixer_Never, // never initialize or use: for debugging only
159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
160 // normal mixer multiplier is 1
161 FastMixer_Static, // initialize if needed, then use all the time if initialized,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 // FIXME for FastMixer_Dynamic:
166 // Supporting this option will require fixing HALs that can't handle large writes.
167 // For example, one HAL implementation returns an error from a large write,
168 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
169 // We could either fix the HAL implementations, or provide a wrapper that breaks
170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700173// Whether to use fast capture
174static const enum {
175 FastCapture_Never, // never initialize or use: for debugging only
176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177 FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
Glenn Kastenea38ee72016-04-18 11:08:01 -0700185// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
186// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
187// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700188
189// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800190static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800191
Glenn Kasten03490092014-05-27 12:30:54 -0700192// The minimum and maximum allowed values
193static const int kFastTrackMultiplierMin = 1;
194static const int kFastTrackMultiplierMax = 2;
195
196// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
197static int sFastTrackMultiplier = kFastTrackMultiplier;
198
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700199// See Thread::readOnlyHeap().
200// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
201// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
202// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700203static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// ----------------------------------------------------------------------------
206
Glenn Kasten03490092014-05-27 12:30:54 -0700207static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
208
209static void sFastTrackMultiplierInit()
210{
211 char value[PROPERTY_VALUE_MAX];
212 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
213 char *endptr;
214 unsigned long ul = strtoul(value, &endptr, 0);
215 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
216 sFastTrackMultiplier = (int) ul;
217 }
218 }
219}
220
221// ----------------------------------------------------------------------------
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223#ifdef ADD_BATTERY_DATA
224// To collect the amplifier usage
225static void addBatteryData(uint32_t params) {
226 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
227 if (service == NULL) {
228 // it already logged
229 return;
230 }
231
232 service->addBatteryData(params);
233}
234#endif
235
Andy Hung3f0c9022016-01-15 17:49:46 -0800236// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
237struct {
238 // call when you acquire a partial wakelock
239 void acquire(const sp<IBinder> &wakeLockToken) {
240 pthread_mutex_lock(&mLock);
241 if (wakeLockToken.get() == nullptr) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 } else {
244 if (mCount == 0) {
245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
246 }
247 ++mCount;
248 }
249 pthread_mutex_unlock(&mLock);
250 }
251
252 // call when you release a partial wakelock.
253 void release(const sp<IBinder> &wakeLockToken) {
254 if (wakeLockToken.get() == nullptr) {
255 return;
256 }
257 pthread_mutex_lock(&mLock);
258 if (--mCount < 0) {
259 ALOGE("negative wakelock count");
260 mCount = 0;
261 }
262 pthread_mutex_unlock(&mLock);
263 }
264
265 // retrieves the boottime timebase offset from monotonic.
266 int64_t getBoottimeOffset() {
267 pthread_mutex_lock(&mLock);
268 int64_t boottimeOffset = mBoottimeOffset;
269 pthread_mutex_unlock(&mLock);
270 return boottimeOffset;
271 }
272
273 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
274 // and the selected timebase.
275 // Currently only TIMEBASE_BOOTTIME is allowed.
276 //
277 // This only needs to be called upon acquiring the first partial wakelock
278 // after all other partial wakelocks are released.
279 //
280 // We do an empirical measurement of the offset rather than parsing
281 // /proc/timer_list since the latter is not a formal kernel ABI.
282 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
283 int clockbase;
284 switch (timebase) {
285 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
286 clockbase = SYSTEM_TIME_BOOTTIME;
287 break;
288 default:
289 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
290 break;
291 }
292 // try three times to get the clock offset, choose the one
293 // with the minimum gap in measurements.
294 const int tries = 3;
295 nsecs_t bestGap, measured;
296 for (int i = 0; i < tries; ++i) {
297 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
298 const nsecs_t tbase = systemTime(clockbase);
299 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t gap = tmono2 - tmono;
301 if (i == 0 || gap < bestGap) {
302 bestGap = gap;
303 measured = tbase - ((tmono + tmono2) >> 1);
304 }
305 }
306
307 // to avoid micro-adjusting, we don't change the timebase
308 // unless it is significantly different.
309 //
310 // Assumption: It probably takes more than toleranceNs to
311 // suspend and resume the device.
312 static int64_t toleranceNs = 10000; // 10 us
313 if (llabs(*offset - measured) > toleranceNs) {
314 ALOGV("Adjusting timebase offset old: %lld new: %lld",
315 (long long)*offset, (long long)measured);
316 *offset = measured;
317 }
318 }
319
320 pthread_mutex_t mLock;
321 int32_t mCount;
322 int64_t mBoottimeOffset;
323} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800324
325// ----------------------------------------------------------------------------
326// CPU Stats
327// ----------------------------------------------------------------------------
328
329class CpuStats {
330public:
331 CpuStats();
332 void sample(const String8 &title);
333#ifdef DEBUG_CPU_USAGE
334private:
335 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
336 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
337
338 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
339
340 int mCpuNum; // thread's current CPU number
341 int mCpukHz; // frequency of thread's current CPU in kHz
342#endif
343};
344
345CpuStats::CpuStats()
346#ifdef DEBUG_CPU_USAGE
347 : mCpuNum(-1), mCpukHz(-1)
348#endif
349{
350}
351
Glenn Kasten0f11b512014-01-31 16:18:54 -0800352void CpuStats::sample(const String8 &title
353#ifndef DEBUG_CPU_USAGE
354 __unused
355#endif
356 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800357#ifdef DEBUG_CPU_USAGE
358 // get current thread's delta CPU time in wall clock ns
359 double wcNs;
360 bool valid = mCpuUsage.sampleAndEnable(wcNs);
361
362 // record sample for wall clock statistics
363 if (valid) {
364 mWcStats.sample(wcNs);
365 }
366
367 // get the current CPU number
368 int cpuNum = sched_getcpu();
369
370 // get the current CPU frequency in kHz
371 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
372
373 // check if either CPU number or frequency changed
374 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
375 mCpuNum = cpuNum;
376 mCpukHz = cpukHz;
377 // ignore sample for purposes of cycles
378 valid = false;
379 }
380
381 // if no change in CPU number or frequency, then record sample for cycle statistics
382 if (valid && mCpukHz > 0) {
383 double cycles = wcNs * cpukHz * 0.000001;
384 mHzStats.sample(cycles);
385 }
386
387 unsigned n = mWcStats.n();
388 // mCpuUsage.elapsed() is expensive, so don't call it every loop
389 if ((n & 127) == 1) {
390 long long elapsed = mCpuUsage.elapsed();
391 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
392 double perLoop = elapsed / (double) n;
393 double perLoop100 = perLoop * 0.01;
394 double perLoop1k = perLoop * 0.001;
395 double mean = mWcStats.mean();
396 double stddev = mWcStats.stddev();
397 double minimum = mWcStats.minimum();
398 double maximum = mWcStats.maximum();
399 double meanCycles = mHzStats.mean();
400 double stddevCycles = mHzStats.stddev();
401 double minCycles = mHzStats.minimum();
402 double maxCycles = mHzStats.maximum();
403 mCpuUsage.resetElapsed();
404 mWcStats.reset();
405 mHzStats.reset();
406 ALOGD("CPU usage for %s over past %.1f secs\n"
407 " (%u mixer loops at %.1f mean ms per loop):\n"
408 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
409 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
410 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
411 title.string(),
412 elapsed * .000000001, n, perLoop * .000001,
413 mean * .001,
414 stddev * .001,
415 minimum * .001,
416 maximum * .001,
417 mean / perLoop100,
418 stddev / perLoop100,
419 minimum / perLoop100,
420 maximum / perLoop100,
421 meanCycles / perLoop1k,
422 stddevCycles / perLoop1k,
423 minCycles / perLoop1k,
424 maxCycles / perLoop1k);
425
426 }
427 }
428#endif
429};
430
431// ----------------------------------------------------------------------------
432// ThreadBase
433// ----------------------------------------------------------------------------
434
Glenn Kasten97b7b752014-09-28 13:04:24 -0700435// static
436const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
437{
438 switch (type) {
439 case MIXER:
440 return "MIXER";
441 case DIRECT:
442 return "DIRECT";
443 case DUPLICATING:
444 return "DUPLICATING";
445 case RECORD:
446 return "RECORD";
447 case OFFLOAD:
448 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800449 case MMAP:
450 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700451 default:
452 return "unknown";
453 }
454}
455
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700456std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800457{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700458 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800459 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700460 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800461 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700462 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800463 }
464 return result;
465}
466
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700467std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700469 std::string result;
470 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471 return result;
472}
473
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700474std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700476 std::string result;
477 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700478 return result;
479}
480
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800481const char *sourceToString(audio_source_t source)
482{
483 switch (source) {
484 case AUDIO_SOURCE_DEFAULT: return "default";
485 case AUDIO_SOURCE_MIC: return "mic";
486 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
487 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
488 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
489 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
490 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
491 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
492 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800493 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800494 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
495 case AUDIO_SOURCE_HOTWORD: return "hotword";
496 default: return "unknown";
497 }
498}
499
Eric Laurent81784c32012-11-19 14:55:58 -0800500AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700501 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800502 : Thread(false /*canCallJava*/),
503 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700504 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700505 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800506 // are set by PlaybackThread::readOutputParameters_l() or
507 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700508 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800509 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700510 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
511 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800512 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700513 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800514 mSystemReady(systemReady),
515 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800516{
Eric Laurent296fb132015-05-01 11:38:42 -0700517 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800518}
519
520AudioFlinger::ThreadBase::~ThreadBase()
521{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700523 mConfigEvents.clear();
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525 // do not lock the mutex in destructor
526 releaseWakeLock_l();
527 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800528 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800529 binder->unlinkToDeath(mDeathRecipient);
530 }
531}
532
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700533status_t AudioFlinger::ThreadBase::readyToRun()
534{
535 status_t status = initCheck();
536 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800537 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700538 } else {
539 ALOGE("No working audio driver found.");
540 }
541 return status;
542}
543
Eric Laurent81784c32012-11-19 14:55:58 -0800544void AudioFlinger::ThreadBase::exit()
545{
546 ALOGV("ThreadBase::exit");
547 // do any cleanup required for exit to succeed
548 preExit();
549 {
550 // This lock prevents the following race in thread (uniprocessor for illustration):
551 // if (!exitPending()) {
552 // // context switch from here to exit()
553 // // exit() calls requestExit(), what exitPending() observes
554 // // exit() calls signal(), which is dropped since no waiters
555 // // context switch back from exit() to here
556 // mWaitWorkCV.wait(...);
557 // // now thread is hung
558 // }
559 AutoMutex lock(mLock);
560 requestExit();
561 mWaitWorkCV.broadcast();
562 }
563 // When Thread::requestExitAndWait is made virtual and this method is renamed to
564 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
565 requestExitAndWait();
566}
567
568status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
569{
Eric Laurent81784c32012-11-19 14:55:58 -0800570 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
571 Mutex::Autolock _l(mLock);
572
Eric Laurent10351942014-05-08 18:49:52 -0700573 return sendSetParameterConfigEvent_l(keyValuePairs);
574}
575
576// sendConfigEvent_l() must be called with ThreadBase::mLock held
577// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
578status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
579{
580 status_t status = NO_ERROR;
581
Eric Laurent72e3f392015-05-20 14:43:50 -0700582 if (event->mRequiresSystemReady && !mSystemReady) {
583 event->mWaitStatus = false;
584 mPendingConfigEvents.add(event);
585 return status;
586 }
Eric Laurent10351942014-05-08 18:49:52 -0700587 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700588 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800589 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700590 mLock.unlock();
591 {
592 Mutex::Autolock _l(event->mLock);
593 while (event->mWaitStatus) {
594 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
595 event->mStatus = TIMED_OUT;
596 event->mWaitStatus = false;
597 }
598 }
599 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800600 }
Eric Laurent10351942014-05-08 18:49:52 -0700601 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800602 return status;
603}
604
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800606{
607 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800609}
610
611// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700612void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800613{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700614 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700615 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800616}
617
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700619{
620 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800621 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700622}
623
Eric Laurent81784c32012-11-19 14:55:58 -0800624// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
626 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800628 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700629 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800630}
631
Eric Laurent10351942014-05-08 18:49:52 -0700632// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
633status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800634{
Andy Hung2ddee192015-12-18 17:34:44 -0800635 sp<ConfigEvent> configEvent;
636 AudioParameter param(keyValuePair);
637 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700638 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800639 setMasterMono_l(value != 0);
640 if (param.size() == 1) {
641 return NO_ERROR; // should be a solo parameter - we don't pass down
642 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700643 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800644 configEvent = new SetParameterConfigEvent(param.toString());
645 } else {
646 configEvent = new SetParameterConfigEvent(keyValuePair);
647 }
Eric Laurent10351942014-05-08 18:49:52 -0700648 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700649}
650
Eric Laurent1c333e22014-05-20 10:48:17 -0700651status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
652 const struct audio_patch *patch,
653 audio_patch_handle_t *handle)
654{
655 Mutex::Autolock _l(mLock);
656 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
657 status_t status = sendConfigEvent_l(configEvent);
658 if (status == NO_ERROR) {
659 CreateAudioPatchConfigEventData *data =
660 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
661 *handle = data->mHandle;
662 }
663 return status;
664}
665
666status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
667 const audio_patch_handle_t handle)
668{
669 Mutex::Autolock _l(mLock);
670 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
671 return sendConfigEvent_l(configEvent);
672}
673
674
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700675// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700676void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700677{
Eric Laurent10351942014-05-08 18:49:52 -0700678 bool configChanged = false;
679
Eric Laurent81784c32012-11-19 14:55:58 -0800680 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700681 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700682 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800683 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700684 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700685 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700686 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
687 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800688 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700689 true /*asynchronous*/);
690 if (err != 0) {
691 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700692 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700693 }
694 } break;
695 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700696 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700697 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700698 } break;
699 case CFG_EVENT_SET_PARAMETER: {
700 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
701 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
702 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700703 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
704 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700705 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700706 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700707 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700708 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700709 CreateAudioPatchConfigEventData *data =
710 (CreateAudioPatchConfigEventData *)event->mData.get();
711 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700712 const audio_devices_t newDevice = getDevice();
713 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
714 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
715 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 } break;
717 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700718 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 ReleaseAudioPatchConfigEventData *data =
720 (ReleaseAudioPatchConfigEventData *)event->mData.get();
721 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700722 const audio_devices_t newDevice = getDevice();
723 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
724 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
725 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700726 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 default:
Eric Laurent10351942014-05-08 18:49:52 -0700728 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent10351942014-05-08 18:49:52 -0700731 {
732 Mutex::Autolock _l(event->mLock);
733 if (event->mWaitStatus) {
734 event->mWaitStatus = false;
735 event->mCond.signal();
736 }
737 }
738 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
739 }
740
741 if (configChanged) {
742 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
Marco Nelissenb2208842014-02-07 14:00:50 -0800746String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
747 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700748 const audio_channel_representation_t representation =
749 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700750
751 switch (representation) {
752 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
753 if (output) {
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
758 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700772 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
773 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700774 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
775 } else {
776 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
780 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
783 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
784 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
785 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
786 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
787 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700788 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
789 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
790 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
791 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
792 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
793 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
795 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
796 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
797 }
798 const int len = s.length();
799 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700800 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700801 s.unlockBuffer(len - 2); // remove trailing ", "
802 }
803 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800804 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700805 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
806 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
807 return s;
808 default:
809 s.appendFormat("unknown mask, representation:%d bits:%#x",
810 representation, audio_channel_mask_get_bits(mask));
811 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800812 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800813}
814
Glenn Kasten0f11b512014-01-31 16:18:54 -0800815void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800816{
817 const size_t SIZE = 256;
818 char buffer[SIZE];
819 String8 result;
820
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800821 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
822 this, mThreadName, getTid(), type(), threadTypeToString(type()));
823
Eric Laurent81784c32012-11-19 14:55:58 -0800824 bool locked = AudioFlinger::dumpTryLock(mLock);
825 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800826 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800827 }
828
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700830 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700831 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700833 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700834 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " Channel count: %u\n", mChannelCount);
836 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700838 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700839 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700840 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 size_t numConfig = mConfigEvents.size();
842 if (numConfig) {
843 for (size_t i = 0; i < numConfig; i++) {
844 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700845 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800850 }
Andy Hung293558a2017-03-21 12:19:20 -0700851 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700852 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
853 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800854 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800855
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700856 // Dump timestamp statistics for the Thread types that support it.
857 if (mType == RECORD
858 || mType == MIXER
859 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700860 || mType == DIRECT
861 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700862 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
863 }
864
Eric Laurent81784c32012-11-19 14:55:58 -0800865 if (locked) {
866 mLock.unlock();
867 }
868}
869
870void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
871{
872 const size_t SIZE = 256;
873 char buffer[SIZE];
874 String8 result;
875
Marco Nelissenb2208842014-02-07 14:00:50 -0800876 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000877 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800878 write(fd, buffer, strlen(buffer));
879
Marco Nelissenb2208842014-02-07 14:00:50 -0800880 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800881 sp<EffectChain> chain = mEffectChains[i];
882 if (chain != 0) {
883 chain->dump(fd, args);
884 }
885 }
886}
887
Andy Hungdae27702016-10-31 14:01:16 -0700888void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800889{
890 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700891 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800892}
893
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100894String16 AudioFlinger::ThreadBase::getWakeLockTag()
895{
896 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800897 case MIXER:
898 return String16("AudioMix");
899 case DIRECT:
900 return String16("AudioDirectOut");
901 case DUPLICATING:
902 return String16("AudioDup");
903 case RECORD:
904 return String16("AudioIn");
905 case OFFLOAD:
906 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800907 case MMAP:
908 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800909 default:
910 ALOG_ASSERT(false);
911 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100912 }
913}
914
Andy Hungdae27702016-10-31 14:01:16 -0700915void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800916{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800917 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800918 if (mPowerManager != 0) {
919 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700920 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
921 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700922 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100923 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700924 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700925 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800926 if (status == NO_ERROR) {
927 mWakeLockToken = binder;
928 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800929 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800930 }
Wei Jia3f273d12015-11-24 09:06:49 -0800931
Andy Hung3f0c9022016-01-15 17:49:46 -0800932 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800933 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
934 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800935}
936
937void AudioFlinger::ThreadBase::releaseWakeLock()
938{
939 Mutex::Autolock _l(mLock);
940 releaseWakeLock_l();
941}
942
943void AudioFlinger::ThreadBase::releaseWakeLock_l()
944{
Andy Hung3f0c9022016-01-15 17:49:46 -0800945 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800946 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800947 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800948 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700949 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
950 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800951 }
952 mWakeLockToken.clear();
953 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800954}
955
956void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700957 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800958 // use checkService() to avoid blocking if power service is not up yet
959 sp<IBinder> binder =
960 defaultServiceManager()->checkService(String16("power"));
961 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800962 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800963 } else {
964 mPowerManager = interface_cast<IPowerManager>(binder);
965 binder->linkToDeath(mDeathRecipient);
966 }
967 }
968}
969
Andy Hungd01b0f12016-11-07 16:10:30 -0800970void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800971 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700972
973#if !LOG_NDEBUG
974 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800975 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700976 s << uid << " ";
977 }
978 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
979#endif
980
Andy Hung438e7572015-12-14 15:51:17 -0800981 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
982 if (mSystemReady) {
983 ALOGE("no wake lock to update, but system ready!");
984 } else {
985 ALOGW("no wake lock to update, system not ready yet");
986 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800987 return;
988 }
989 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800990 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
991 status_t status = mPowerManager->updateWakeLockUids(
992 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
993 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800994 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800995 }
996}
997
Eric Laurent81784c32012-11-19 14:55:58 -0800998void AudioFlinger::ThreadBase::clearPowerManager()
999{
1000 Mutex::Autolock _l(mLock);
1001 releaseWakeLock_l();
1002 mPowerManager.clear();
1003}
1004
Glenn Kasten0f11b512014-01-31 16:18:54 -08001005void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001006{
1007 sp<ThreadBase> thread = mThread.promote();
1008 if (thread != 0) {
1009 thread->clearPowerManager();
1010 }
1011 ALOGW("power manager service died !!!");
1012}
1013
Eric Laurent81784c32012-11-19 14:55:58 -08001014void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001015 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001016{
1017 sp<EffectChain> chain = getEffectChain_l(sessionId);
1018 if (chain != 0) {
1019 if (type != NULL) {
1020 chain->setEffectSuspended_l(type, suspend);
1021 } else {
1022 chain->setEffectSuspendedAll_l(suspend);
1023 }
1024 }
1025
1026 updateSuspendedSessions_l(type, suspend, sessionId);
1027}
1028
1029void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1030{
1031 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1032 if (index < 0) {
1033 return;
1034 }
1035
1036 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1037 mSuspendedSessions.valueAt(index);
1038
1039 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001040 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001041 for (int j = 0; j < desc->mRefCount; j++) {
1042 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1043 chain->setEffectSuspendedAll_l(true);
1044 } else {
1045 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1046 desc->mType.timeLow);
1047 chain->setEffectSuspended_l(&desc->mType, true);
1048 }
1049 }
1050 }
1051}
1052
1053void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1054 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001055 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001056{
1057 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1058
1059 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1060
1061 if (suspend) {
1062 if (index >= 0) {
1063 sessionEffects = mSuspendedSessions.valueAt(index);
1064 } else {
1065 mSuspendedSessions.add(sessionId, sessionEffects);
1066 }
1067 } else {
1068 if (index < 0) {
1069 return;
1070 }
1071 sessionEffects = mSuspendedSessions.valueAt(index);
1072 }
1073
1074
1075 int key = EffectChain::kKeyForSuspendAll;
1076 if (type != NULL) {
1077 key = type->timeLow;
1078 }
1079 index = sessionEffects.indexOfKey(key);
1080
1081 sp<SuspendedSessionDesc> desc;
1082 if (suspend) {
1083 if (index >= 0) {
1084 desc = sessionEffects.valueAt(index);
1085 } else {
1086 desc = new SuspendedSessionDesc();
1087 if (type != NULL) {
1088 desc->mType = *type;
1089 }
1090 sessionEffects.add(key, desc);
1091 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1092 }
1093 desc->mRefCount++;
1094 } else {
1095 if (index < 0) {
1096 return;
1097 }
1098 desc = sessionEffects.valueAt(index);
1099 if (--desc->mRefCount == 0) {
1100 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1101 sessionEffects.removeItemsAt(index);
1102 if (sessionEffects.isEmpty()) {
1103 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1104 sessionId);
1105 mSuspendedSessions.removeItem(sessionId);
1106 }
1107 }
1108 }
1109 if (!sessionEffects.isEmpty()) {
1110 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1111 }
1112}
1113
1114void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1115 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001116 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001117{
1118 Mutex::Autolock _l(mLock);
1119 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1120}
1121
1122void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1123 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001124 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001125{
1126 if (mType != RECORD) {
1127 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1128 // another session. This gives the priority to well behaved effect control panels
1129 // and applications not using global effects.
1130 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1131 // global effects
1132 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1133 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1134 }
1135 }
1136
1137 sp<EffectChain> chain = getEffectChain_l(sessionId);
1138 if (chain != 0) {
1139 chain->checkSuspendOnEffectEnabled(effect, enabled);
1140 }
1141}
1142
Eric Laurent4c415062016-06-17 16:14:16 -07001143// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1144status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1145 const effect_descriptor_t *desc, audio_session_t sessionId)
1146{
1147 // No global effect sessions on record threads
1148 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1149 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1150 desc->name, mThreadName);
1151 return BAD_VALUE;
1152 }
1153 // only pre processing effects on record thread
1154 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1155 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1156 desc->name, mThreadName);
1157 return BAD_VALUE;
1158 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001159
1160 // always allow effects without processing load or latency
1161 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1162 return NO_ERROR;
1163 }
1164
Eric Laurent4c415062016-06-17 16:14:16 -07001165 audio_input_flags_t flags = mInput->flags;
1166 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1167 if (flags & AUDIO_INPUT_FLAG_RAW) {
1168 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1169 desc->name, mThreadName);
1170 return BAD_VALUE;
1171 }
1172 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1173 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1174 desc->name, mThreadName);
1175 return BAD_VALUE;
1176 }
1177 }
1178 return NO_ERROR;
1179}
1180
1181// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1182status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1183 const effect_descriptor_t *desc, audio_session_t sessionId)
1184{
1185 // no preprocessing on playback threads
1186 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1187 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1188 " thread %s", desc->name, mThreadName);
1189 return BAD_VALUE;
1190 }
1191
Eric Laurent3e4de772017-07-16 16:55:08 -07001192 // always allow effects without processing load or latency
1193 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1194 return NO_ERROR;
1195 }
1196
Eric Laurent4c415062016-06-17 16:14:16 -07001197 switch (mType) {
1198 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001199#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001200 // Reject any effect on mixer multichannel sinks.
1201 // TODO: fix both format and multichannel issues with effects.
1202 if (mChannelCount != FCC_2) {
1203 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1204 " thread %s", desc->name, mChannelCount, mThreadName);
1205 return BAD_VALUE;
1206 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001207#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001208 audio_output_flags_t flags = mOutput->flags;
1209 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1210 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1211 // global effects are applied only to non fast tracks if they are SW
1212 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1213 break;
1214 }
1215 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1216 // only post processing on output stage session
1217 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1218 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1219 " on output stage session", desc->name);
1220 return BAD_VALUE;
1221 }
1222 } else {
1223 // no restriction on effects applied on non fast tracks
1224 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1225 break;
1226 }
1227 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001228
Eric Laurent4c415062016-06-17 16:14:16 -07001229 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1230 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1231 desc->name);
1232 return BAD_VALUE;
1233 }
1234 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1235 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1236 " in fast mode", desc->name);
1237 return BAD_VALUE;
1238 }
1239 }
1240 } break;
1241 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001242 // nothing actionable on offload threads, if the effect:
1243 // - is offloadable: the effect can be created
1244 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1245 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001246 break;
1247 case DIRECT:
1248 // Reject any effect on Direct output threads for now, since the format of
1249 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1250 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1251 desc->name, mThreadName);
1252 return BAD_VALUE;
1253 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001254#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001255 // Reject any effect on mixer multichannel sinks.
1256 // TODO: fix both format and multichannel issues with effects.
1257 if (mChannelCount != FCC_2) {
1258 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1259 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1260 return BAD_VALUE;
1261 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001262#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001263 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1264 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1265 " thread %s", desc->name, mThreadName);
1266 return BAD_VALUE;
1267 }
1268 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1269 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1270 " DUPLICATING thread %s", desc->name, mThreadName);
1271 return BAD_VALUE;
1272 }
1273 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1274 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1275 " DUPLICATING thread %s", desc->name, mThreadName);
1276 return BAD_VALUE;
1277 }
1278 break;
1279 default:
1280 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1281 }
1282
1283 return NO_ERROR;
1284}
1285
Eric Laurent81784c32012-11-19 14:55:58 -08001286// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1287sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1288 const sp<AudioFlinger::Client>& client,
1289 const sp<IEffectClient>& effectClient,
1290 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001291 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001292 effect_descriptor_t *desc,
1293 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001294 status_t *status,
1295 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001296{
1297 sp<EffectModule> effect;
1298 sp<EffectHandle> handle;
1299 status_t lStatus;
1300 sp<EffectChain> chain;
1301 bool chainCreated = false;
1302 bool effectCreated = false;
1303 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001304 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001305
1306 lStatus = initCheck();
1307 if (lStatus != NO_ERROR) {
1308 ALOGW("createEffect_l() Audio driver not initialized.");
1309 goto Exit;
1310 }
1311
Eric Laurent81784c32012-11-19 14:55:58 -08001312 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1313
1314 { // scope for mLock
1315 Mutex::Autolock _l(mLock);
1316
Eric Laurent4c415062016-06-17 16:14:16 -07001317 lStatus = checkEffectCompatibility_l(desc, sessionId);
1318 if (lStatus != NO_ERROR) {
1319 goto Exit;
1320 }
1321
Eric Laurent81784c32012-11-19 14:55:58 -08001322 // check for existing effect chain with the requested audio session
1323 chain = getEffectChain_l(sessionId);
1324 if (chain == 0) {
1325 // create a new chain for this session
1326 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1327 chain = new EffectChain(this, sessionId);
1328 addEffectChain_l(chain);
1329 chain->setStrategy(getStrategyForSession_l(sessionId));
1330 chainCreated = true;
1331 } else {
1332 effect = chain->getEffectFromDesc_l(desc);
1333 }
1334
1335 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1336
1337 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001338 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001339 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001340 lStatus = AudioSystem::registerEffect(
1341 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001342 if (lStatus != NO_ERROR) {
1343 goto Exit;
1344 }
1345 effectRegistered = true;
1346 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001347 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001348 if (lStatus != NO_ERROR) {
1349 goto Exit;
1350 }
1351 effectCreated = true;
1352
1353 effect->setDevice(mOutDevice);
1354 effect->setDevice(mInDevice);
1355 effect->setMode(mAudioFlinger->getMode());
1356 effect->setAudioSource(mAudioSource);
1357 }
1358 // create effect handle and connect it to effect module
1359 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001360 lStatus = handle->initCheck();
1361 if (lStatus == OK) {
1362 lStatus = effect->addHandle(handle.get());
1363 }
Eric Laurent81784c32012-11-19 14:55:58 -08001364 if (enabled != NULL) {
1365 *enabled = (int)effect->isEnabled();
1366 }
1367 }
1368
1369Exit:
1370 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1371 Mutex::Autolock _l(mLock);
1372 if (effectCreated) {
1373 chain->removeEffect_l(effect);
1374 }
1375 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001376 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001377 }
1378 if (chainCreated) {
1379 removeEffectChain_l(chain);
1380 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001381 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001382 }
1383
Glenn Kasten9156ef32013-08-06 15:39:08 -07001384 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001385 return handle;
1386}
1387
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001388void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1389 bool unpinIfLast)
1390{
1391 bool remove = false;
1392 sp<EffectModule> effect;
1393 {
1394 Mutex::Autolock _l(mLock);
1395
1396 effect = handle->effect().promote();
1397 if (effect == 0) {
1398 return;
1399 }
1400 // restore suspended effects if the disconnected handle was enabled and the last one.
1401 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1402 if (remove) {
1403 removeEffect_l(effect, true);
1404 }
1405 }
1406 if (remove) {
1407 mAudioFlinger->updateOrphanEffectChains(effect);
1408 AudioSystem::unregisterEffect(effect->id());
1409 if (handle->enabled()) {
1410 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1411 }
1412 }
1413}
1414
Glenn Kastend848eb42016-03-08 13:42:11 -08001415sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1416 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001417{
1418 Mutex::Autolock _l(mLock);
1419 return getEffect_l(sessionId, effectId);
1420}
1421
Glenn Kastend848eb42016-03-08 13:42:11 -08001422sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1423 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001424{
1425 sp<EffectChain> chain = getEffectChain_l(sessionId);
1426 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1427}
1428
1429// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1430// PlaybackThread::mLock held
1431status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1432{
1433 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001434 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001435 sp<EffectChain> chain = getEffectChain_l(sessionId);
1436 bool chainCreated = false;
1437
Eric Laurent5baf2af2013-09-12 17:37:00 -07001438 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001439 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001440 this, effect->desc().name, effect->desc().flags);
1441
Eric Laurent81784c32012-11-19 14:55:58 -08001442 if (chain == 0) {
1443 // create a new chain for this session
1444 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1445 chain = new EffectChain(this, sessionId);
1446 addEffectChain_l(chain);
1447 chain->setStrategy(getStrategyForSession_l(sessionId));
1448 chainCreated = true;
1449 }
1450 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1451
1452 if (chain->getEffectFromId_l(effect->id()) != 0) {
1453 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1454 this, effect->desc().name, chain.get());
1455 return BAD_VALUE;
1456 }
1457
Eric Laurent5baf2af2013-09-12 17:37:00 -07001458 effect->setOffloaded(mType == OFFLOAD, mId);
1459
Eric Laurent81784c32012-11-19 14:55:58 -08001460 status_t status = chain->addEffect_l(effect);
1461 if (status != NO_ERROR) {
1462 if (chainCreated) {
1463 removeEffectChain_l(chain);
1464 }
1465 return status;
1466 }
1467
1468 effect->setDevice(mOutDevice);
1469 effect->setDevice(mInDevice);
1470 effect->setMode(mAudioFlinger->getMode());
1471 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001472
Eric Laurent81784c32012-11-19 14:55:58 -08001473 return NO_ERROR;
1474}
1475
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001476void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001477
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001478 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001479 effect_descriptor_t desc = effect->desc();
1480 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1481 detachAuxEffect_l(effect->id());
1482 }
1483
1484 sp<EffectChain> chain = effect->chain().promote();
1485 if (chain != 0) {
1486 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001487 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001488 removeEffectChain_l(chain);
1489 }
1490 } else {
1491 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1492 }
1493}
1494
1495void AudioFlinger::ThreadBase::lockEffectChains_l(
1496 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1497{
1498 effectChains = mEffectChains;
1499 for (size_t i = 0; i < mEffectChains.size(); i++) {
1500 mEffectChains[i]->lock();
1501 }
1502}
1503
1504void AudioFlinger::ThreadBase::unlockEffectChains(
1505 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1506{
1507 for (size_t i = 0; i < effectChains.size(); i++) {
1508 effectChains[i]->unlock();
1509 }
1510}
1511
Glenn Kastend848eb42016-03-08 13:42:11 -08001512sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001513{
1514 Mutex::Autolock _l(mLock);
1515 return getEffectChain_l(sessionId);
1516}
1517
Glenn Kastend848eb42016-03-08 13:42:11 -08001518sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1519 const
Eric Laurent81784c32012-11-19 14:55:58 -08001520{
1521 size_t size = mEffectChains.size();
1522 for (size_t i = 0; i < size; i++) {
1523 if (mEffectChains[i]->sessionId() == sessionId) {
1524 return mEffectChains[i];
1525 }
1526 }
1527 return 0;
1528}
1529
1530void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1531{
1532 Mutex::Autolock _l(mLock);
1533 size_t size = mEffectChains.size();
1534 for (size_t i = 0; i < size; i++) {
1535 mEffectChains[i]->setMode_l(mode);
1536 }
1537}
1538
Mikhail Naganovdc769682018-05-04 15:34:08 -07001539void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001540{
1541 config->type = AUDIO_PORT_TYPE_MIX;
1542 config->ext.mix.handle = mId;
1543 config->sample_rate = mSampleRate;
1544 config->format = mFormat;
1545 config->channel_mask = mChannelMask;
1546 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1547 AUDIO_PORT_CONFIG_FORMAT;
1548}
1549
Eric Laurent72e3f392015-05-20 14:43:50 -07001550void AudioFlinger::ThreadBase::systemReady()
1551{
1552 Mutex::Autolock _l(mLock);
1553 if (mSystemReady) {
1554 return;
1555 }
1556 mSystemReady = true;
1557
1558 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1559 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1560 }
1561 mPendingConfigEvents.clear();
1562}
1563
Andy Hungdae27702016-10-31 14:01:16 -07001564template <typename T>
1565ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1566 ssize_t index = mActiveTracks.indexOf(track);
1567 if (index >= 0) {
1568 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1569 return index;
1570 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001571 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001572 mActiveTracksGeneration++;
1573 mLatestActiveTrack = track;
1574 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001575 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001576 return mActiveTracks.add(track);
1577}
1578
1579template <typename T>
1580ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1581 ssize_t index = mActiveTracks.remove(track);
1582 if (index < 0) {
1583 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1584 return index;
1585 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001586 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001587 mActiveTracksGeneration++;
1588 --mBatteryCounter[track->uid()].second;
1589 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001590 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001591#ifdef TEE_SINK
1592 track->dumpTee(-1 /* fd */, "_REMOVE");
1593#endif
Andy Hungdae27702016-10-31 14:01:16 -07001594 return index;
1595}
1596
1597template <typename T>
1598void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1599 for (const sp<T> &track : mActiveTracks) {
1600 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001601 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001602 }
1603 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001604 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001605 mActiveTracks.clear();
1606 mLatestActiveTrack.clear();
1607 mBatteryCounter.clear();
1608}
1609
1610template <typename T>
1611void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1612 sp<ThreadBase> thread, bool force) {
1613 // Updates ActiveTracks client uids to the thread wakelock.
1614 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1615 thread->updateWakeLockUids_l(getWakeLockUids());
1616 mLastActiveTracksGeneration = mActiveTracksGeneration;
1617 }
1618
1619 // Updates BatteryNotifier uids
1620 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1621 const uid_t uid = it->first;
1622 ssize_t &previous = it->second.first;
1623 ssize_t &current = it->second.second;
1624 if (current > 0) {
1625 if (previous == 0) {
1626 BatteryNotifier::getInstance().noteStartAudio(uid);
1627 }
1628 previous = current;
1629 ++it;
1630 } else if (current == 0) {
1631 if (previous > 0) {
1632 BatteryNotifier::getInstance().noteStopAudio(uid);
1633 }
1634 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1635 } else /* (current < 0) */ {
1636 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1637 }
1638 }
1639}
Eric Laurent83b88082014-06-20 18:31:16 -07001640
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001641template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001642bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1643 const bool hasChanged = mHasChanged;
1644 mHasChanged = false;
1645 return hasChanged;
1646}
1647
1648template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001649void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1650 const char *funcName, const sp<T> &track) const {
1651 if (mLocalLog != nullptr) {
1652 String8 result;
1653 track->appendDump(result, false /* active */);
1654 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1655 }
1656}
1657
Eric Laurent6acd1d42017-01-04 14:23:29 -08001658void AudioFlinger::ThreadBase::broadcast_l()
1659{
1660 // Thread could be blocked waiting for async
1661 // so signal it to handle state changes immediately
1662 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1663 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1664 mSignalPending = true;
1665 mWaitWorkCV.broadcast();
1666}
1667
Eric Laurent81784c32012-11-19 14:55:58 -08001668// ----------------------------------------------------------------------------
1669// Playback
1670// ----------------------------------------------------------------------------
1671
1672AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1673 AudioStreamOut* output,
1674 audio_io_handle_t id,
1675 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001676 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001677 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001678 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001679 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001680 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001681 mMixerBuffer(NULL),
1682 mMixerBufferSize(0),
1683 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1684 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001685 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001686 mEffectBuffer(NULL),
1687 mEffectBufferSize(0),
1688 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1689 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001690 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001691 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001692 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001693 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001694 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001695 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001696 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001697 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001698 mMixerStatus(MIXER_IDLE),
1699 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001700 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001701 mBytesRemaining(0),
1702 mCurrentWriteLength(0),
1703 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001704 mWriteAckSequence(0),
1705 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001706 mScreenState(AudioFlinger::mScreenState),
1707 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001708 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001709 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1710 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001711{
Glenn Kastend7dca052015-03-05 16:05:54 -08001712 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1713 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001714
1715 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1716 // it would be safer to explicitly pass initial masterVolume/masterMute as
1717 // parameter.
1718 //
1719 // If the HAL we are using has support for master volume or master mute,
1720 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1721 // and the mute set to false).
1722 mMasterVolume = audioFlinger->masterVolume_l();
1723 mMasterMute = audioFlinger->masterMute_l();
1724 if (mOutput && mOutput->audioHwDev) {
1725 if (mOutput->audioHwDev->canSetMasterVolume()) {
1726 mMasterVolume = 1.0;
1727 }
1728
1729 if (mOutput->audioHwDev->canSetMasterMute()) {
1730 mMasterMute = false;
1731 }
1732 }
1733
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001734 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001735
Eric Laurent223fd5c2014-11-11 13:43:36 -08001736 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001737 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001738 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001739 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001740 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1741 }
Eric Laurent98e38192018-02-15 18:31:53 -08001742 // Audio patch volume is always max
1743 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1744 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001745}
1746
1747AudioFlinger::PlaybackThread::~PlaybackThread()
1748{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001749 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001750 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001751 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001752 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001753}
1754
1755void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1756{
1757 dumpInternals(fd, args);
1758 dumpTracks(fd, args);
1759 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001760 dprintf(fd, " Local log:\n");
1761 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001762}
1763
Glenn Kasten0f11b512014-01-31 16:18:54 -08001764void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001765{
Eric Laurent81784c32012-11-19 14:55:58 -08001766 String8 result;
1767
Marco Nelissenb2208842014-02-07 14:00:50 -08001768 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001769 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1770 const stream_type_t *st = &mStreamTypes[i];
1771 if (i > 0) {
1772 result.appendFormat(", ");
1773 }
1774 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1775 if (st->mute) {
1776 result.append("M");
1777 }
1778 }
1779 result.append("\n");
1780 write(fd, result.string(), result.length());
1781 result.clear();
1782
Eric Laurent81784c32012-11-19 14:55:58 -08001783 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1784 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001785 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001786 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001787
1788 size_t numtracks = mTracks.size();
1789 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001790 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001791 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001792 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001793 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001794 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001795 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001796 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001797 for (size_t i = 0; i < numtracks; ++i) {
1798 sp<Track> track = mTracks[i];
1799 if (track != 0) {
1800 bool active = mActiveTracks.indexOf(track) >= 0;
1801 if (active) {
1802 numactiveseen++;
1803 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001804 result.append(prefix);
1805 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001806 }
1807 }
1808 } else {
1809 result.append("\n");
1810 }
1811 if (numactiveseen != numactive) {
1812 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001814 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001815 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001816 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001817 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001818 sp<Track> track = mActiveTracks[i];
1819 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001820 result.append(prefix);
1821 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001822 }
1823 }
1824 }
1825
1826 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001827}
1828
1829void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1830{
Glenn Kasten44182c22015-03-05 17:12:23 -08001831 dumpBase(fd, args);
1832
Elliott Hughes87cebad2014-05-22 10:14:43 -07001833 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001834 dprintf(fd, " Last write occurred (msecs): %llu\n",
1835 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001836 dprintf(fd, " Total writes: %d\n", mNumWrites);
1837 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1838 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1839 dprintf(fd, " Suspend count: %d\n", mSuspended);
1840 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1841 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1842 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1843 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001844 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001845 AudioStreamOut *output = mOutput;
1846 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001847 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1848 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001849 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1850 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1851 if (mPipeSink.get() != nullptr) {
1852 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1853 }
1854 if (output != nullptr) {
1855 dprintf(fd, " Hal stream dump:\n");
1856 (void)output->stream->dump(fd);
1857 }
Eric Laurent81784c32012-11-19 14:55:58 -08001858}
1859
1860// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001861
1862void AudioFlinger::PlaybackThread::onFirstRef()
1863{
Glenn Kastend7dca052015-03-05 16:05:54 -08001864 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001865}
1866
1867// ThreadBase virtuals
1868void AudioFlinger::PlaybackThread::preExit()
1869{
1870 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001871 // FIXME this is using hard-coded strings but in the future, this functionality will be
1872 // converted to use audio HAL extensions required to support tunneling
1873 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1874 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001875}
1876
1877// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1878sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1879 const sp<AudioFlinger::Client>& client,
1880 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001881 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001882 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001883 audio_format_t format,
1884 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001885 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001886 size_t *pNotificationFrameCount,
1887 uint32_t notificationsPerBuffer,
1888 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001889 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001890 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001891 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001892 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001893 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001894 status_t *status,
1895 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001896{
Glenn Kasten74935e42013-12-19 08:56:45 -08001897 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001898 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001899 sp<Track> track;
1900 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001901 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001902 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001903 uint32_t sampleRate;
1904
1905 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1906 lStatus = BAD_VALUE;
1907 goto Exit;
1908 }
Eric Laurent21da6472017-11-09 16:29:26 -08001909
1910 if (*pSampleRate == 0) {
1911 *pSampleRate = mSampleRate;
1912 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001913 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001914
1915 // special case for FAST flag considered OK if fast mixer is present
1916 if (hasFastMixer()) {
1917 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1918 }
1919
1920 // Check if requested flags are compatible with output stream flags
1921 if ((*flags & outputFlags) != *flags) {
1922 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1923 *flags, outputFlags);
1924 *flags = (audio_output_flags_t)(*flags & outputFlags);
1925 }
Eric Laurent81784c32012-11-19 14:55:58 -08001926
Eric Laurent81784c32012-11-19 14:55:58 -08001927 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001928 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001929 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001930 // PCM data
1931 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001932 // TODO: extract as a data library function that checks that a computationally
1933 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001934 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001935 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1936 (channelMask == AUDIO_CHANNEL_OUT_MONO
1937 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001938 // hardware sample rate
1939 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001940 // normal mixer has an associated fast mixer
1941 hasFastMixer() &&
1942 // there are sufficient fast track slots available
1943 (mFastTrackAvailMask != 0)
1944 // FIXME test that MixerThread for this fast track has a capable output HAL
1945 // FIXME add a permission test also?
1946 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001947 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1948 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001949 // read the fast track multiplier property the first time it is needed
1950 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1951 if (ok != 0) {
1952 ALOGE("%s pthread_once failed: %d", __func__, ok);
1953 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001954 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001955 }
Eric Laurent4c415062016-06-17 16:14:16 -07001956
1957 // check compatibility with audio effects.
1958 { // scope for mLock
1959 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001960 for (audio_session_t session : {
1961 AUDIO_SESSION_OUTPUT_STAGE,
1962 AUDIO_SESSION_OUTPUT_MIX,
1963 sessionId,
1964 }) {
1965 sp<EffectChain> chain = getEffectChain_l(session);
1966 if (chain.get() != nullptr) {
1967 audio_output_flags_t old = *flags;
1968 chain->checkOutputFlagCompatibility(flags);
1969 if (old != *flags) {
1970 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1971 (int)session, (int)old, (int)*flags);
1972 }
Eric Laurent4c415062016-06-17 16:14:16 -07001973 }
1974 }
1975 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001976 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001977 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1978 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001979 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001980 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1981 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001982 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001983 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001984 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001985 audio_is_linear_pcm(format),
1986 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001987 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001988 }
1989 }
Eric Laurent21da6472017-11-09 16:29:26 -08001990
1991 if (!audio_has_proportional_frames(format)) {
1992 if (sharedBuffer != 0) {
1993 // Same comment as below about ignoring frameCount parameter for set()
1994 frameCount = sharedBuffer->size();
1995 } else if (frameCount == 0) {
1996 frameCount = mNormalFrameCount;
1997 }
1998 if (notificationFrameCount != frameCount) {
1999 notificationFrameCount = frameCount;
2000 }
2001 } else if (sharedBuffer != 0) {
2002 // FIXME: Ensure client side memory buffers need
2003 // not have additional alignment beyond sample
2004 // (e.g. 16 bit stereo accessed as 32 bit frame).
2005 size_t alignment = audio_bytes_per_sample(format);
2006 if (alignment & 1) {
2007 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2008 alignment = 1;
2009 }
2010 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2011 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2012 if (channelCount > 1) {
2013 // More than 2 channels does not require stronger alignment than stereo
2014 alignment <<= 1;
2015 }
2016 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2017 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2018 sharedBuffer->pointer(), channelCount);
2019 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002020 goto Exit;
2021 }
Eric Laurent21da6472017-11-09 16:29:26 -08002022
2023 // When initializing a shared buffer AudioTrack via constructors,
2024 // there's no frameCount parameter.
2025 // But when initializing a shared buffer AudioTrack via set(),
2026 // there _is_ a frameCount parameter. We silently ignore it.
2027 frameCount = sharedBuffer->size() / frameSize;
2028 } else {
2029 size_t minFrameCount = 0;
2030 // For fast tracks we try to respect the application's request for notifications per buffer.
2031 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2032 if (notificationsPerBuffer > 0) {
2033 // Avoid possible arithmetic overflow during multiplication.
2034 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2035 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2036 notificationsPerBuffer, mFrameCount);
2037 } else {
2038 minFrameCount = mFrameCount * notificationsPerBuffer;
2039 }
2040 }
2041 } else {
2042 // For normal PCM streaming tracks, update minimum frame count.
2043 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2044 // cover audio hardware latency.
2045 // This is probably too conservative, but legacy application code may depend on it.
2046 // If you change this calculation, also review the start threshold which is related.
2047 uint32_t latencyMs = latency_l();
2048 if (latencyMs == 0) {
2049 ALOGE("Error when retrieving output stream latency");
2050 lStatus = UNKNOWN_ERROR;
2051 goto Exit;
2052 }
2053
2054 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2055 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2056
Eric Laurent81784c32012-11-19 14:55:58 -08002057 }
Eric Laurent21da6472017-11-09 16:29:26 -08002058 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002059 frameCount = minFrameCount;
2060 }
Eric Laurent81784c32012-11-19 14:55:58 -08002061 }
Eric Laurent21da6472017-11-09 16:29:26 -08002062
2063 // Make sure that application is notified with sufficient margin before underrun.
2064 // The client can divide the AudioTrack buffer into sub-buffers,
2065 // and expresses its desire to server as the notification frame count.
2066 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2067 size_t maxNotificationFrames;
2068 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2069 // notify every HAL buffer, regardless of the size of the track buffer
2070 maxNotificationFrames = mFrameCount;
2071 } else {
2072 // For normal tracks, use at least double-buffering if no sample rate conversion,
2073 // or at least triple-buffering if there is sample rate conversion
2074 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2075 maxNotificationFrames = frameCount / nBuffering;
2076 // If client requested a fast track but this was denied, then use the smaller maximum.
2077 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2078 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2079 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2080 maxNotificationFrames = maxNotificationFramesFastDenied;
2081 }
2082 }
2083 }
2084 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2085 if (notificationFrameCount == 0) {
2086 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2087 maxNotificationFrames, frameCount);
2088 } else {
2089 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2090 notificationFrameCount, maxNotificationFrames, frameCount);
2091 }
2092 notificationFrameCount = maxNotificationFrames;
2093 }
2094 }
2095
Glenn Kasten74935e42013-12-19 08:56:45 -08002096 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002097 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002098
Glenn Kastenc3df8382014-03-13 15:05:25 -07002099 switch (mType) {
2100
2101 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002102 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002103 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002104 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2105 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002106 sampleRate, format, channelMask, mOutput, mFormat);
2107 lStatus = BAD_VALUE;
2108 goto Exit;
2109 }
2110 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002111 break;
2112
2113 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002114 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002115 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2116 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002117 sampleRate, format, channelMask, mOutput, mFormat);
2118 lStatus = BAD_VALUE;
2119 goto Exit;
2120 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002121 break;
2122
2123 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002124 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002125 ALOGE("createTrack_l() Bad parameter: format %#x \""
2126 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002127 format, mOutput, mFormat);
2128 lStatus = BAD_VALUE;
2129 goto Exit;
2130 }
Andy Hungcd044842014-08-07 11:04:34 -07002131 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002132 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2133 lStatus = BAD_VALUE;
2134 goto Exit;
2135 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002136 break;
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138 }
2139
2140 lStatus = initCheck();
2141 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002142 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002143 goto Exit;
2144 }
2145
2146 { // scope for mLock
2147 Mutex::Autolock _l(mLock);
2148
2149 // all tracks in same audio session must share the same routing strategy otherwise
2150 // conflicts will happen when tracks are moved from one output to another by audio policy
2151 // manager
2152 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2153 for (size_t i = 0; i < mTracks.size(); ++i) {
2154 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002155 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002156 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2157 if (sessionId == t->sessionId() && strategy != actual) {
2158 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2159 strategy, actual);
2160 lStatus = BAD_VALUE;
2161 goto Exit;
2162 }
2163 }
2164 }
2165
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002166 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002167 channelMask, frameCount,
2168 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002169 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002170
Glenn Kasten03003332013-08-06 15:40:54 -07002171 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2172 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002173 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002174 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002175 goto Exit;
2176 }
2177 mTracks.add(track);
2178
2179 sp<EffectChain> chain = getEffectChain_l(sessionId);
2180 if (chain != 0) {
2181 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2182 track->setMainBuffer(chain->inBuffer());
2183 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2184 chain->incTrackCnt();
2185 }
2186
Eric Laurent05067782016-06-01 18:27:28 -07002187 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002188 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2189 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2190 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002191 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002192 }
2193 }
2194
2195 lStatus = NO_ERROR;
2196
2197Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002198 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002199 return track;
2200}
2201
Andy Hung1bc088a2018-02-09 15:57:31 -08002202template<typename T>
2203ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2204{
2205 const ssize_t index = mTracks.add(track);
2206 if (index >= 0) {
2207 // set name for track when adding.
2208 int name;
2209 if (mUnusedTrackNames.empty()) {
2210 name = mTracks.size() - 1; // new name {0 ... size-1}.
2211 } else {
2212 // reuse smallest name for deleted track.
2213 auto it = mUnusedTrackNames.begin();
2214 name = *it;
2215 (void)mUnusedTrackNames.erase(it);
2216 }
2217 track->setName(name);
2218 } else {
2219 LOG_ALWAYS_FATAL("cannot add track");
2220 }
2221 return index;
2222}
2223
2224template<typename T>
2225ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2226{
2227 const int name = track->name();
2228 const ssize_t index = mTracks.remove(track);
2229 if (index >= 0) {
2230 // invalidate name when removing from mTracks.
2231 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2232
2233 if (mSaveDeletedTrackNames) {
2234 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2235 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2236 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2237 mDeletedTrackNames.emplace(name);
2238 }
2239
2240 mUnusedTrackNames.emplace(name);
2241 track->setName(T::TRACK_NAME_PENDING);
2242 } else {
2243 LOG_ALWAYS_FATAL_IF(name >= 0,
2244 "valid name %d for track not in mTracks (returned %zd)", name, index);
2245 }
2246 return index;
2247}
2248
Eric Laurent81784c32012-11-19 14:55:58 -08002249uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2250{
2251 return latency;
2252}
2253
2254uint32_t AudioFlinger::PlaybackThread::latency() const
2255{
2256 Mutex::Autolock _l(mLock);
2257 return latency_l();
2258}
2259uint32_t AudioFlinger::PlaybackThread::latency_l() const
2260{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002261 uint32_t latency;
2262 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2263 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002264 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002265 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002266}
2267
2268void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2269{
2270 Mutex::Autolock _l(mLock);
2271 // Don't apply master volume in SW if our HAL can do it for us.
2272 if (mOutput && mOutput->audioHwDev &&
2273 mOutput->audioHwDev->canSetMasterVolume()) {
2274 mMasterVolume = 1.0;
2275 } else {
2276 mMasterVolume = value;
2277 }
2278}
2279
2280void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2281{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002282 if (isDuplicating()) {
2283 return;
2284 }
Eric Laurent81784c32012-11-19 14:55:58 -08002285 Mutex::Autolock _l(mLock);
2286 // Don't apply master mute in SW if our HAL can do it for us.
2287 if (mOutput && mOutput->audioHwDev &&
2288 mOutput->audioHwDev->canSetMasterMute()) {
2289 mMasterMute = false;
2290 } else {
2291 mMasterMute = muted;
2292 }
2293}
2294
2295void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2296{
2297 Mutex::Autolock _l(mLock);
2298 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002299 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002300}
2301
2302void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2303{
2304 Mutex::Autolock _l(mLock);
2305 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002306 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002307}
2308
2309float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2310{
2311 Mutex::Autolock _l(mLock);
2312 return mStreamTypes[stream].volume;
2313}
2314
2315// addTrack_l() must be called with ThreadBase::mLock held
2316status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2317{
2318 status_t status = ALREADY_EXISTS;
2319
Eric Laurent81784c32012-11-19 14:55:58 -08002320 if (mActiveTracks.indexOf(track) < 0) {
2321 // the track is newly added, make sure it fills up all its
2322 // buffers before playing. This is to ensure the client will
2323 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002324 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002325 TrackBase::track_state state = track->mState;
2326 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002327 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002328 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002329 mLock.lock();
2330 // abort track was stopped/paused while we released the lock
2331 if (state != track->mState) {
2332 if (status == NO_ERROR) {
2333 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002334 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002335 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002336 mLock.lock();
2337 }
2338 return INVALID_OPERATION;
2339 }
2340 // abort if start is rejected by audio policy manager
2341 if (status != NO_ERROR) {
2342 return PERMISSION_DENIED;
2343 }
2344#ifdef ADD_BATTERY_DATA
2345 // to track the speaker usage
2346 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2347#endif
2348 }
2349
Eric Laurent51716182016-02-29 18:00:56 -08002350 // set retry count for buffer fill
2351 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002352 if (track->isStopping_1()) {
2353 track->mRetryCount = kMaxTrackStopRetriesOffload;
2354 } else {
2355 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2356 }
2357 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002358 } else {
2359 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002360 track->mFillingUpStatus =
2361 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002362 }
2363
Eric Laurent81784c32012-11-19 14:55:58 -08002364 track->mResetDone = false;
2365 track->mPresentationCompleteFrames = 0;
2366 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002367 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2368 if (chain != 0) {
2369 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2370 track->sessionId());
2371 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002372 }
2373
2374 status = NO_ERROR;
2375 }
2376
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002377 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002378 return status;
2379}
2380
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002382{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002384 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002385 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2386 track->mState = TrackBase::STOPPED;
2387 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002388 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002389 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002391 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002392
2393 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002394}
2395
2396void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2397{
2398 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002399
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002400 String8 result;
2401 track->appendDump(result, false /* active */);
2402 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002403
Eric Laurent81784c32012-11-19 14:55:58 -08002404 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002405 if (track->isFastTrack()) {
2406 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002407 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002408 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2409 mFastTrackAvailMask |= 1 << index;
2410 // redundant as track is about to be destroyed, for dumpsys only
2411 track->mFastIndex = -1;
2412 }
2413 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2414 if (chain != 0) {
2415 chain->decTrackCnt();
2416 }
2417}
2418
2419String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2420{
Eric Laurent81784c32012-11-19 14:55:58 -08002421 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002422 String8 out_s8;
2423 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2424 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002425 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002426 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002427}
2428
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002429void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002430 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2431 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002432
Eric Laurent73e26b62015-04-27 16:55:58 -07002433 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002434
2435 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002436 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002437 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002438 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002439 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002440 desc->mChannelMask = mChannelMask;
2441 desc->mSamplingRate = mSampleRate;
2442 desc->mFormat = mFormat;
2443 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002444 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002445 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002446 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002447 break;
2448
Eric Laurent73e26b62015-04-27 16:55:58 -07002449 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002450 default:
2451 break;
2452 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002453 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002454}
2455
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002456void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002458 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459}
2460
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002461void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002463 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464}
2465
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002466void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002467{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002468 mCallbackThread->setAsyncError();
2469}
2470
Eric Laurent3b4529e2013-09-05 18:09:19 -07002471void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472{
2473 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002474 // reject out of sequence requests
2475 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2476 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477 mWaitWorkCV.signal();
2478 }
2479}
2480
Eric Laurent3b4529e2013-09-05 18:09:19 -07002481void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002482{
2483 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002484 // reject out of sequence requests
2485 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002486 // Register discontinuity when HW drain is completed because that can cause
2487 // the timestamp frame position to reset to 0 for direct and offload threads.
2488 // (Out of sequence requests are ignored, since the discontinuity would be handled
2489 // elsewhere, e.g. in flush).
2490 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002491 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492 mWaitWorkCV.signal();
2493 }
2494}
2495
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002496void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002497{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002498 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002499 mSampleRate = mOutput->getSampleRate();
2500 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002501 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002502 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002503 }
Andy Hung9a592762014-07-21 21:56:01 -07002504 if ((mType == MIXER || mType == DUPLICATING)
2505 && !isValidPcmSinkChannelMask(mChannelMask)) {
2506 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2507 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002508 }
Andy Hunge5412692014-05-16 11:25:07 -07002509 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002510
2511 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002512 status_t result = mOutput->stream->getFormat(&mHALFormat);
2513 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002514 // Get format from the shim, which will be different than the HAL format
2515 // if playing compressed audio over HDMI passthrough.
2516 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002517 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002518 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002519 }
Andy Hung6146c082014-03-18 11:56:15 -07002520 if ((mType == MIXER || mType == DUPLICATING)
2521 && !isValidPcmSinkFormat(mFormat)) {
2522 LOG_FATAL("HAL format %#x not supported for mixed output",
2523 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002524 }
Phil Burk062e67a2015-02-11 13:40:50 -08002525 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002526 result = mOutput->stream->getBufferSize(&mBufferSize);
2527 LOG_ALWAYS_FATAL_IF(result != OK,
2528 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002529 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002530 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002531 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002532 mFrameCount);
2533 }
2534
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002535 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2536 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002538 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002539 }
2540 }
2541
Eric Laurentd1f69b02014-12-15 14:33:13 -08002542 mHwSupportsPause = false;
2543 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002544 bool supportsPause = false, supportsResume = false;
2545 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2546 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002547 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002548 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002549 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002550 } else if (supportsResume) {
2551 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002552 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002553 }
2554 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002555 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2556 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2557 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002558
Andy Hungfbfc3952015-01-15 13:33:51 -08002559 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2560 // For best precision, we use float instead of the associated output
2561 // device format (typically PCM 16 bit).
2562
2563 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2564 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2565 mBufferSize = mFrameSize * mFrameCount;
2566
2567 // TODO: We currently use the associated output device channel mask and sample rate.
2568 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2569 // (if a valid mask) to avoid premature downmix.
2570 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2571 // instead of the output device sample rate to avoid loss of high frequency information.
2572 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2573 }
2574
Andy Hung09a50072014-02-27 14:30:47 -08002575 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002576 double multiplier = 1.0;
2577 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2578 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002579 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2580 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002581
Eric Laurent81784c32012-11-19 14:55:58 -08002582 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2583 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2584 maxNormalFrameCount = maxNormalFrameCount & ~15;
2585 if (maxNormalFrameCount < minNormalFrameCount) {
2586 maxNormalFrameCount = minNormalFrameCount;
2587 }
2588 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2589 if (multiplier <= 1.0) {
2590 multiplier = 1.0;
2591 } else if (multiplier <= 2.0) {
2592 if (2 * mFrameCount <= maxNormalFrameCount) {
2593 multiplier = 2.0;
2594 } else {
2595 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2596 }
2597 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002598 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002599 }
2600 }
2601 mNormalFrameCount = multiplier * mFrameCount;
2602 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002603 if (mType == MIXER || mType == DUPLICATING) {
2604 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2605 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002606 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002607 mNormalFrameCount);
2608
Andy Hung08fb1742015-05-31 23:22:10 -07002609 // Check if we want to throttle the processing to no more than 2x normal rate
2610 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002611 mThreadThrottleTimeMs = 0;
2612 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002613 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2614
Andy Hung010a1a12014-03-13 13:57:33 -07002615 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2616 // Originally this was int16_t[] array, need to remove legacy implications.
2617 free(mSinkBuffer);
2618 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002619 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2620 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2621 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002622 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002623
Andy Hung69aed5f2014-02-25 17:24:40 -08002624 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2625 // drives the output.
2626 free(mMixerBuffer);
2627 mMixerBuffer = NULL;
2628 if (mMixerBufferEnabled) {
2629 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2630 mMixerBufferSize = mNormalFrameCount * mChannelCount
2631 * audio_bytes_per_sample(mMixerBufferFormat);
2632 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2633 }
Andy Hung98ef9782014-03-04 14:46:50 -08002634 free(mEffectBuffer);
2635 mEffectBuffer = NULL;
2636 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002637 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002638 mEffectBufferSize = mNormalFrameCount * mChannelCount
2639 * audio_bytes_per_sample(mEffectBufferFormat);
2640 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2641 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002642
Eric Laurent81784c32012-11-19 14:55:58 -08002643 // force reconfiguration of effect chains and engines to take new buffer size and audio
2644 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002645 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002646 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2647 // matter.
2648 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2649 Vector< sp<EffectChain> > effectChains = mEffectChains;
2650 for (size_t i = 0; i < effectChains.size(); i ++) {
2651 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2652 }
2653}
2654
Kevin Rocard069c2712018-03-29 19:09:14 -07002655void AudioFlinger::PlaybackThread::updateMetadata_l()
2656{
Kevin Rocard12381092018-04-11 09:19:59 -07002657 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2658 return; // That should not happen
2659 }
2660 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2661 for (const sp<Track> &track : mActiveTracks) {
2662 // Do not short-circuit as all hasChanged states must be reset
2663 // as all the metadata are going to be sent
2664 hasChanged |= track->readAndClearHasChanged();
2665 }
2666 if (!hasChanged) {
2667 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002668 }
2669 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002670 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002671 for (const sp<Track> &track : mActiveTracks) {
2672 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002673 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002674 }
Kevin Rocard12381092018-04-11 09:19:59 -07002675 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002676}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002677
Kevin Rocard12381092018-04-11 09:19:59 -07002678void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2679 const StreamOutHalInterface::SourceMetadata& metadata)
2680{
2681 mOutput->stream->updateSourceMetadata(metadata);
2682};
2683
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002684status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002685{
2686 if (halFrames == NULL || dspFrames == NULL) {
2687 return BAD_VALUE;
2688 }
2689 Mutex::Autolock _l(mLock);
2690 if (initCheck() != NO_ERROR) {
2691 return INVALID_OPERATION;
2692 }
Andy Hung818e7a32016-02-16 18:08:07 -08002693 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002694 *halFrames = framesWritten;
2695
2696 if (isSuspended()) {
2697 // return an estimation of rendered frames when the output is suspended
2698 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002699 *dspFrames = (uint32_t)
2700 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002701 return NO_ERROR;
2702 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002703 status_t status;
2704 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002705 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002706 *dspFrames = (size_t)frames;
2707 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002708 }
2709}
2710
Eric Laurent4c415062016-06-17 16:14:16 -07002711// hasAudioSession_l() must be called with ThreadBase::mLock held
2712uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002713{
Eric Laurent81784c32012-11-19 14:55:58 -08002714 uint32_t result = 0;
2715 if (getEffectChain_l(sessionId) != 0) {
2716 result = EFFECT_SESSION;
2717 }
2718
2719 for (size_t i = 0; i < mTracks.size(); ++i) {
2720 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002721 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002722 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002723 if (track->isFastTrack()) {
2724 result |= FAST_SESSION;
2725 }
Eric Laurent81784c32012-11-19 14:55:58 -08002726 break;
2727 }
2728 }
2729
2730 return result;
2731}
2732
Glenn Kastend848eb42016-03-08 13:42:11 -08002733uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002734{
2735 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2736 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2737 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2738 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2739 }
2740 for (size_t i = 0; i < mTracks.size(); i++) {
2741 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002742 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002743 return AudioSystem::getStrategyForStream(track->streamType());
2744 }
2745 }
2746 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2747}
2748
2749
Phil Burk062e67a2015-02-11 13:40:50 -08002750AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002751{
2752 Mutex::Autolock _l(mLock);
2753 return mOutput;
2754}
2755
Phil Burk062e67a2015-02-11 13:40:50 -08002756AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002757{
2758 Mutex::Autolock _l(mLock);
2759 AudioStreamOut *output = mOutput;
2760 mOutput = NULL;
2761 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2762 // must push a NULL and wait for ack
2763 mOutputSink.clear();
2764 mPipeSink.clear();
2765 mNormalSink.clear();
2766 return output;
2767}
2768
2769// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002770sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002771{
2772 if (mOutput == NULL) {
2773 return NULL;
2774 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002775 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002776}
2777
2778uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2779{
2780 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2781}
2782
2783status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2784{
2785 if (!isValidSyncEvent(event)) {
2786 return BAD_VALUE;
2787 }
2788
2789 Mutex::Autolock _l(mLock);
2790
2791 for (size_t i = 0; i < mTracks.size(); ++i) {
2792 sp<Track> track = mTracks[i];
2793 if (event->triggerSession() == track->sessionId()) {
2794 (void) track->setSyncEvent(event);
2795 return NO_ERROR;
2796 }
2797 }
2798
2799 return NAME_NOT_FOUND;
2800}
2801
2802bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2803{
2804 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2805}
2806
2807void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2808 const Vector< sp<Track> >& tracksToRemove)
2809{
2810 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002811 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002812 for (size_t i = 0 ; i < count ; i++) {
2813 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002814 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002815 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002816 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002817#ifdef ADD_BATTERY_DATA
2818 // to track the speaker usage
2819 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2820#endif
2821 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002822 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002823 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002824 }
Eric Laurent81784c32012-11-19 14:55:58 -08002825 }
2826 }
2827 }
Eric Laurent81784c32012-11-19 14:55:58 -08002828}
2829
2830void AudioFlinger::PlaybackThread::checkSilentMode_l()
2831{
2832 if (!mMasterMute) {
2833 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002834 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2835 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2836 return;
2837 }
Eric Laurent81784c32012-11-19 14:55:58 -08002838 if (property_get("ro.audio.silent", value, "0") > 0) {
2839 char *endptr;
2840 unsigned long ul = strtoul(value, &endptr, 0);
2841 if (*endptr == '\0' && ul != 0) {
2842 ALOGD("Silence is golden");
2843 // The setprop command will not allow a property to be changed after
2844 // the first time it is set, so we don't have to worry about un-muting.
2845 setMasterMute_l(true);
2846 }
2847 }
2848 }
2849}
2850
2851// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002852ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002853{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002854 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002855 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002857 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002858
2859 // If an NBAIO sink is present, use it to write the normal mixer's submix
2860 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002861
Andy Hung010a1a12014-03-13 13:57:33 -07002862 const size_t count = mBytesRemaining / mFrameSize;
2863
Simon Wilson2d590962012-11-29 15:18:50 -08002864 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002865 // update the setpoint when AudioFlinger::mScreenState changes
2866 uint32_t screenState = AudioFlinger::mScreenState;
2867 if (screenState != mScreenState) {
2868 mScreenState = screenState;
2869 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2870 if (pipe != NULL) {
2871 pipe->setAvgFrames((mScreenState & 1) ?
2872 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2873 }
2874 }
Andy Hung010a1a12014-03-13 13:57:33 -07002875 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002876 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002877 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002878 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002879#ifdef TEE_SINK
2880 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2881#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002882 } else {
2883 bytesWritten = framesWritten;
2884 }
2885 // otherwise use the HAL / AudioStreamOut directly
2886 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002888
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002890 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2891 mWriteAckSequence += 2;
2892 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002894 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002895 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002896 // FIXME We should have an implementation of timestamps for direct output threads.
2897 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002898 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002899
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 if (mUseAsyncWrite &&
2901 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2902 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002903 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002905 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002906 }
Eric Laurent81784c32012-11-19 14:55:58 -08002907 }
2908
Eric Laurent81784c32012-11-19 14:55:58 -08002909 mNumWrites++;
2910 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002911 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002912 return bytesWritten;
2913}
2914
2915void AudioFlinger::PlaybackThread::threadLoop_drain()
2916{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002917 bool supportsDrain = false;
2918 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2920 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002921 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2922 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002924 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002926 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002927 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928 }
2929}
2930
2931void AudioFlinger::PlaybackThread::threadLoop_exit()
2932{
Eric Laurent275e8e92014-11-30 15:14:47 -08002933 {
2934 Mutex::Autolock _l(mLock);
2935 for (size_t i = 0; i < mTracks.size(); i++) {
2936 sp<Track> track = mTracks[i];
2937 track->invalidate();
2938 }
Andy Hungdae27702016-10-31 14:01:16 -07002939 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2940 // After we exit there are no more track changes sent to BatteryNotifier
2941 // because that requires an active threadLoop.
2942 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2943 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002944 }
Eric Laurent81784c32012-11-19 14:55:58 -08002945}
2946
2947/*
2948The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002949 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002950 - mActiveSleepTimeUs from activeSleepTimeUs()
2951 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002952 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2953 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002954 - maxPeriod from frame count and sample rate (MIXER only)
2955
2956The parameters that affect these derived values are:
2957 - frame count
2958 - frame size
2959 - sample rate
2960 - device type: A2DP or not
2961 - device latency
2962 - format: PCM or not
2963 - active sleep time
2964 - idle sleep time
2965*/
2966
2967void AudioFlinger::PlaybackThread::cacheParameters_l()
2968{
Andy Hung25c2dac2014-02-27 14:56:00 -08002969 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002970 mActiveSleepTimeUs = activeSleepTimeUs();
2971 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002972
2973 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2974 // truncating audio when going to standby.
2975 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2976 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2977 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2978 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2979 }
2980 }
Eric Laurent81784c32012-11-19 14:55:58 -08002981}
2982
Eric Laurent13084622016-05-17 10:51:49 -07002983bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002984{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002985 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002986 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002987 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002988 size_t size = mTracks.size();
2989 for (size_t i = 0; i < size; i++) {
2990 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002991 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002992 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002993 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002994 }
2995 }
Eric Laurent13084622016-05-17 10:51:49 -07002996 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002997}
2998
Haynes Mathew George05317d22016-05-03 16:34:26 -07002999void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3000{
3001 Mutex::Autolock _l(mLock);
3002 invalidateTracks_l(streamType);
3003}
3004
Eric Laurent81784c32012-11-19 14:55:58 -08003005status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3006{
Glenn Kastend848eb42016-03-08 13:42:11 -08003007 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003008 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003009 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003010 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3011 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3012 &halInBuffer);
3013 if (result != OK) return result;
3014 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003015 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003016 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003017 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003018 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003019 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003020 if (mType != DIRECT) {
3021 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003022 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003023 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003024 &halInBuffer);
3025 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003026#ifdef FLOAT_EFFECT_CHAIN
3027 buffer = halInBuffer->audioBuffer()->f32;
3028#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003029 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003030#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003031 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3032 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003033 }
3034
3035 // Attach all tracks with same session ID to this chain.
3036 for (size_t i = 0; i < mTracks.size(); ++i) {
3037 sp<Track> track = mTracks[i];
3038 if (session == track->sessionId()) {
3039 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3040 buffer);
3041 track->setMainBuffer(buffer);
3042 chain->incTrackCnt();
3043 }
3044 }
3045
3046 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003047 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003048 if (session == track->sessionId()) {
3049 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3050 chain->incActiveTrackCnt();
3051 }
3052 }
3053 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003054 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003055 chain->setInBuffer(halInBuffer);
3056 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003057 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003058 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003059 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3060 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003061 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003062 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003063 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003064 // Effect chain for other sessions are inserted at beginning of effect
3065 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003066 // sessions is not important.
3067 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3068 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3069 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003070 size_t size = mEffectChains.size();
3071 size_t i = 0;
3072 for (i = 0; i < size; i++) {
3073 if (mEffectChains[i]->sessionId() < session) {
3074 break;
3075 }
3076 }
3077 mEffectChains.insertAt(chain, i);
3078 checkSuspendOnAddEffectChain_l(chain);
3079
3080 return NO_ERROR;
3081}
3082
3083size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3084{
Glenn Kastend848eb42016-03-08 13:42:11 -08003085 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003086
3087 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3088
3089 for (size_t i = 0; i < mEffectChains.size(); i++) {
3090 if (chain == mEffectChains[i]) {
3091 mEffectChains.removeAt(i);
3092 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003093 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003094 if (session == track->sessionId()) {
3095 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3096 chain.get(), session);
3097 chain->decActiveTrackCnt();
3098 }
3099 }
3100
3101 // detach all tracks with same session ID from this chain
3102 for (size_t i = 0; i < mTracks.size(); ++i) {
3103 sp<Track> track = mTracks[i];
3104 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003105 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003106 chain->decTrackCnt();
3107 }
3108 }
3109 break;
3110 }
3111 }
3112 return mEffectChains.size();
3113}
3114
3115status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003116 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003117{
3118 Mutex::Autolock _l(mLock);
3119 return attachAuxEffect_l(track, EffectId);
3120}
3121
3122status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003123 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003124{
3125 status_t status = NO_ERROR;
3126
3127 if (EffectId == 0) {
3128 track->setAuxBuffer(0, NULL);
3129 } else {
3130 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3131 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3132 if (effect != 0) {
3133 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3134 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3135 } else {
3136 status = INVALID_OPERATION;
3137 }
3138 } else {
3139 status = BAD_VALUE;
3140 }
3141 }
3142 return status;
3143}
3144
3145void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3146{
3147 for (size_t i = 0; i < mTracks.size(); ++i) {
3148 sp<Track> track = mTracks[i];
3149 if (track->auxEffectId() == effectId) {
3150 attachAuxEffect_l(track, 0);
3151 }
3152 }
3153}
3154
3155bool AudioFlinger::PlaybackThread::threadLoop()
3156{
Glenn Kasten388d5712017-04-07 14:38:41 -07003157 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003158
Eric Laurent81784c32012-11-19 14:55:58 -08003159 Vector< sp<Track> > tracksToRemove;
3160
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003161 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003162 nsecs_t lastWriteFinished = -1; // time last server write completed
3163 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003164
3165 // MIXER
3166 nsecs_t lastWarning = 0;
3167
3168 // DUPLICATING
3169 // FIXME could this be made local to while loop?
3170 writeFrames = 0;
3171
3172 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003173 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003174
3175 if (mType == MIXER) {
3176 sleepTimeShift = 0;
3177 }
3178
3179 CpuStats cpuStats;
3180 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3181
3182 acquireWakeLock();
3183
Glenn Kasteneef598c2017-04-03 14:41:13 -07003184 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3185 // thread associated with this PlaybackThread.
3186 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3187 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003188 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3189 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003190 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003191 const char *logString = NULL;
3192
rago1bb90822017-05-02 18:31:48 -07003193 // Estimated time for next buffer to be written to hal. This is used only on
3194 // suspended mode (for now) to help schedule the wait time until next iteration.
3195 nsecs_t timeLoopNextNs = 0;
3196
Eric Laurent664539d2013-09-23 18:24:31 -07003197 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003198
Andy Hungf3234512018-07-03 14:51:47 -07003199 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3200 // TODO: add confirmation checks:
3201 // 1) DIRECT threads and linear PCM format really resets to 0?
3202 // 2) Is frame count really valid if not linear pcm?
3203 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3204 if (mType == OFFLOAD || mType == DIRECT) {
3205 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3206 }
3207
Eric Laurent81784c32012-11-19 14:55:58 -08003208 while (!exitPending())
3209 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003210 // Log merge requests are performed during AudioFlinger binder transactions, but
3211 // that does not cover audio playback. It's requested here for that reason.
3212 mAudioFlinger->requestLogMerge();
3213
Eric Laurent81784c32012-11-19 14:55:58 -08003214 cpuStats.sample(myName);
3215
3216 Vector< sp<EffectChain> > effectChains;
3217
Eric Laurent81784c32012-11-19 14:55:58 -08003218 { // scope for mLock
3219
3220 Mutex::Autolock _l(mLock);
3221
Eric Laurent021cf962014-05-13 10:18:14 -07003222 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003223
Glenn Kasteneef598c2017-04-03 14:41:13 -07003224 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003225 if (logString != NULL) {
3226 mNBLogWriter->logTimestamp();
3227 mNBLogWriter->log(logString);
3228 logString = NULL;
3229 }
3230
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003231 // Collect timestamp statistics for the Playback Thread types that support it.
3232 if (mType == MIXER
3233 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003234 || mType == DIRECT
3235 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003236 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003237 // and associate with the sink frames written out. We need
3238 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003239 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003240 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003241 if (mStandby) {
3242 mTimestampVerifier.discontinuity();
3243 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3244 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3245 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3246 mSampleRate);
Andy Hung818e7a32016-02-16 18:08:07 -08003247 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003248 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003249
3250 // We keep track of the last valid kernel position in case we are in underrun
3251 // and the normal mixer period is the same as the fast mixer period, or there
3252 // is some error from the HAL.
3253 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3254 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3255 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3256 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3257 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3258
3259 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3260 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3261 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3262 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003263 }
3264
3265 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3266 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003267 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003268 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003269 }
3270
Andy Hung818e7a32016-02-16 18:08:07 -08003271 // copy over kernel info
3272 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003273 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3274 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003275 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3276 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003277 } else {
3278 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003279 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003280
Andy Hungc54b1ff2016-02-23 14:07:07 -08003281 // mFramesWritten for non-offloaded tracks are contiguous
3282 // even after standby() is called. This is useful for the track frame
3283 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003284 bool serverLocationUpdate = false;
3285 if (mFramesWritten != lastFramesWritten) {
3286 serverLocationUpdate = true;
3287 lastFramesWritten = mFramesWritten;
3288 }
3289 // Only update timestamps if there is a meaningful change.
3290 // Either the kernel timestamp must be valid or we have written something.
3291 if (kernelLocationUpdate || serverLocationUpdate) {
3292 if (serverLocationUpdate) {
3293 // use the time before we called the HAL write - it is a bit more accurate
3294 // to when the server last read data than the current time here.
3295 //
3296 // If we haven't written anything, mLastWriteTime will be -1
3297 // and we use systemTime().
3298 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3299 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3300 ? systemTime() : mLastWriteTime;
3301 }
Andy Hungdae27702016-10-31 14:01:16 -07003302
3303 for (const sp<Track> &t : mActiveTracks) {
3304 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003305 t->updateTrackFrameInfo(
3306 t->mAudioTrackServerProxy->framesReleased(),
3307 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003308 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003309 mTimestamp);
3310 }
Andy Hunge10393e2015-06-12 13:59:33 -07003311 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003312 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003313 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003314#if 0
3315 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003316 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003317 timespec ts;
3318 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003319 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003320 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003321 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003322 }
3323 ++z;
3324#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003325 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003326 if (mSignalPending) {
3327 // A signal was raised while we were unlocked
3328 mSignalPending = false;
3329 } else if (waitingAsyncCallback_l()) {
3330 if (exitPending()) {
3331 break;
3332 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003333 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003334 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003335 releaseWakeLock_l();
3336 released = true;
3337 }
Andy Hung10cbff12017-02-21 17:30:14 -08003338
3339 const int64_t waitNs = computeWaitTimeNs_l();
3340 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3341 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3342 if (status == TIMED_OUT) {
3343 mSignalPending = true; // if timeout recheck everything
3344 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003345 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003346 if (released) {
3347 acquireWakeLock_l();
3348 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003349 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3350 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003351
3352 continue;
3353 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003354 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003355 isSuspended()) {
3356 // put audio hardware into standby after short delay
3357 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003358
3359 threadLoop_standby();
3360
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003361 // This is where we go into standby
3362 if (!mStandby) {
3363 LOG_AUDIO_STATE();
3364 }
Eric Laurent81784c32012-11-19 14:55:58 -08003365 mStandby = true;
3366 }
3367
3368 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3369 // we're about to wait, flush the binder command buffer
3370 IPCThreadState::self()->flushCommands();
3371
3372 clearOutputTracks();
3373
3374 if (exitPending()) {
3375 break;
3376 }
3377
3378 releaseWakeLock_l();
3379 // wait until we have something to do...
3380 ALOGV("%s going to sleep", myName.string());
3381 mWaitWorkCV.wait(mLock);
3382 ALOGV("%s waking up", myName.string());
3383 acquireWakeLock_l();
3384
3385 mMixerStatus = MIXER_IDLE;
3386 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3387 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003388 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003389 checkSilentMode_l();
3390
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003391 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3392 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003393 if (mType == MIXER) {
3394 sleepTimeShift = 0;
3395 }
3396
3397 continue;
3398 }
3399 }
Eric Laurent81784c32012-11-19 14:55:58 -08003400 // mMixerStatusIgnoringFastTracks is also updated internally
3401 mMixerStatus = prepareTracks_l(&tracksToRemove);
3402
Andy Hungdae27702016-10-31 14:01:16 -07003403 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003404
Kevin Rocard069c2712018-03-29 19:09:14 -07003405 updateMetadata_l();
3406
Eric Laurent81784c32012-11-19 14:55:58 -08003407 // prevent any changes in effect chain list and in each effect chain
3408 // during mixing and effect process as the audio buffers could be deleted
3409 // or modified if an effect is created or deleted
3410 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003411 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003412
Eric Laurentbfb1b832013-01-07 09:53:42 -08003413 if (mBytesRemaining == 0) {
3414 mCurrentWriteLength = 0;
3415 if (mMixerStatus == MIXER_TRACKS_READY) {
3416 // threadLoop_mix() sets mCurrentWriteLength
3417 threadLoop_mix();
3418 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3419 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003420 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003421 // must be written to HAL
3422 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003423 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003424 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003425 }
3426 }
Andy Hung98ef9782014-03-04 14:46:50 -08003427 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003428 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003429 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3430 // or mSinkBuffer (if there are no effects).
3431 //
3432 // This is done pre-effects computation; if effects change to
3433 // support higher precision, this needs to move.
3434 //
3435 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003436 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003437 if (mMixerBufferValid) {
3438 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3439 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3440
Andy Hung2ddee192015-12-18 17:34:44 -08003441 // mono blend occurs for mixer threads only (not direct or offloaded)
3442 // and is handled here if we're going directly to the sink.
3443 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003444 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3445 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003446 }
3447
Andy Hung98ef9782014-03-04 14:46:50 -08003448 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3449 mNormalFrameCount * mChannelCount);
3450 }
3451
Eric Laurentbfb1b832013-01-07 09:53:42 -08003452 mBytesRemaining = mCurrentWriteLength;
3453 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003454 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3455 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3456 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3457 mBytesWritten += mBytesRemaining;
3458 mFramesWritten += framesRemaining;
3459 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003460 mBytesRemaining = 0;
3461 }
Eric Laurent81784c32012-11-19 14:55:58 -08003462
Eric Laurentbfb1b832013-01-07 09:53:42 -08003463 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003464 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003465 for (size_t i = 0; i < effectChains.size(); i ++) {
3466 effectChains[i]->process_l();
3467 }
Eric Laurent81784c32012-11-19 14:55:58 -08003468 }
3469 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003470 // Process effect chains for offloaded thread even if no audio
3471 // was read from audio track: process only updates effect state
3472 // and thus does have to be synchronized with audio writes but may have
3473 // to be called while waiting for async write callback
3474 if (mType == OFFLOAD) {
3475 for (size_t i = 0; i < effectChains.size(); i ++) {
3476 effectChains[i]->process_l();
3477 }
3478 }
Eric Laurent81784c32012-11-19 14:55:58 -08003479
Andy Hung98ef9782014-03-04 14:46:50 -08003480 // Only if the Effects buffer is enabled and there is data in the
3481 // Effects buffer (buffer valid), we need to
3482 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003483 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003484 if (mEffectBufferValid) {
3485 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003486
3487 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003488 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3489 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003490 }
3491
Andy Hung98ef9782014-03-04 14:46:50 -08003492 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3493 mNormalFrameCount * mChannelCount);
3494 }
3495
Eric Laurent81784c32012-11-19 14:55:58 -08003496 // enable changes in effect chain
3497 unlockEffectChains(effectChains);
3498
Eric Laurentbfb1b832013-01-07 09:53:42 -08003499 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003500 // mSleepTimeUs == 0 means we must write to audio hardware
3501 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003502 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003503 // We save lastWriteFinished here, as previousLastWriteFinished,
3504 // for throttling. On thread start, previousLastWriteFinished will be
3505 // set to -1, which properly results in no throttling after the first write.
3506 nsecs_t previousLastWriteFinished = lastWriteFinished;
3507 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003508 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003509 // FIXME rewrite to reduce number of system calls
3510 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003511 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003512 lastWriteFinished = systemTime();
3513 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 if (ret < 0) {
3515 mBytesRemaining = 0;
3516 } else {
3517 mBytesWritten += ret;
3518 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003519 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003520 }
3521 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3522 (mMixerStatus == MIXER_DRAIN_ALL)) {
3523 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003524 }
Andy Hung08fb1742015-05-31 23:22:10 -07003525 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003526 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003527 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003528 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003529 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003530 ATRACE_NAME("underrun");
3531 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003532 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003533 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003534 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003535 }
Andy Hung08fb1742015-05-31 23:22:10 -07003536
3537 if (mThreadThrottle
3538 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3539 && ret > 0) { // we wrote something
3540 // Limit MixerThread data processing to no more than twice the
3541 // expected processing rate.
3542 //
3543 // This helps prevent underruns with NuPlayer and other applications
3544 // which may set up buffers that are close to the minimum size, or use
3545 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3546 //
3547 // The throttle smooths out sudden large data drains from the device,
3548 // e.g. when it comes out of standby, which often causes problems with
3549 // (1) mixer threads without a fast mixer (which has its own warm-up)
3550 // (2) minimum buffer sized tracks (even if the track is full,
3551 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003552 //
3553 // Total time spent in last processing cycle equals time spent in
3554 // 1. threadLoop_write, as well as time spent in
3555 // 2. threadLoop_mix (significant for heavy mixing, especially
3556 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003557
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003558 // it's OK if deltaMs (and deltaNs) is an overestimate.
3559 nsecs_t deltaNs;
3560 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3561 __builtin_sub_overflow(
3562 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3563 const int32_t deltaMs = deltaNs / 1000000;
3564
Ivan Lozanoea04d392017-11-07 14:37:07 -08003565 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003566 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3567 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003568 // notify of throttle start on verbose log
3569 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3570 "mixer(%p) throttle begin:"
3571 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003572 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003573 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003574 // Throttle must be attributed to the previous mixer loop's write time
3575 // to allow back-to-back throttling.
3576 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003577 } else {
3578 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3579 if (diff > 0) {
3580 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003581 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003582 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3583 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003584 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003585 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3586 }
Andy Hung08fb1742015-05-31 23:22:10 -07003587 }
3588 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 }
Eric Laurent81784c32012-11-19 14:55:58 -08003590
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003592 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003593 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003594 // suspended requires accurate metering of sleep time.
3595 if (isSuspended()) {
3596 // advance by expected sleepTime
3597 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3598 const nsecs_t nowNs = systemTime();
3599
3600 // compute expected next time vs current time.
3601 // (negative deltas are treated as delays).
3602 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3603 if (deltaNs < -kMaxNextBufferDelayNs) {
3604 // Delays longer than the max allowed trigger a reset.
3605 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3606 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3607 timeLoopNextNs = nowNs + deltaNs;
3608 } else if (deltaNs < 0) {
3609 // Delays within the max delay allowed: zero the delta/sleepTime
3610 // to help the system catch up in the next iteration(s)
3611 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3612 deltaNs = 0;
3613 }
3614 // update sleep time (which is >= 0)
3615 mSleepTimeUs = deltaNs / 1000;
3616 }
Eric Laurente93cc032016-05-05 10:15:10 -07003617 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3618 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003619 }
Glenn Kastene7754022014-10-31 12:11:26 -07003620 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003621 }
Eric Laurent81784c32012-11-19 14:55:58 -08003622 }
3623
3624 // Finally let go of removed track(s), without the lock held
3625 // since we can't guarantee the destructors won't acquire that
3626 // same lock. This will also mutate and push a new fast mixer state.
3627 threadLoop_removeTracks(tracksToRemove);
3628 tracksToRemove.clear();
3629
3630 // FIXME I don't understand the need for this here;
3631 // it was in the original code but maybe the
3632 // assignment in saveOutputTracks() makes this unnecessary?
3633 clearOutputTracks();
3634
3635 // Effect chains will be actually deleted here if they were removed from
3636 // mEffectChains list during mixing or effects processing
3637 effectChains.clear();
3638
3639 // FIXME Note that the above .clear() is no longer necessary since effectChains
3640 // is now local to this block, but will keep it for now (at least until merge done).
3641 }
3642
Eric Laurentbfb1b832013-01-07 09:53:42 -08003643 threadLoop_exit();
3644
Eric Laurentcf817a22014-08-04 20:36:31 -07003645 if (!mStandby) {
3646 threadLoop_standby();
3647 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003648 }
3649
3650 releaseWakeLock();
3651
3652 ALOGV("Thread %p type %d exiting", this, mType);
3653 return false;
3654}
3655
Eric Laurentbfb1b832013-01-07 09:53:42 -08003656// removeTracks_l() must be called with ThreadBase::mLock held
3657void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3658{
3659 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003660 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003661 for (size_t i=0 ; i<count ; i++) {
3662 const sp<Track>& track = tracksToRemove.itemAt(i);
3663 mActiveTracks.remove(track);
3664 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3665 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3666 if (chain != 0) {
3667 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3668 track->sessionId());
3669 chain->decActiveTrackCnt();
3670 }
3671 if (track->isTerminated()) {
3672 removeTrack_l(track);
3673 }
3674 }
3675 }
3676
3677}
Eric Laurent81784c32012-11-19 14:55:58 -08003678
Eric Laurentaccc1472013-09-20 09:36:34 -07003679status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3680{
3681 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003682 ExtendedTimestamp ets;
3683 status_t status = mNormalSink->getTimestamp(ets);
3684 if (status == NO_ERROR) {
3685 status = ets.getBestTimestamp(&timestamp);
3686 }
3687 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003688 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003689 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003690 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003691 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003692 timestamp.mPosition = (uint32_t)position64;
3693 return NO_ERROR;
3694 }
3695 }
3696 return INVALID_OPERATION;
3697}
Eric Laurent1c333e22014-05-20 10:48:17 -07003698
Eric Laurent054d9d32015-04-24 08:48:48 -07003699status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3700 audio_patch_handle_t *handle)
3701{
Andy Hungf60abce2016-08-26 11:37:54 -07003702 status_t status;
3703 if (property_get_bool("af.patch_park", false /* default_value */)) {
3704 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3705 // or if HAL does not properly lock against access.
3706 AutoPark<FastMixer> park(mFastMixer);
3707 status = PlaybackThread::createAudioPatch_l(patch, handle);
3708 } else {
3709 status = PlaybackThread::createAudioPatch_l(patch, handle);
3710 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003711 return status;
3712}
3713
Eric Laurent1c333e22014-05-20 10:48:17 -07003714status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3715 audio_patch_handle_t *handle)
3716{
3717 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003718
3719 // store new device and send to effects
3720 audio_devices_t type = AUDIO_DEVICE_NONE;
3721 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3722 type |= patch->sinks[i].ext.device.type;
3723 }
3724
3725#ifdef ADD_BATTERY_DATA
3726 // when changing the audio output device, call addBatteryData to notify
3727 // the change
3728 if (mOutDevice != type) {
3729 uint32_t params = 0;
3730 // check whether speaker is on
3731 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3732 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003733 }
3734
Eric Laurent054d9d32015-04-24 08:48:48 -07003735 audio_devices_t deviceWithoutSpeaker
3736 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3737 // check if any other device (except speaker) is on
3738 if (type & deviceWithoutSpeaker) {
3739 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3740 }
3741
3742 if (params != 0) {
3743 addBatteryData(params);
3744 }
3745 }
3746#endif
3747
3748 for (size_t i = 0; i < mEffectChains.size(); i++) {
3749 mEffectChains[i]->setDevice_l(type);
3750 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003751
3752 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3753 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3754 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003755 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003756 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003757
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003758 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003759 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3760 status = hwDevice->createAudioPatch(patch->num_sources,
3761 patch->sources,
3762 patch->num_sinks,
3763 patch->sinks,
3764 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003765 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003766 char *address;
3767 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3768 //FIXME: we only support address on first sink with HAL version < 3.0
3769 address = audio_device_address_to_parameter(
3770 patch->sinks[0].ext.device.type,
3771 patch->sinks[0].ext.device.address);
3772 } else {
3773 address = (char *)calloc(1, 1);
3774 }
3775 AudioParameter param = AudioParameter(String8(address));
3776 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003777 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003778 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003779 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003780 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003781 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003782 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003783 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3784 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003785 return status;
3786}
3787
Eric Laurent054d9d32015-04-24 08:48:48 -07003788status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3789{
Andy Hungf60abce2016-08-26 11:37:54 -07003790 status_t status;
3791 if (property_get_bool("af.patch_park", false /* default_value */)) {
3792 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3793 // or if HAL does not properly lock against access.
3794 AutoPark<FastMixer> park(mFastMixer);
3795 status = PlaybackThread::releaseAudioPatch_l(handle);
3796 } else {
3797 status = PlaybackThread::releaseAudioPatch_l(handle);
3798 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003799 return status;
3800}
3801
Eric Laurent1c333e22014-05-20 10:48:17 -07003802status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3803{
3804 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003805
3806 mOutDevice = AUDIO_DEVICE_NONE;
3807
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003808 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003809 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3810 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003811 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003812 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003813 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003814 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003815 }
3816 return status;
3817}
3818
Eric Laurent83b88082014-06-20 18:31:16 -07003819void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3820{
3821 Mutex::Autolock _l(mLock);
3822 mTracks.add(track);
3823}
3824
3825void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3826{
3827 Mutex::Autolock _l(mLock);
3828 destroyTrack_l(track);
3829}
3830
Mikhail Naganovdc769682018-05-04 15:34:08 -07003831void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003832{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003833 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003834 config->role = AUDIO_PORT_ROLE_SOURCE;
3835 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3836 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003837 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3838 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3839 config->flags.output = mOutput->flags;
3840 }
Eric Laurent83b88082014-06-20 18:31:16 -07003841}
3842
Eric Laurent81784c32012-11-19 14:55:58 -08003843// ----------------------------------------------------------------------------
3844
3845AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003846 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3847 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003848 // mAudioMixer below
3849 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003850 mFastMixerFutex(0),
3851 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // mOutputSink below
3853 // mPipeSink below
3854 // mNormalSink below
3855{
3856 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003857 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003858 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003859 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3860 mNormalFrameCount);
3861 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3862
Andy Hungfbfc3952015-01-15 13:33:51 -08003863 if (type == DUPLICATING) {
3864 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3865 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3866 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3867 return;
3868 }
Eric Laurent81784c32012-11-19 14:55:58 -08003869 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003870 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003871 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003872 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003873#if !LOG_NDEBUG
3874 ssize_t index =
3875#else
3876 (void)
3877#endif
3878 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003879 ALOG_ASSERT(index == 0);
3880
3881 // initialize fast mixer depending on configuration
3882 bool initFastMixer;
3883 switch (kUseFastMixer) {
3884 case FastMixer_Never:
3885 initFastMixer = false;
3886 break;
3887 case FastMixer_Always:
3888 initFastMixer = true;
3889 break;
3890 case FastMixer_Static:
3891 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003892 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3893 // where the period is less than an experimentally determined threshold that can be
3894 // scheduled reliably with CFS. However, the BT A2DP HAL is
3895 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3896 initFastMixer = mFrameCount < mNormalFrameCount
3897 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003898 break;
3899 }
Andy Hungfda69402017-02-15 14:33:12 -08003900 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3901 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3902 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003903 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003904 audio_format_t fastMixerFormat;
3905 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3906 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3907 } else {
3908 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3909 }
3910 if (mFormat != fastMixerFormat) {
3911 // change our Sink format to accept our intermediate precision
3912 mFormat = fastMixerFormat;
3913 free(mSinkBuffer);
3914 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3915 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3916 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3917 }
Eric Laurent81784c32012-11-19 14:55:58 -08003918
3919 // create a MonoPipe to connect our submix to FastMixer
3920 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003921
Andy Hung1258c1a2014-05-23 21:22:17 -07003922 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003923 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003924 format.mFormat = fastMixerFormat;
3925 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3926
Eric Laurent81784c32012-11-19 14:55:58 -08003927 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3928 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3929 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3930 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3931 const NBAIO_Format offers[1] = {format};
3932 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003933#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003934 ssize_t index =
3935#else
3936 (void)
3937#endif
3938 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003939 ALOG_ASSERT(index == 0);
3940 monoPipe->setAvgFrames((mScreenState & 1) ?
3941 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3942 mPipeSink = monoPipe;
3943
Eric Laurent81784c32012-11-19 14:55:58 -08003944 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003945 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003946 FastMixerStateQueue *sq = mFastMixer->sq();
3947#ifdef STATE_QUEUE_DUMP
3948 sq->setObserverDump(&mStateQueueObserverDump);
3949 sq->setMutatorDump(&mStateQueueMutatorDump);
3950#endif
3951 FastMixerState *state = sq->begin();
3952 FastTrack *fastTrack = &state->mFastTracks[0];
3953 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3954 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3955 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003956 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3957 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003958 fastTrack->mGeneration++;
3959 state->mFastTracksGen++;
3960 state->mTrackMask = 1;
3961 // fast mixer will use the HAL output sink
3962 state->mOutputSink = mOutputSink.get();
3963 state->mOutputSinkGen++;
3964 state->mFrameCount = mFrameCount;
3965 state->mCommand = FastMixerState::COLD_IDLE;
3966 // already done in constructor initialization list
3967 //mFastMixerFutex = 0;
3968 state->mColdFutexAddr = &mFastMixerFutex;
3969 state->mColdGen++;
3970 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003971 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3972 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003973 sq->end();
3974 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3975
3976 // start the fast mixer
3977 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3978 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003979 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003980 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003981
3982#ifdef AUDIO_WATCHDOG
3983 // create and start the watchdog
3984 mAudioWatchdog = new AudioWatchdog();
3985 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3986 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3987 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003988 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003989#endif
Andy Hung8946a282018-04-19 20:04:56 -07003990 } else {
3991#ifdef TEE_SINK
3992 // Only use the MixerThread tee if there is no FastMixer.
3993 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3994 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3995#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003996 }
3997
3998 switch (kUseFastMixer) {
3999 case FastMixer_Never:
4000 case FastMixer_Dynamic:
4001 mNormalSink = mOutputSink;
4002 break;
4003 case FastMixer_Always:
4004 mNormalSink = mPipeSink;
4005 break;
4006 case FastMixer_Static:
4007 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4008 break;
4009 }
4010}
4011
4012AudioFlinger::MixerThread::~MixerThread()
4013{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004014 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004015 FastMixerStateQueue *sq = mFastMixer->sq();
4016 FastMixerState *state = sq->begin();
4017 if (state->mCommand == FastMixerState::COLD_IDLE) {
4018 int32_t old = android_atomic_inc(&mFastMixerFutex);
4019 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004020 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004021 }
4022 }
4023 state->mCommand = FastMixerState::EXIT;
4024 sq->end();
4025 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4026 mFastMixer->join();
4027 // Though the fast mixer thread has exited, it's state queue is still valid.
4028 // We'll use that extract the final state which contains one remaining fast track
4029 // corresponding to our sub-mix.
4030 state = sq->begin();
4031 ALOG_ASSERT(state->mTrackMask == 1);
4032 FastTrack *fastTrack = &state->mFastTracks[0];
4033 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4034 delete fastTrack->mBufferProvider;
4035 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004036 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004037#ifdef AUDIO_WATCHDOG
4038 if (mAudioWatchdog != 0) {
4039 mAudioWatchdog->requestExit();
4040 mAudioWatchdog->requestExitAndWait();
4041 mAudioWatchdog.clear();
4042 }
4043#endif
4044 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004045 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004046 delete mAudioMixer;
4047}
4048
4049
4050uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4051{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004052 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004053 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4054 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4055 }
4056 return latency;
4057}
4058
4059
4060void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4061{
4062 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4063}
4064
Eric Laurentbfb1b832013-01-07 09:53:42 -08004065ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004066{
4067 // FIXME we should only do one push per cycle; confirm this is true
4068 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004069 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004070 FastMixerStateQueue *sq = mFastMixer->sq();
4071 FastMixerState *state = sq->begin();
4072 if (state->mCommand != FastMixerState::MIX_WRITE &&
4073 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4074 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004075
4076 // FIXME workaround for first HAL write being CPU bound on some devices
4077 ATRACE_BEGIN("write");
4078 mOutput->write((char *)mSinkBuffer, 0);
4079 ATRACE_END();
4080
Eric Laurent81784c32012-11-19 14:55:58 -08004081 int32_t old = android_atomic_inc(&mFastMixerFutex);
4082 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004083 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004084 }
4085#ifdef AUDIO_WATCHDOG
4086 if (mAudioWatchdog != 0) {
4087 mAudioWatchdog->resume();
4088 }
4089#endif
4090 }
4091 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004092#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004093 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004094 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004095#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004096 sq->end();
4097 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4098 if (kUseFastMixer == FastMixer_Dynamic) {
4099 mNormalSink = mPipeSink;
4100 }
4101 } else {
4102 sq->end(false /*didModify*/);
4103 }
4104 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004105 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004106}
4107
4108void AudioFlinger::MixerThread::threadLoop_standby()
4109{
4110 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004111 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004112 FastMixerStateQueue *sq = mFastMixer->sq();
4113 FastMixerState *state = sq->begin();
4114 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004115 // Report any frames trapped in the Monopipe
4116 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4117 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4118 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4119 "monoPipeWritten:%lld monoPipeLeft:%lld",
4120 (long long)mFramesWritten, (long long)mSuspendedFrames,
4121 (long long)mPipeSink->framesWritten(), pipeFrames);
4122 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4123
Eric Laurent81784c32012-11-19 14:55:58 -08004124 state->mCommand = FastMixerState::COLD_IDLE;
4125 state->mColdFutexAddr = &mFastMixerFutex;
4126 state->mColdGen++;
4127 mFastMixerFutex = 0;
4128 sq->end();
4129 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4130 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4131 if (kUseFastMixer == FastMixer_Dynamic) {
4132 mNormalSink = mOutputSink;
4133 }
4134#ifdef AUDIO_WATCHDOG
4135 if (mAudioWatchdog != 0) {
4136 mAudioWatchdog->pause();
4137 }
4138#endif
4139 } else {
4140 sq->end(false /*didModify*/);
4141 }
4142 }
4143 PlaybackThread::threadLoop_standby();
4144}
4145
Eric Laurentbfb1b832013-01-07 09:53:42 -08004146bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4147{
4148 return false;
4149}
4150
4151bool AudioFlinger::PlaybackThread::shouldStandby_l()
4152{
4153 return !mStandby;
4154}
4155
4156bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4157{
4158 Mutex::Autolock _l(mLock);
4159 return waitingAsyncCallback_l();
4160}
4161
Eric Laurent81784c32012-11-19 14:55:58 -08004162// shared by MIXER and DIRECT, overridden by DUPLICATING
4163void AudioFlinger::PlaybackThread::threadLoop_standby()
4164{
4165 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004166 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004168 // discard any pending drain or write ack by incrementing sequence
4169 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4170 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004172 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4173 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004175 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004176}
4177
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004178void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4179{
4180 ALOGV("signal playback thread");
4181 broadcast_l();
4182}
4183
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004184void AudioFlinger::PlaybackThread::onAsyncError()
4185{
4186 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4187 invalidateTracks((audio_stream_type_t)i);
4188 }
4189}
4190
Eric Laurent81784c32012-11-19 14:55:58 -08004191void AudioFlinger::MixerThread::threadLoop_mix()
4192{
Eric Laurent81784c32012-11-19 14:55:58 -08004193 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004194 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004195 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004196 // increase sleep time progressively when application underrun condition clears.
4197 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4198 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4199 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004200 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004201 sleepTimeShift--;
4202 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004203 mSleepTimeUs = 0;
4204 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004205 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004206
Eric Laurent81784c32012-11-19 14:55:58 -08004207}
4208
4209void AudioFlinger::MixerThread::threadLoop_sleepTime()
4210{
4211 // If no tracks are ready, sleep once for the duration of an output
4212 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004213 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004214 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004215 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4216 // Using the Monopipe availableToWrite, we estimate the
4217 // sleep time to retry for more data (before we underrun).
4218 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4219 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4220 const size_t pipeFrames = monoPipe->maxFrames();
4221 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4222 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4223 const size_t framesDelay = std::min(
4224 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4225 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4226 pipeFrames, framesLeft, framesDelay);
4227 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4228 } else {
4229 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4230 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4231 mSleepTimeUs = kMinThreadSleepTimeUs;
4232 }
4233 // reduce sleep time in case of consecutive application underruns to avoid
4234 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4235 // duration we would end up writing less data than needed by the audio HAL if
4236 // the condition persists.
4237 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4238 sleepTimeShift++;
4239 }
Eric Laurent81784c32012-11-19 14:55:58 -08004240 }
4241 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004242 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004243 }
4244 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004245 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4246 // before effects processing or output.
4247 if (mMixerBufferValid) {
4248 memset(mMixerBuffer, 0, mMixerBufferSize);
4249 } else {
4250 memset(mSinkBuffer, 0, mSinkBufferSize);
4251 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004252 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004253 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4254 "anticipated start");
4255 }
4256 // TODO add standby time extension fct of effect tail
4257}
4258
4259// prepareTracks_l() must be called with ThreadBase::mLock held
4260AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4261 Vector< sp<Track> > *tracksToRemove)
4262{
Andy Hung1bc088a2018-02-09 15:57:31 -08004263 // clean up deleted track names in AudioMixer before allocating new tracks
4264 (void)mTracks.processDeletedTrackNames([this](int name) {
4265 // for each name, destroy it in the AudioMixer
4266 if (mAudioMixer->exists(name)) {
4267 mAudioMixer->destroy(name);
4268 }
4269 });
4270 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004271
4272 mixer_state mixerStatus = MIXER_IDLE;
4273 // find out which tracks need to be processed
4274 size_t count = mActiveTracks.size();
4275 size_t mixedTracks = 0;
4276 size_t tracksWithEffect = 0;
4277 // counts only _active_ fast tracks
4278 size_t fastTracks = 0;
4279 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4280
4281 float masterVolume = mMasterVolume;
4282 bool masterMute = mMasterMute;
4283
4284 if (masterMute) {
4285 masterVolume = 0;
4286 }
4287 // Delegate master volume control to effect in output mix effect chain if needed
4288 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4289 if (chain != 0) {
4290 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4291 chain->setVolume_l(&v, &v);
4292 masterVolume = (float)((v + (1 << 23)) >> 24);
4293 chain.clear();
4294 }
4295
4296 // prepare a new state to push
4297 FastMixerStateQueue *sq = NULL;
4298 FastMixerState *state = NULL;
4299 bool didModify = false;
4300 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004301 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004302 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004303 sq = mFastMixer->sq();
4304 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004305 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004306 }
4307
Andy Hung69aed5f2014-02-25 17:24:40 -08004308 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004309 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004310
Andy Hungbd3b2b02018-05-21 10:53:11 -07004311 // DeferredOperations handles statistics after setting mixerStatus.
4312 class DeferredOperations {
4313 public:
4314 DeferredOperations(mixer_state *mixerStatus)
4315 : mMixerStatus(mixerStatus) { }
4316
4317 // when leaving scope, tally frames properly.
4318 ~DeferredOperations() {
4319 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4320 // because that is when the underrun occurs.
4321 // We do not distinguish between FastTracks and NormalTracks here.
4322 if (*mMixerStatus == MIXER_TRACKS_READY) {
4323 for (const auto &underrun : mUnderrunFrames) {
4324 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4325 underrun.second);
4326 }
4327 }
4328 }
4329
4330 // tallyUnderrunFrames() is called to update the track counters
4331 // with the number of underrun frames for a particular mixer period.
4332 // We defer tallying until we know the final mixer status.
4333 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4334 mUnderrunFrames.emplace_back(track, underrunFrames);
4335 }
4336
4337 private:
4338 const mixer_state * const mMixerStatus;
4339 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4340 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4341
Eric Laurent81784c32012-11-19 14:55:58 -08004342 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004343 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004344
4345 // this const just means the local variable doesn't change
4346 Track* const track = t.get();
4347
4348 // process fast tracks
4349 if (track->isFastTrack()) {
4350
4351 // It's theoretically possible (though unlikely) for a fast track to be created
4352 // and then removed within the same normal mix cycle. This is not a problem, as
4353 // the track never becomes active so it's fast mixer slot is never touched.
4354 // The converse, of removing an (active) track and then creating a new track
4355 // at the identical fast mixer slot within the same normal mix cycle,
4356 // is impossible because the slot isn't marked available until the end of each cycle.
4357 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004358 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004359 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4360 FastTrack *fastTrack = &state->mFastTracks[j];
4361
4362 // Determine whether the track is currently in underrun condition,
4363 // and whether it had a recent underrun.
4364 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4365 FastTrackUnderruns underruns = ftDump->mUnderruns;
4366 uint32_t recentFull = (underruns.mBitFields.mFull -
4367 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4368 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4369 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4370 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4371 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4372 uint32_t recentUnderruns = recentPartial + recentEmpty;
4373 track->mObservedUnderruns = underruns;
4374 // don't count underruns that occur while stopping or pausing
4375 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004376 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004377 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4378 recentUnderruns > 0) {
4379 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004380 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004381 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004382 // Immediately account for FastTrack underruns.
4383 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004384
4385 // This is similar to the state machine for normal tracks,
4386 // with a few modifications for fast tracks.
4387 bool isActive = true;
4388 switch (track->mState) {
4389 case TrackBase::STOPPING_1:
4390 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004392 track->mState = TrackBase::STOPPING_2;
4393 }
4394 break;
4395 case TrackBase::PAUSING:
4396 // ramp down is not yet implemented
4397 track->setPaused();
4398 break;
4399 case TrackBase::RESUMING:
4400 // ramp up is not yet implemented
4401 track->mState = TrackBase::ACTIVE;
4402 break;
4403 case TrackBase::ACTIVE:
4404 if (recentFull > 0 || recentPartial > 0) {
4405 // track has provided at least some frames recently: reset retry count
4406 track->mRetryCount = kMaxTrackRetries;
4407 }
4408 if (recentUnderruns == 0) {
4409 // no recent underruns: stay active
4410 break;
4411 }
4412 // there has recently been an underrun of some kind
4413 if (track->sharedBuffer() == 0) {
4414 // were any of the recent underruns "empty" (no frames available)?
4415 if (recentEmpty == 0) {
4416 // no, then ignore the partial underruns as they are allowed indefinitely
4417 break;
4418 }
4419 // there has recently been an "empty" underrun: decrement the retry counter
4420 if (--(track->mRetryCount) > 0) {
4421 break;
4422 }
4423 // indicate to client process that the track was disabled because of underrun;
4424 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004425 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004426 // remove from active list, but state remains ACTIVE [confusing but true]
4427 isActive = false;
4428 break;
4429 }
4430 // fall through
4431 case TrackBase::STOPPING_2:
4432 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004433 case TrackBase::STOPPED:
4434 case TrackBase::FLUSHED: // flush() while active
4435 // Check for presentation complete if track is inactive
4436 // We have consumed all the buffers of this track.
4437 // This would be incomplete if we auto-paused on underrun
4438 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004439 uint32_t latency = 0;
4440 status_t result = mOutput->stream->getLatency(&latency);
4441 ALOGE_IF(result != OK,
4442 "Error when retrieving output stream latency: %d", result);
4443 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004444 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004445 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4446 // track stays in active list until presentation is complete
4447 break;
4448 }
4449 }
4450 if (track->isStopping_2()) {
4451 track->mState = TrackBase::STOPPED;
4452 }
4453 if (track->isStopped()) {
4454 // Can't reset directly, as fast mixer is still polling this track
4455 // track->reset();
4456 // So instead mark this track as needing to be reset after push with ack
4457 resetMask |= 1 << i;
4458 }
4459 isActive = false;
4460 break;
4461 case TrackBase::IDLE:
4462 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004463 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004464 }
4465
4466 if (isActive) {
4467 // was it previously inactive?
4468 if (!(state->mTrackMask & (1 << j))) {
4469 ExtendedAudioBufferProvider *eabp = track;
4470 VolumeProvider *vp = track;
4471 fastTrack->mBufferProvider = eabp;
4472 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004473 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004474 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004475 fastTrack->mGeneration++;
4476 state->mTrackMask |= 1 << j;
4477 didModify = true;
4478 // no acknowledgement required for newly active tracks
4479 }
Kevin Rocard12381092018-04-11 09:19:59 -07004480 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004481 // cache the combined master volume and stream type volume for fast mixer; this
4482 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004483 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004484 proxy->framesReleased()).first;
4485 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004486 * mStreamTypes[track->streamType()].volume
4487 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004488 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004489 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4490 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4491 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4492 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004493 ++fastTracks;
4494 } else {
4495 // was it previously active?
4496 if (state->mTrackMask & (1 << j)) {
4497 fastTrack->mBufferProvider = NULL;
4498 fastTrack->mGeneration++;
4499 state->mTrackMask &= ~(1 << j);
4500 didModify = true;
4501 // If any fast tracks were removed, we must wait for acknowledgement
4502 // because we're about to decrement the last sp<> on those tracks.
4503 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4504 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004505 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4506 // AudioTrack may start (which may not be with a start() but with a write()
4507 // after underrun) and immediately paused or released. In that case the
4508 // FastTrack state hasn't had time to update.
4509 // TODO Remove the ALOGW when this theory is confirmed.
4510 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004511 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4512 j, track->mState, state->mTrackMask, recentUnderruns,
4513 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004514 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004515 }
4516 tracksToRemove->add(track);
4517 // Avoids a misleading display in dumpsys
4518 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4519 }
4520 continue;
4521 }
4522
4523 { // local variable scope to avoid goto warning
4524
4525 audio_track_cblk_t* cblk = track->cblk();
4526
4527 // The first time a track is added we wait
4528 // for all its buffers to be filled before processing it
4529 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004530
4531 // if an active track doesn't exist in the AudioMixer, create it.
4532 if (!mAudioMixer->exists(name)) {
4533 status_t status = mAudioMixer->create(
4534 name,
4535 track->mChannelMask,
4536 track->mFormat,
4537 track->mSessionId);
4538 if (status != OK) {
4539 ALOGW("%s: cannot create track name"
4540 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4541 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4542 tracksToRemove->add(track);
4543 track->invalidate(); // consider it dead.
4544 continue;
4545 }
4546 }
4547
Eric Laurent81784c32012-11-19 14:55:58 -08004548 // make sure that we have enough frames to mix one full buffer.
4549 // enforce this condition only once to enable draining the buffer in case the client
4550 // app does not call stop() and relies on underrun to stop:
4551 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4552 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004553 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004554 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004555 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004556
4557 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004558 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004559 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4560 // add frames already consumed but not yet released by the resampler
4561 // because mAudioTrackServerProxy->framesReady() will include these frames
4562 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4563
Eric Laurent81784c32012-11-19 14:55:58 -08004564 uint32_t minFrames = 1;
4565 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4566 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004567 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004568 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004569
4570 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004571 if (ATRACE_ENABLED()) {
4572 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004573 std::string traceName("nRdy");
4574 traceName += std::to_string(track->name());
4575 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004576 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004577 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004578 !track->isPaused() && !track->isTerminated())
4579 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004580 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004581
4582 mixedTracks++;
4583
Andy Hung69aed5f2014-02-25 17:24:40 -08004584 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4585 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004586 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004587 if (track->mainBuffer() != mSinkBuffer &&
4588 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004589 if (mEffectBufferEnabled) {
4590 mEffectBufferValid = true; // Later can set directly.
4591 }
Eric Laurent81784c32012-11-19 14:55:58 -08004592 chain = getEffectChain_l(track->sessionId());
4593 // Delegate volume control to effect in track effect chain if needed
4594 if (chain != 0) {
4595 tracksWithEffect++;
4596 } else {
4597 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4598 "session %d",
4599 name, track->sessionId());
4600 }
4601 }
4602
4603
4604 int param = AudioMixer::VOLUME;
4605 if (track->mFillingUpStatus == Track::FS_FILLED) {
4606 // no ramp for the first volume setting
4607 track->mFillingUpStatus = Track::FS_ACTIVE;
4608 if (track->mState == TrackBase::RESUMING) {
4609 track->mState = TrackBase::ACTIVE;
4610 param = AudioMixer::RAMP_VOLUME;
4611 }
4612 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004613 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004614 // FIXME should not make a decision based on mServer
4615 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004616 // If the track is stopped before the first frame was mixed,
4617 // do not apply ramp
4618 param = AudioMixer::RAMP_VOLUME;
4619 }
4620
4621 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004622 uint32_t vl, vr; // in U8.24 integer format
4623 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004624 // read original volumes with volume control
4625 float typeVolume = mStreamTypes[track->streamType()].volume;
4626 float v = masterVolume * typeVolume;
4627
Glenn Kastene4756fe2012-11-29 13:38:14 -08004628 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004629 vl = vr = 0;
4630 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004631 if (track->isPausing()) {
4632 track->setPaused();
4633 }
4634 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004635 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004636 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004637 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4638 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004639 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004640 if (vlf > GAIN_FLOAT_UNITY) {
4641 ALOGV("Track left volume out of range: %.3g", vlf);
4642 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004643 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004644 if (vrf > GAIN_FLOAT_UNITY) {
4645 ALOGV("Track right volume out of range: %.3g", vrf);
4646 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004647 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004648 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004649 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004650 // now apply the master volume and stream type volume and shaper volume
4651 vlf *= v * vh;
4652 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004653 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004654 // then derive vl and vr as U8.24 versions for the effect chain
4655 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4656 vl = (uint32_t) (scaleto8_24 * vlf);
4657 vr = (uint32_t) (scaleto8_24 * vrf);
4658 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004659 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004660 // send level comes from shared memory and so may be corrupt
4661 if (sendLevel > MAX_GAIN_INT) {
4662 ALOGV("Track send level out of range: %04X", sendLevel);
4663 sendLevel = MAX_GAIN_INT;
4664 }
Andy Hung6be49402014-05-30 10:42:03 -07004665 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4666 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004668
Kevin Rocard12381092018-04-11 09:19:59 -07004669 track->setFinalVolume((vrf + vlf) / 2.f);
4670
Eric Laurent81784c32012-11-19 14:55:58 -08004671 // Delegate volume control to effect in track effect chain if needed
4672 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4673 // Do not ramp volume if volume is controlled by effect
4674 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004675 // Update remaining floating point volume levels
4676 vlf = (float)vl / (1 << 24);
4677 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004678 track->mHasVolumeController = true;
4679 } else {
4680 // force no volume ramp when volume controller was just disabled or removed
4681 // from effect chain to avoid volume spike
4682 if (track->mHasVolumeController) {
4683 param = AudioMixer::VOLUME;
4684 }
4685 track->mHasVolumeController = false;
4686 }
4687
Eric Laurent7c29ec92017-09-20 17:54:22 -07004688 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4689 // still applied by the mixer.
4690 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4691 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4692 if (v != mLeftVolFloat) {
4693 status_t result = mOutput->stream->setVolume(v, v);
4694 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4695 if (result == OK) {
4696 mLeftVolFloat = v;
4697 }
4698 }
4699 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4700 // remove stream volume contribution from software volume.
4701 if (v != 0.0f && mLeftVolFloat == v) {
4702 vlf = min(1.0f, vlf / v);
4703 vrf = min(1.0f, vrf / v);
4704 vaf = min(1.0f, vaf / v);
4705 }
4706 }
Eric Laurent81784c32012-11-19 14:55:58 -08004707 // XXX: these things DON'T need to be done each time
4708 mAudioMixer->setBufferProvider(name, track);
4709 mAudioMixer->enable(name);
4710
Andy Hung6be49402014-05-30 10:42:03 -07004711 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4712 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4713 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004714 mAudioMixer->setParameter(
4715 name,
4716 AudioMixer::TRACK,
4717 AudioMixer::FORMAT, (void *)track->format());
4718 mAudioMixer->setParameter(
4719 name,
4720 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004721 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004722 mAudioMixer->setParameter(
4723 name,
4724 AudioMixer::TRACK,
4725 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004726 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004727 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004728 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004729 if (reqSampleRate == 0) {
4730 reqSampleRate = mSampleRate;
4731 } else if (reqSampleRate > maxSampleRate) {
4732 reqSampleRate = maxSampleRate;
4733 }
Eric Laurent81784c32012-11-19 14:55:58 -08004734 mAudioMixer->setParameter(
4735 name,
4736 AudioMixer::RESAMPLE,
4737 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004738 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004739
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004740 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004741 mAudioMixer->setParameter(
4742 name,
4743 AudioMixer::TIMESTRETCH,
4744 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004745 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004746
Andy Hung69aed5f2014-02-25 17:24:40 -08004747 /*
4748 * Select the appropriate output buffer for the track.
4749 *
Andy Hung98ef9782014-03-04 14:46:50 -08004750 * Tracks with effects go into their own effects chain buffer
4751 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004752 *
4753 * Other tracks can use mMixerBuffer for higher precision
4754 * channel accumulation. If this buffer is enabled
4755 * (mMixerBufferEnabled true), then selected tracks will accumulate
4756 * into it.
4757 *
4758 */
4759 if (mMixerBufferEnabled
4760 && (track->mainBuffer() == mSinkBuffer
4761 || track->mainBuffer() == mMixerBuffer)) {
4762 mAudioMixer->setParameter(
4763 name,
4764 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004765 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004766 mAudioMixer->setParameter(
4767 name,
4768 AudioMixer::TRACK,
4769 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4770 // TODO: override track->mainBuffer()?
4771 mMixerBufferValid = true;
4772 } else {
4773 mAudioMixer->setParameter(
4774 name,
4775 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004776 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004777 mAudioMixer->setParameter(
4778 name,
4779 AudioMixer::TRACK,
4780 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4781 }
Eric Laurent81784c32012-11-19 14:55:58 -08004782 mAudioMixer->setParameter(
4783 name,
4784 AudioMixer::TRACK,
4785 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4786
4787 // reset retry count
4788 track->mRetryCount = kMaxTrackRetries;
4789
4790 // If one track is ready, set the mixer ready if:
4791 // - the mixer was not ready during previous round OR
4792 // - no other track is not ready
4793 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4794 mixerStatus != MIXER_TRACKS_ENABLED) {
4795 mixerStatus = MIXER_TRACKS_READY;
4796 }
4797 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004798 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004799 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004800 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4801 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004802 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004803 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004804 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004805
Eric Laurent81784c32012-11-19 14:55:58 -08004806 // clear effect chain input buffer if an active track underruns to avoid sending
4807 // previous audio buffer again to effects
4808 chain = getEffectChain_l(track->sessionId());
4809 if (chain != 0) {
4810 chain->clearInputBuffer();
4811 }
4812
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004813 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004814 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4815 track->isStopped() || track->isPaused()) {
4816 // We have consumed all the buffers of this track.
4817 // Remove it from the list of active tracks.
4818 // TODO: use actual buffer filling status instead of latency when available from
4819 // audio HAL
4820 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004821 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004822 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4823 if (track->isStopped()) {
4824 track->reset();
4825 }
4826 tracksToRemove->add(track);
4827 }
4828 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004829 // No buffers for this track. Give it a few chances to
4830 // fill a buffer, then remove it from active list.
4831 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004832 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004833 tracksToRemove->add(track);
4834 // indicate to client process that the track was disabled because of underrun;
4835 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004836 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004837 // If one track is not ready, mark the mixer also not ready if:
4838 // - the mixer was ready during previous round OR
4839 // - no other track is ready
4840 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4841 mixerStatus != MIXER_TRACKS_READY) {
4842 mixerStatus = MIXER_TRACKS_ENABLED;
4843 }
4844 }
4845 mAudioMixer->disable(name);
4846 }
4847
4848 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004849
4850 }
4851
4852 // Push the new FastMixer state if necessary
4853 bool pauseAudioWatchdog = false;
4854 if (didModify) {
4855 state->mFastTracksGen++;
4856 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4857 if (kUseFastMixer == FastMixer_Dynamic &&
4858 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4859 state->mCommand = FastMixerState::COLD_IDLE;
4860 state->mColdFutexAddr = &mFastMixerFutex;
4861 state->mColdGen++;
4862 mFastMixerFutex = 0;
4863 if (kUseFastMixer == FastMixer_Dynamic) {
4864 mNormalSink = mOutputSink;
4865 }
4866 // If we go into cold idle, need to wait for acknowledgement
4867 // so that fast mixer stops doing I/O.
4868 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4869 pauseAudioWatchdog = true;
4870 }
Eric Laurent81784c32012-11-19 14:55:58 -08004871 }
4872 if (sq != NULL) {
4873 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004874 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4875 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4876 // when bringing the output sink into standby.)
4877 //
4878 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4879 //
4880 // This occurs with BT suspend when we idle the FastMixer with
4881 // active tracks, which may be added or removed.
4882 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004883 }
4884#ifdef AUDIO_WATCHDOG
4885 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4886 mAudioWatchdog->pause();
4887 }
4888#endif
4889
4890 // Now perform the deferred reset on fast tracks that have stopped
4891 while (resetMask != 0) {
4892 size_t i = __builtin_ctz(resetMask);
4893 ALOG_ASSERT(i < count);
4894 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004895 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004896 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4897 track->reset();
4898 }
4899
Andy Hung80d03d22018-04-10 10:32:11 -07004900 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4901 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4902 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4903 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4904 // See also the implementation of destroyTrack_l().
4905 for (const auto &track : *tracksToRemove) {
4906 const int name = track->name();
4907 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4908 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4909 }
4910 }
4911
Eric Laurent81784c32012-11-19 14:55:58 -08004912 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004913 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004914
Eric Laurent97d547d2014-09-02 14:45:53 -07004915 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4916 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004917 }
4918
4919 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004920 // as long as there are effects we should clear the effects buffer, to avoid
4921 // passing a non-clean buffer to the effect chain
4922 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004923 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004924 // sink or mix buffer must be cleared if all tracks are connected to an
4925 // effect chain as in this case the mixer will not write to the sink or mix buffer
4926 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004927 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4928 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004929 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004930 if (mMixerBufferValid) {
4931 memset(mMixerBuffer, 0, mMixerBufferSize);
4932 // TODO: In testing, mSinkBuffer below need not be cleared because
4933 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4934 // after mixing.
4935 //
4936 // To enforce this guarantee:
4937 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4938 // (mixedTracks == 0 && fastTracks > 0))
4939 // must imply MIXER_TRACKS_READY.
4940 // Later, we may clear buffers regardless, and skip much of this logic.
4941 }
Andy Hung98ef9782014-03-04 14:46:50 -08004942 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004943 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004944 }
4945
4946 // if any fast tracks, then status is ready
4947 mMixerStatusIgnoringFastTracks = mixerStatus;
4948 if (fastTracks > 0) {
4949 mixerStatus = MIXER_TRACKS_READY;
4950 }
4951 return mixerStatus;
4952}
4953
Eric Laurentad7dd962016-09-22 12:38:37 -07004954// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004955uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004956{
4957 uint32_t trackCount = 0;
4958 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004959 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004960 trackCount++;
4961 }
4962 }
4963 return trackCount;
4964}
4965
Andy Hung1bc088a2018-02-09 15:57:31 -08004966// isTrackAllowed_l() must be called with ThreadBase::mLock held
4967bool AudioFlinger::MixerThread::isTrackAllowed_l(
4968 audio_channel_mask_t channelMask, audio_format_t format,
4969 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004970{
Andy Hung1bc088a2018-02-09 15:57:31 -08004971 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4972 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004973 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004974 // Check validity as we don't call AudioMixer::create() here.
4975 if (!AudioMixer::isValidFormat(format)) {
4976 ALOGW("%s: invalid format: %#x", __func__, format);
4977 return false;
4978 }
4979 if (!AudioMixer::isValidChannelMask(channelMask)) {
4980 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4981 return false;
4982 }
4983 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004984}
4985
Eric Laurent10351942014-05-08 18:49:52 -07004986// checkForNewParameter_l() must be called with ThreadBase::mLock held
4987bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4988 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004989{
Eric Laurent81784c32012-11-19 14:55:58 -08004990 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004991 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004992
Eric Laurent10351942014-05-08 18:49:52 -07004993 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004994
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004995 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004996
Eric Laurent10351942014-05-08 18:49:52 -07004997 AudioParameter param = AudioParameter(keyValuePair);
4998 int value;
4999 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5000 reconfig = true;
5001 }
5002 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005003 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005004 status = BAD_VALUE;
5005 } else {
5006 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005007 reconfig = true;
5008 }
Eric Laurent10351942014-05-08 18:49:52 -07005009 }
5010 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005011 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005012 status = BAD_VALUE;
5013 } else {
5014 // no need to save value, since it's constant
5015 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005016 }
Eric Laurent10351942014-05-08 18:49:52 -07005017 }
5018 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5019 // do not accept frame count changes if tracks are open as the track buffer
5020 // size depends on frame count and correct behavior would not be guaranteed
5021 // if frame count is changed after track creation
5022 if (!mTracks.isEmpty()) {
5023 status = INVALID_OPERATION;
5024 } else {
5025 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005026 }
Eric Laurent10351942014-05-08 18:49:52 -07005027 }
5028 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005029#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005030 // when changing the audio output device, call addBatteryData to notify
5031 // the change
5032 if (mOutDevice != value) {
5033 uint32_t params = 0;
5034 // check whether speaker is on
5035 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5036 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005037 }
Eric Laurent10351942014-05-08 18:49:52 -07005038
5039 audio_devices_t deviceWithoutSpeaker
5040 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5041 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005042 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005043 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5044 }
5045
5046 if (params != 0) {
5047 addBatteryData(params);
5048 }
5049 }
Eric Laurent81784c32012-11-19 14:55:58 -08005050#endif
5051
Eric Laurent10351942014-05-08 18:49:52 -07005052 // forward device change to effects that have requested to be
5053 // aware of attached audio device.
5054 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005055 a2dpDeviceChanged =
5056 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005057 mOutDevice = value;
5058 for (size_t i = 0; i < mEffectChains.size(); i++) {
5059 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005060 }
5061 }
Eric Laurent10351942014-05-08 18:49:52 -07005062 }
Eric Laurent81784c32012-11-19 14:55:58 -08005063
Eric Laurent10351942014-05-08 18:49:52 -07005064 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005065 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005066 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005067 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005068 mStandby = true;
5069 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005070 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005071 }
Eric Laurent10351942014-05-08 18:49:52 -07005072 if (status == NO_ERROR && reconfig) {
5073 readOutputParameters_l();
5074 delete mAudioMixer;
5075 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005076 for (const auto &track : mTracks) {
5077 const int name = track->name();
5078 status_t status = mAudioMixer->create(
5079 name,
5080 track->mChannelMask,
5081 track->mFormat,
5082 track->mSessionId);
5083 ALOGW_IF(status != NO_ERROR,
5084 "%s: cannot create track name"
5085 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5086 __func__,
5087 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005088 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005089 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005090 }
Eric Laurent81784c32012-11-19 14:55:58 -08005091 }
5092
Eric Laurent42537be2016-01-08 17:16:42 -08005093 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005094}
5095
5096
5097void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5098{
Eric Laurent81784c32012-11-19 14:55:58 -08005099 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005100 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005101 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005102 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005103 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005104 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005105 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005106 } else {
5107 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005108 }
Eric Laurent81784c32012-11-19 14:55:58 -08005109
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005110 if (hasFastMixer()) {
5111 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5112
5113 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5114 // while we are dumping it. It may be inconsistent, but it won't mutate!
5115 // This is a large object so we place it on the heap.
5116 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5117 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
5118 copy->dump(fd);
5119 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08005120
5121#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005122 // Similar for state queue
5123 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5124 observerCopy.dump(fd);
5125 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5126 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005127#endif
5128
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005129#ifdef AUDIO_WATCHDOG
5130 if (mAudioWatchdog != 0) {
5131 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5132 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5133 wdCopy.dump(fd);
5134 }
5135#endif
5136
5137 } else {
5138 dprintf(fd, " No FastMixer\n");
5139 }
Eric Laurent81784c32012-11-19 14:55:58 -08005140}
5141
5142uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5143{
5144 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5145}
5146
5147uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5148{
5149 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5150}
5151
5152void AudioFlinger::MixerThread::cacheParameters_l()
5153{
5154 PlaybackThread::cacheParameters_l();
5155
5156 // FIXME: Relaxed timing because of a certain device that can't meet latency
5157 // Should be reduced to 2x after the vendor fixes the driver issue
5158 // increase threshold again due to low power audio mode. The way this warning
5159 // threshold is calculated and its usefulness should be reconsidered anyway.
5160 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5161}
5162
5163// ----------------------------------------------------------------------------
5164
5165AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005166 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5167 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005168{
5169}
5170
Eric Laurentbfb1b832013-01-07 09:53:42 -08005171AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5172 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005173 ThreadBase::type_t type, bool systemReady)
5174 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005175 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005176{
5177}
5178
Eric Laurent81784c32012-11-19 14:55:58 -08005179AudioFlinger::DirectOutputThread::~DirectOutputThread()
5180{
5181}
5182
Eric Laurent5850c4c2016-11-10 13:04:31 -08005183void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005184{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005185 float left, right;
5186
5187 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5188 left = right = 0;
5189 } else {
5190 float typeVolume = mStreamTypes[track->streamType()].volume;
5191 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005192 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005193
Andy Hung10cbff12017-02-21 17:30:14 -08005194 // Get volumeshaper scaling
5195 std::pair<float /* volume */, bool /* active */>
5196 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005197 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005198 v *= vh.first;
5199 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005200
Glenn Kastenc56f3422014-03-21 17:53:17 -07005201 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5202 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5203 if (left > GAIN_FLOAT_UNITY) {
5204 left = GAIN_FLOAT_UNITY;
5205 }
5206 left *= v;
5207 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5208 if (right > GAIN_FLOAT_UNITY) {
5209 right = GAIN_FLOAT_UNITY;
5210 }
5211 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212 }
5213
5214 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005215 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005216 if (left != mLeftVolFloat || right != mRightVolFloat) {
5217 mLeftVolFloat = left;
5218 mRightVolFloat = right;
5219
5220 // Convert volumes from float to 8.24
5221 uint32_t vl = (uint32_t)(left * (1 << 24));
5222 uint32_t vr = (uint32_t)(right * (1 << 24));
5223
5224 // Delegate volume control to effect in track effect chain if needed
5225 // only one effect chain can be present on DirectOutputThread, so if
5226 // there is one, the track is connected to it
5227 if (!mEffectChains.isEmpty()) {
5228 mEffectChains[0]->setVolume_l(&vl, &vr);
5229 left = (float)vl / (1 << 24);
5230 right = (float)vr / (1 << 24);
5231 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005232 status_t result = mOutput->stream->setVolume(left, right);
5233 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005234 }
5235 }
5236}
5237
Phil Burk43b4dcc2015-06-09 16:53:44 -07005238void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5239{
5240 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005241 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005242
Eric Laurent0f0631e2015-07-06 18:01:25 -07005243 if (previousTrack != 0 && latestTrack != 0) {
5244 if (mType == DIRECT) {
5245 if (previousTrack.get() != latestTrack.get()) {
5246 mFlushPending = true;
5247 }
5248 } else /* mType == OFFLOAD */ {
5249 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5250 mFlushPending = true;
5251 }
5252 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005253 }
5254 PlaybackThread::onAddNewTrack_l();
5255}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005256
Eric Laurent81784c32012-11-19 14:55:58 -08005257AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5258 Vector< sp<Track> > *tracksToRemove
5259)
5260{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005261 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005262 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005263 bool doHwPause = false;
5264 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005265
5266 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005267 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005268 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005269 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005270 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005271 continue;
5272 }
5273
Eric Laurent5850c4c2016-11-10 13:04:31 -08005274 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005275#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005276 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005277#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005278 // Only consider last track started for volume and mixer state control.
5279 // In theory an older track could underrun and restart after the new one starts
5280 // but as we only care about the transition phase between two tracks on a
5281 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005282 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005283 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005284
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005285 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005286 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005287 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005288 doHwPause = true;
5289 mHwPaused = true;
5290 }
5291 tracksToRemove->add(track);
5292 } else if (track->isFlushPending()) {
5293 track->flushAck();
5294 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005295 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005296 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005297 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005298 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005299 if (last) {
5300 mLeftVolFloat = mRightVolFloat = -1.0;
5301 if (mHwPaused) {
5302 doHwResume = true;
5303 mHwPaused = false;
5304 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005305 }
5306 }
5307
Eric Laurent81784c32012-11-19 14:55:58 -08005308 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005309 // for all its buffers to be filled before processing it.
5310 // Allow draining the buffer in case the client
5311 // app does not call stop() and relies on underrun to stop:
5312 // hence the test on (track->mRetryCount > 1).
5313 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005314 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005315 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005316 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005317 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005318 minFrames = mNormalFrameCount;
5319 } else {
5320 minFrames = 1;
5321 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005322
Eric Laurentab5cdba2014-06-09 17:22:27 -07005323 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5324 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005325 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005326 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005327
5328 if (track->mFillingUpStatus == Track::FS_FILLED) {
5329 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005330 if (last) {
5331 // make sure processVolume_l() will apply new volume even if 0
5332 mLeftVolFloat = mRightVolFloat = -1.0;
5333 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005334 if (!mHwSupportsPause) {
5335 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005336 }
5337 }
5338
5339 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005340 processVolume_l(track, last);
5341 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005342 sp<Track> previousTrack = mPreviousTrack.promote();
5343 if (previousTrack != 0) {
5344 if (track != previousTrack.get()) {
5345 // Flush any data still being written from last track
5346 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005347 // Invalidate previous track to force a seek when resuming.
5348 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005349 }
5350 }
5351 mPreviousTrack = track;
5352
Eric Laurentd595b7c2013-04-03 17:27:56 -07005353 // reset retry count
5354 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005355 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005356 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005357 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005358 doHwResume = true;
5359 mHwPaused = false;
5360 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005361 }
Eric Laurent81784c32012-11-19 14:55:58 -08005362 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005363 // clear effect chain input buffer if the last active track started underruns
5364 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005365 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 mEffectChains[0]->clearInputBuffer();
5367 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005368 if (track->isStopping_1()) {
5369 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005370 if (last && mHwPaused) {
5371 doHwResume = true;
5372 mHwPaused = false;
5373 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005374 }
5375 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5376 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005377 // We have consumed all the buffers of this track.
5378 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005379 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005380 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005381 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5382 } else {
5383 audioHALFrames = 0;
5384 }
5385
Andy Hung818e7a32016-02-16 18:08:07 -08005386 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005387 if (mStandby || !last ||
5388 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005389 if (track->isStopping_2()) {
5390 track->mState = TrackBase::STOPPED;
5391 }
Eric Laurent81784c32012-11-19 14:55:58 -08005392 if (track->isStopped()) {
5393 track->reset();
5394 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005395 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005396 }
5397 } else {
5398 // No buffers for this track. Give it a few chances to
5399 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005400 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005401 if (--(track->mRetryCount) <= 0) {
5402 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005403 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005404 // indicate to client process that the track was disabled because of underrun;
5405 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005406 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005407 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005408 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5409 "minFrames = %u, mFormat = %#x",
5410 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005411 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005412 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005413 doHwPause = true;
5414 mHwPaused = true;
5415 }
Eric Laurent81784c32012-11-19 14:55:58 -08005416 }
5417 }
5418 }
5419 }
5420
Eric Laurentd1f69b02014-12-15 14:33:13 -08005421 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005422 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005423 for (size_t i = 0; i < mTracks.size(); i++) {
5424 if (mTracks[i]->isFlushPending()) {
5425 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005426 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005427 }
5428 }
5429 }
5430
5431 // make sure the pause/flush/resume sequence is executed in the right order.
5432 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5433 // before flush and then resume HW. This can happen in case of pause/flush/resume
5434 // if resume is received before pause is executed.
5435 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005436 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005437 status_t result = mOutput->stream->pause();
5438 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005439 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005440 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005441 flushHw_l();
5442 }
5443 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005444 status_t result = mOutput->stream->resume();
5445 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005446 }
Eric Laurent81784c32012-11-19 14:55:58 -08005447 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005449
5450 return mixerStatus;
5451}
5452
5453void AudioFlinger::DirectOutputThread::threadLoop_mix()
5454{
Eric Laurent81784c32012-11-19 14:55:58 -08005455 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005456 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005457 // output audio to hardware
5458 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005459 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005460 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005461 status_t status = mActiveTrack->getNextBuffer(&buffer);
5462 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005463 // no need to pad with 0 for compressed audio
5464 if (audio_has_proportional_frames(mFormat)) {
5465 memset(curBuf, 0, frameCount * mFrameSize);
5466 }
Eric Laurent81784c32012-11-19 14:55:58 -08005467 break;
5468 }
5469 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5470 frameCount -= buffer.frameCount;
5471 curBuf += buffer.frameCount * mFrameSize;
5472 mActiveTrack->releaseBuffer(&buffer);
5473 }
Andy Hung2098f272014-02-27 14:00:06 -08005474 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005475 mSleepTimeUs = 0;
5476 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005478}
5479
5480void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5481{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005482 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005483 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005484 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005485 return;
5486 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005487 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005488 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005489 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005490 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005491 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005492 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005493 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005494 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005495 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005496 }
5497}
5498
Eric Laurentd1f69b02014-12-15 14:33:13 -08005499void AudioFlinger::DirectOutputThread::threadLoop_exit()
5500{
5501 {
5502 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005503 for (size_t i = 0; i < mTracks.size(); i++) {
5504 if (mTracks[i]->isFlushPending()) {
5505 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005506 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005507 }
5508 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005509 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005510 flushHw_l();
5511 }
5512 }
5513 PlaybackThread::threadLoop_exit();
5514}
5515
5516// must be called with thread mutex locked
5517bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5518{
5519 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005520 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005521
vivek mehta9cd7ad12016-03-17 00:18:29 -07005522 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5523 return !mStandby;
5524 }
5525
Eric Laurentd1f69b02014-12-15 14:33:13 -08005526 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5527 // after a timeout and we will enter standby then.
5528 if (mTracks.size() > 0) {
5529 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005530 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5531 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005532 }
5533
Eric Laurent5cff4032015-05-26 13:49:58 -07005534 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005535}
5536
Eric Laurent10351942014-05-08 18:49:52 -07005537// checkForNewParameter_l() must be called with ThreadBase::mLock held
5538bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5539 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005540{
5541 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005542 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005543
Eric Laurent10351942014-05-08 18:49:52 -07005544 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005545
Eric Laurent10351942014-05-08 18:49:52 -07005546 AudioParameter param = AudioParameter(keyValuePair);
5547 int value;
5548 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5549 // forward device change to effects that have requested to be
5550 // aware of attached audio device.
5551 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005552 a2dpDeviceChanged =
5553 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005554 mOutDevice = value;
5555 for (size_t i = 0; i < mEffectChains.size(); i++) {
5556 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005557 }
5558 }
Eric Laurent81784c32012-11-19 14:55:58 -08005559 }
Eric Laurent10351942014-05-08 18:49:52 -07005560 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5561 // do not accept frame count changes if tracks are open as the track buffer
5562 // size depends on frame count and correct behavior would not be garantied
5563 // if frame count is changed after track creation
5564 if (!mTracks.isEmpty()) {
5565 status = INVALID_OPERATION;
5566 } else {
5567 reconfig = true;
5568 }
5569 }
5570 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005571 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005572 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005573 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005574 mStandby = true;
5575 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005576 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005577 }
5578 if (status == NO_ERROR && reconfig) {
5579 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005580 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005581 }
5582 }
5583
Eric Laurent42537be2016-01-08 17:16:42 -08005584 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005585}
5586
5587uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5588{
5589 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005590 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005591 time = PlaybackThread::activeSleepTimeUs();
5592 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005593 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005594 }
5595 return time;
5596}
5597
5598uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5599{
5600 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005601 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005602 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5603 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005604 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005605 }
5606 return time;
5607}
5608
5609uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5610{
5611 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005612 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005613 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5614 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005615 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
5617 return time;
5618}
5619
5620void AudioFlinger::DirectOutputThread::cacheParameters_l()
5621{
5622 PlaybackThread::cacheParameters_l();
5623
5624 // use shorter standby delay as on normal output to release
5625 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005626 // no delay on outputs with HW A/V sync
5627 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005628 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005629 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005630 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005631 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005632 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005633 }
Eric Laurent81784c32012-11-19 14:55:58 -08005634}
5635
Eric Laurente659ef42014-09-29 13:06:46 -07005636void AudioFlinger::DirectOutputThread::flushHw_l()
5637{
Phil Burk062e67a2015-02-11 13:40:50 -08005638 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005639 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005640 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005641 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005642}
5643
Andy Hung10cbff12017-02-21 17:30:14 -08005644int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5645 // If a VolumeShaper is active, we must wake up periodically to update volume.
5646 const int64_t NS_PER_MS = 1000000;
5647 return mVolumeShaperActive ?
5648 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5649}
5650
Eric Laurent81784c32012-11-19 14:55:58 -08005651// ----------------------------------------------------------------------------
5652
Eric Laurentbfb1b832013-01-07 09:53:42 -08005653AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005654 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005655 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005656 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005657 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005658 mDrainSequence(0),
5659 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005660{
5661}
5662
5663AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5664{
5665}
5666
5667void AudioFlinger::AsyncCallbackThread::onFirstRef()
5668{
5669 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5670}
5671
5672bool AudioFlinger::AsyncCallbackThread::threadLoop()
5673{
5674 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005675 uint32_t writeAckSequence;
5676 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005677 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005678
5679 {
5680 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005681 while (!((mWriteAckSequence & 1) ||
5682 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005683 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005684 exitPending())) {
5685 mWaitWorkCV.wait(mLock);
5686 }
5687
Eric Laurentbfb1b832013-01-07 09:53:42 -08005688 if (exitPending()) {
5689 break;
5690 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005691 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5692 mWriteAckSequence, mDrainSequence);
5693 writeAckSequence = mWriteAckSequence;
5694 mWriteAckSequence &= ~1;
5695 drainSequence = mDrainSequence;
5696 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005697 asyncError = mAsyncError;
5698 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005699 }
5700 {
Eric Laurent4de95592013-09-26 15:28:21 -07005701 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5702 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005703 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005704 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005705 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005706 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005707 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005709 if (asyncError) {
5710 playbackThread->onAsyncError();
5711 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005712 }
5713 }
5714 }
5715 return false;
5716}
5717
5718void AudioFlinger::AsyncCallbackThread::exit()
5719{
5720 ALOGV("AsyncCallbackThread::exit");
5721 Mutex::Autolock _l(mLock);
5722 requestExit();
5723 mWaitWorkCV.broadcast();
5724}
5725
Eric Laurent3b4529e2013-09-05 18:09:19 -07005726void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005727{
5728 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005729 // bit 0 is cleared
5730 mWriteAckSequence = sequence << 1;
5731}
5732
5733void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5734{
5735 Mutex::Autolock _l(mLock);
5736 // ignore unexpected callbacks
5737 if (mWriteAckSequence & 2) {
5738 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 mWaitWorkCV.signal();
5740 }
5741}
5742
Eric Laurent3b4529e2013-09-05 18:09:19 -07005743void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744{
5745 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005746 // bit 0 is cleared
5747 mDrainSequence = sequence << 1;
5748}
5749
5750void AudioFlinger::AsyncCallbackThread::resetDraining()
5751{
5752 Mutex::Autolock _l(mLock);
5753 // ignore unexpected callbacks
5754 if (mDrainSequence & 2) {
5755 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005756 mWaitWorkCV.signal();
5757 }
5758}
5759
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005760void AudioFlinger::AsyncCallbackThread::setAsyncError()
5761{
5762 Mutex::Autolock _l(mLock);
5763 mAsyncError = true;
5764 mWaitWorkCV.signal();
5765}
5766
Eric Laurentbfb1b832013-01-07 09:53:42 -08005767
5768// ----------------------------------------------------------------------------
5769AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005770 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5771 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005772 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5773 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005774{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005775 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005776 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005777 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005778}
5779
Eric Laurentbfb1b832013-01-07 09:53:42 -08005780void AudioFlinger::OffloadThread::threadLoop_exit()
5781{
5782 if (mFlushPending || mHwPaused) {
5783 // If a flush is pending or track was paused, just discard buffered data
5784 flushHw_l();
5785 } else {
5786 mMixerStatus = MIXER_DRAIN_ALL;
5787 threadLoop_drain();
5788 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005789 if (mUseAsyncWrite) {
5790 ALOG_ASSERT(mCallbackThread != 0);
5791 mCallbackThread->exit();
5792 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005793 PlaybackThread::threadLoop_exit();
5794}
5795
5796AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5797 Vector< sp<Track> > *tracksToRemove
5798)
5799{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005800 size_t count = mActiveTracks.size();
5801
5802 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005803 bool doHwPause = false;
5804 bool doHwResume = false;
5805
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005806 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005807
Eric Laurentbfb1b832013-01-07 09:53:42 -08005808 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005809 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005810 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005811#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005813#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005814 // Only consider last track started for volume and mixer state control.
5815 // In theory an older track could underrun and restart after the new one starts
5816 // but as we only care about the transition phase between two tracks on a
5817 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005818 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005819 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005820
Haynes Mathew George7844f672014-01-15 12:32:55 -08005821 if (track->isInvalid()) {
5822 ALOGW("An invalidated track shouldn't be in active list");
5823 tracksToRemove->add(track);
5824 continue;
5825 }
5826
5827 if (track->mState == TrackBase::IDLE) {
5828 ALOGW("An idle track shouldn't be in active list");
5829 continue;
5830 }
5831
Eric Laurentbfb1b832013-01-07 09:53:42 -08005832 if (track->isPausing()) {
5833 track->setPaused();
5834 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005835 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005836 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005837 mHwPaused = true;
5838 }
5839 // If we were part way through writing the mixbuffer to
5840 // the HAL we must save this until we resume
5841 // BUG - this will be wrong if a different track is made active,
5842 // in that case we want to discard the pending data in the
5843 // mixbuffer and tell the client to present it again when the
5844 // track is resumed
5845 mPausedWriteLength = mCurrentWriteLength;
5846 mPausedBytesRemaining = mBytesRemaining;
5847 mBytesRemaining = 0; // stop writing
5848 }
5849 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005850 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005851 if (track->isStopping_1()) {
5852 track->mRetryCount = kMaxTrackStopRetriesOffload;
5853 } else {
5854 track->mRetryCount = kMaxTrackRetriesOffload;
5855 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005856 track->flushAck();
5857 if (last) {
5858 mFlushPending = true;
5859 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005860 } else if (track->isResumePending()){
5861 track->resumeAck();
5862 if (last) {
5863 if (mPausedBytesRemaining) {
5864 // Need to continue write that was interrupted
5865 mCurrentWriteLength = mPausedWriteLength;
5866 mBytesRemaining = mPausedBytesRemaining;
5867 mPausedBytesRemaining = 0;
5868 }
5869 if (mHwPaused) {
5870 doHwResume = true;
5871 mHwPaused = false;
5872 // threadLoop_mix() will handle the case that we need to
5873 // resume an interrupted write
5874 }
5875 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005876 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005877
Eric Laurent3df841a2016-07-15 15:15:40 -07005878 mLeftVolFloat = mRightVolFloat = -1.0;
5879
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005880 // Do not handle new data in this iteration even if track->framesReady()
5881 mixerStatus = MIXER_TRACKS_ENABLED;
5882 }
5883 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005884 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005885 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005886 if (track->mFillingUpStatus == Track::FS_FILLED) {
5887 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005888 if (last) {
5889 // make sure processVolume_l() will apply new volume even if 0
5890 mLeftVolFloat = mRightVolFloat = -1.0;
5891 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005892 }
5893
5894 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005895 sp<Track> previousTrack = mPreviousTrack.promote();
5896 if (previousTrack != 0) {
5897 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005898 // Flush any data still being written from last track
5899 mBytesRemaining = 0;
5900 if (mPausedBytesRemaining) {
5901 // Last track was paused so we also need to flush saved
5902 // mixbuffer state and invalidate track so that it will
5903 // re-submit that unwritten data when it is next resumed
5904 mPausedBytesRemaining = 0;
5905 // Invalidate is a bit drastic - would be more efficient
5906 // to have a flag to tell client that some of the
5907 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005908 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005909 }
5910 // flush data already sent to the DSP if changing audio session as audio
5911 // comes from a different source. Also invalidate previous track to force a
5912 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005913 if (previousTrack->sessionId() != track->sessionId()) {
5914 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005915 }
5916 }
5917 }
5918 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005919 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005920 if (track->isStopping_1()) {
5921 track->mRetryCount = kMaxTrackStopRetriesOffload;
5922 } else {
5923 track->mRetryCount = kMaxTrackRetriesOffload;
5924 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005925 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005926 mixerStatus = MIXER_TRACKS_READY;
5927 }
5928 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005929 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005930 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005931 if (--(track->mRetryCount) <= 0) {
5932 // Hardware buffer can hold a large amount of audio so we must
5933 // wait for all current track's data to drain before we say
5934 // that the track is stopped.
5935 if (mBytesRemaining == 0) {
5936 // Only start draining when all data in mixbuffer
5937 // has been written
5938 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5939 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5940 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5941 if (last && !mStandby) {
5942 // do not modify drain sequence if we are already draining. This happens
5943 // when resuming from pause after drain.
5944 if ((mDrainSequence & 1) == 0) {
5945 mSleepTimeUs = 0;
5946 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5947 mixerStatus = MIXER_DRAIN_TRACK;
5948 mDrainSequence += 2;
5949 }
5950 if (mHwPaused) {
5951 // It is possible to move from PAUSED to STOPPING_1 without
5952 // a resume so we must ensure hardware is running
5953 doHwResume = true;
5954 mHwPaused = false;
5955 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005956 }
5957 }
Eric Laurente93cc032016-05-05 10:15:10 -07005958 } else if (last) {
5959 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5960 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005961 }
5962 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005963 // Drain has completed or we are in standby, signal presentation complete
5964 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005965 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005966 uint32_t latency = 0;
5967 status_t result = mOutput->stream->getLatency(&latency);
5968 ALOGE_IF(result != OK,
5969 "Error when retrieving output stream latency: %d", result);
5970 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005971 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005972 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005973 track->presentationComplete(framesWritten, audioHALFrames);
5974 track->reset();
5975 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07005976 // DIRECT and OFFLOADED stop resets frame counts.
5977 if (!mUseAsyncWrite) {
5978 // If we don't get explicit drain notification we must
5979 // register discontinuity regardless of whether this is
5980 // the previous (!last) or the upcoming (last) track
5981 // to avoid skipping the discontinuity.
5982 mTimestampVerifier.discontinuity();
5983 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005984 }
5985 } else {
5986 // No buffers for this track. Give it a few chances to
5987 // fill a buffer, then remove it from active list.
5988 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005989 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005990 uint64_t position = 0;
5991 struct timespec unused;
5992 // The running check restarts the retry counter at least once.
5993 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5994 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5995 running = true;
5996 mOffloadUnderrunPosition = position;
5997 }
5998 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005999 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6000 (long long)position, (long long)mOffloadUnderrunPosition);
6001 }
6002 if (running) { // still running, give us more time.
6003 track->mRetryCount = kMaxTrackRetriesOffload;
6004 } else {
6005 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
6006 track->name());
6007 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006008 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006009 // it will then automatically call start() when data is available
6010 track->disable();
6011 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006012 } else if (last){
6013 mixerStatus = MIXER_TRACKS_ENABLED;
6014 }
6015 }
6016 }
6017 // compute volume for this track
6018 processVolume_l(track, last);
6019 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006020
Eric Laurentea0fade2013-10-04 16:23:48 -07006021 // make sure the pause/flush/resume sequence is executed in the right order.
6022 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6023 // before flush and then resume HW. This can happen in case of pause/flush/resume
6024 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006025 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006026 status_t result = mOutput->stream->pause();
6027 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006028 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006029 if (mFlushPending) {
6030 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006031 }
Eric Laurentfd477972013-10-25 18:10:40 -07006032 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006033 status_t result = mOutput->stream->resume();
6034 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006035 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006036
Eric Laurentbfb1b832013-01-07 09:53:42 -08006037 // remove all the tracks that need to be...
6038 removeTracks_l(*tracksToRemove);
6039
6040 return mixerStatus;
6041}
6042
Eric Laurentbfb1b832013-01-07 09:53:42 -08006043// must be called with thread mutex locked
6044bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6045{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006046 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6047 mWriteAckSequence, mDrainSequence);
6048 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006049 return true;
6050 }
6051 return false;
6052}
6053
Eric Laurentbfb1b832013-01-07 09:53:42 -08006054bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6055{
6056 Mutex::Autolock _l(mLock);
6057 return waitingAsyncCallback_l();
6058}
6059
6060void AudioFlinger::OffloadThread::flushHw_l()
6061{
Eric Laurente659ef42014-09-29 13:06:46 -07006062 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006063 // Flush anything still waiting in the mixbuffer
6064 mCurrentWriteLength = 0;
6065 mBytesRemaining = 0;
6066 mPausedWriteLength = 0;
6067 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006068 // reset bytes written count to reflect that DSP buffers are empty after flush.
6069 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006070 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006071
Eric Laurentbfb1b832013-01-07 09:53:42 -08006072 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006073 // discard any pending drain or write ack by incrementing sequence
6074 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6075 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006076 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006077 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6078 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006079 }
6080}
6081
Haynes Mathew George05317d22016-05-03 16:34:26 -07006082void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6083{
6084 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006085 if (PlaybackThread::invalidateTracks_l(streamType)) {
6086 mFlushPending = true;
6087 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006088}
6089
Eric Laurentbfb1b832013-01-07 09:53:42 -08006090// ----------------------------------------------------------------------------
6091
Eric Laurent81784c32012-11-19 14:55:58 -08006092AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006093 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006094 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006095 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006096 mWaitTimeMs(UINT_MAX)
6097{
6098 addOutputTrack(mainThread);
6099}
6100
6101AudioFlinger::DuplicatingThread::~DuplicatingThread()
6102{
6103 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6104 mOutputTracks[i]->destroy();
6105 }
6106}
6107
6108void AudioFlinger::DuplicatingThread::threadLoop_mix()
6109{
6110 // mix buffers...
6111 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006112 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006113 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006114 if (mMixerBufferValid) {
6115 memset(mMixerBuffer, 0, mMixerBufferSize);
6116 } else {
6117 memset(mSinkBuffer, 0, mSinkBufferSize);
6118 }
Eric Laurent81784c32012-11-19 14:55:58 -08006119 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006120 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006121 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006122 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006123 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006124}
6125
6126void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6127{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006128 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006129 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006130 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006131 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006132 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006133 }
6134 } else if (mBytesWritten != 0) {
6135 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6136 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006137 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006138 } else {
6139 // flush remaining overflow buffers in output tracks
6140 writeFrames = 0;
6141 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006142 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006143 }
6144}
6145
Eric Laurentbfb1b832013-01-07 09:53:42 -08006146ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006147{
6148 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006149 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6150
6151 // Consider the first OutputTrack for timestamp and frame counting.
6152
6153 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6154 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6155 // we always claim success.
6156 if (i == 0) {
6157 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6158 ALOGD_IF(correction != 0 && writeFrames != 0,
6159 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6160 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6161 mFramesWritten -= correction;
6162 }
6163
6164 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006165 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006166 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006167 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006168}
6169
6170void AudioFlinger::DuplicatingThread::threadLoop_standby()
6171{
6172 // DuplicatingThread implements standby by stopping all tracks
6173 for (size_t i = 0; i < outputTracks.size(); i++) {
6174 outputTracks[i]->stop();
6175 }
6176}
6177
Andy Hung1bc088a2018-02-09 15:57:31 -08006178void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6179{
6180 MixerThread::dumpInternals(fd, args);
6181
6182 std::stringstream ss;
6183 const size_t numTracks = mOutputTracks.size();
6184 ss << " " << numTracks << " OutputTracks";
6185 if (numTracks > 0) {
6186 ss << ":";
6187 for (const auto &track : mOutputTracks) {
6188 const sp<ThreadBase> thread = track->thread().promote();
6189 ss << " (" << track->name() << " : ";
6190 if (thread.get() != nullptr) {
6191 ss << thread.get() << ", " << thread->id();
6192 } else {
6193 ss << "null";
6194 }
6195 ss << ")";
6196 }
6197 }
6198 ss << "\n";
6199 std::string result = ss.str();
6200 write(fd, result.c_str(), result.size());
6201}
6202
Eric Laurent81784c32012-11-19 14:55:58 -08006203void AudioFlinger::DuplicatingThread::saveOutputTracks()
6204{
6205 outputTracks = mOutputTracks;
6206}
6207
6208void AudioFlinger::DuplicatingThread::clearOutputTracks()
6209{
6210 outputTracks.clear();
6211}
6212
6213void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6214{
6215 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006216 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6217 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6218 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6219 const size_t frameCount =
6220 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6221 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6222 // from different OutputTracks and their associated MixerThreads (e.g. one may
6223 // nearly empty and the other may be dropping data).
6224
6225 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006226 this,
6227 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006228 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006229 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006230 frameCount,
6231 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006232 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6233 if (status != NO_ERROR) {
6234 ALOGE("addOutputTrack() initCheck failed %d", status);
6235 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006236 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006237 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6238 mOutputTracks.add(outputTrack);
6239 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6240 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006241}
6242
6243void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6244{
6245 Mutex::Autolock _l(mLock);
6246 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6247 if (mOutputTracks[i]->thread() == thread) {
6248 mOutputTracks[i]->destroy();
6249 mOutputTracks.removeAt(i);
6250 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006251 if (thread->getOutput() == mOutput) {
6252 mOutput = NULL;
6253 }
Eric Laurent81784c32012-11-19 14:55:58 -08006254 return;
6255 }
6256 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006257 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006258}
6259
6260// caller must hold mLock
6261void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6262{
6263 mWaitTimeMs = UINT_MAX;
6264 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6265 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6266 if (strong != 0) {
6267 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6268 if (waitTimeMs < mWaitTimeMs) {
6269 mWaitTimeMs = waitTimeMs;
6270 }
6271 }
6272 }
6273}
6274
6275
6276bool AudioFlinger::DuplicatingThread::outputsReady(
6277 const SortedVector< sp<OutputTrack> > &outputTracks)
6278{
6279 for (size_t i = 0; i < outputTracks.size(); i++) {
6280 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6281 if (thread == 0) {
6282 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6283 outputTracks[i].get());
6284 return false;
6285 }
6286 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6287 // see note at standby() declaration
6288 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6289 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6290 thread.get());
6291 return false;
6292 }
6293 }
6294 return true;
6295}
6296
Kevin Rocard12381092018-04-11 09:19:59 -07006297void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6298 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006299{
Kevin Rocard12381092018-04-11 09:19:59 -07006300 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6301 outputTrack->setMetadatas(metadata.tracks);
6302 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006303}
6304
Eric Laurent81784c32012-11-19 14:55:58 -08006305uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6306{
6307 return (mWaitTimeMs * 1000) / 2;
6308}
6309
6310void AudioFlinger::DuplicatingThread::cacheParameters_l()
6311{
6312 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6313 updateWaitTime_l();
6314
6315 MixerThread::cacheParameters_l();
6316}
6317
Eric Laurent6acd1d42017-01-04 14:23:29 -08006318
Eric Laurent81784c32012-11-19 14:55:58 -08006319// ----------------------------------------------------------------------------
6320// Record
6321// ----------------------------------------------------------------------------
6322
6323AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6324 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006325 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006326 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006327 audio_devices_t inDevice,
6328 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006329 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006330 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006331 mInput(input),
6332 mActiveTracks(&this->mLocalLog),
6333 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006334 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006335 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006336 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6337 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006338 // mFastCapture below
6339 , mFastCaptureFutex(0)
6340 // mInputSource
6341 // mPipeSink
6342 // mPipeSource
6343 , mPipeFramesP2(0)
6344 // mPipeMemory
6345 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006346 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006347 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006348{
Glenn Kastend7dca052015-03-05 16:05:54 -08006349 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6350 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006351
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006352 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006353
6354 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006355 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006356 size_t numCounterOffers = 0;
6357 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006358#if !LOG_NDEBUG
6359 ssize_t index =
6360#else
6361 (void)
6362#endif
6363 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006364 ALOG_ASSERT(index == 0);
6365
6366 // initialize fast capture depending on configuration
6367 bool initFastCapture;
6368 switch (kUseFastCapture) {
6369 case FastCapture_Never:
6370 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006371 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006372 break;
6373 case FastCapture_Always:
6374 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006375 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006376 break;
6377 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006378 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006379 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6380 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6381 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006382 break;
6383 // case FastCapture_Dynamic:
6384 }
6385
6386 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006387 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006388 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006389 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6390 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006391 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006392 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006393 const sp<MemoryDealer> roHeap(readOnlyHeap());
6394 sp<IMemory> pipeMemory;
6395 if ((roHeap == 0) ||
6396 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006397 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6398 ALOGE("not enough memory for pipe buffer size=%zu; "
6399 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6400 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6401 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006402 goto failed;
6403 }
6404 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6405 memset(pipeBuffer, 0, pipeSize);
6406 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6407 const NBAIO_Format offers[1] = {format};
6408 size_t numCounterOffers = 0;
6409 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6410 ALOG_ASSERT(index == 0);
6411 mPipeSink = pipe;
6412 PipeReader *pipeReader = new PipeReader(*pipe);
6413 numCounterOffers = 0;
6414 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6415 ALOG_ASSERT(index == 0);
6416 mPipeSource = pipeReader;
6417 mPipeFramesP2 = pipeFramesP2;
6418 mPipeMemory = pipeMemory;
6419
6420 // create fast capture
6421 mFastCapture = new FastCapture();
6422 FastCaptureStateQueue *sq = mFastCapture->sq();
6423#ifdef STATE_QUEUE_DUMP
6424 // FIXME
6425#endif
6426 FastCaptureState *state = sq->begin();
6427 state->mCblk = NULL;
6428 state->mInputSource = mInputSource.get();
6429 state->mInputSourceGen++;
6430 state->mPipeSink = pipe;
6431 state->mPipeSinkGen++;
6432 state->mFrameCount = mFrameCount;
6433 state->mCommand = FastCaptureState::COLD_IDLE;
6434 // already done in constructor initialization list
6435 //mFastCaptureFutex = 0;
6436 state->mColdFutexAddr = &mFastCaptureFutex;
6437 state->mColdGen++;
6438 state->mDumpState = &mFastCaptureDumpState;
6439#ifdef TEE_SINK
6440 // FIXME
6441#endif
6442 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6443 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6444 sq->end();
6445 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6446
6447 // start the fast capture
6448 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6449 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006450 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006451 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006452#ifdef AUDIO_WATCHDOG
6453 // FIXME
6454#endif
6455
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006456 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006457 }
Andy Hung8946a282018-04-19 20:04:56 -07006458#ifdef TEE_SINK
6459 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6460 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6461#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006462failed: ;
6463
6464 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006465}
6466
Eric Laurent81784c32012-11-19 14:55:58 -08006467AudioFlinger::RecordThread::~RecordThread()
6468{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006469 if (mFastCapture != 0) {
6470 FastCaptureStateQueue *sq = mFastCapture->sq();
6471 FastCaptureState *state = sq->begin();
6472 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6473 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6474 if (old == -1) {
6475 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6476 }
6477 }
6478 state->mCommand = FastCaptureState::EXIT;
6479 sq->end();
6480 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6481 mFastCapture->join();
6482 mFastCapture.clear();
6483 }
6484 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006485 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006486 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006487}
6488
6489void AudioFlinger::RecordThread::onFirstRef()
6490{
Glenn Kastend7dca052015-03-05 16:05:54 -08006491 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006492}
6493
Eric Laurent555530a2017-02-07 18:17:24 -08006494void AudioFlinger::RecordThread::preExit()
6495{
6496 ALOGV(" preExit()");
6497 Mutex::Autolock _l(mLock);
6498 for (size_t i = 0; i < mTracks.size(); i++) {
6499 sp<RecordTrack> track = mTracks[i];
6500 track->invalidate();
6501 }
6502 mActiveTracks.clear();
6503 mStartStopCond.broadcast();
6504}
6505
Eric Laurent81784c32012-11-19 14:55:58 -08006506bool AudioFlinger::RecordThread::threadLoop()
6507{
Eric Laurent81784c32012-11-19 14:55:58 -08006508 nsecs_t lastWarning = 0;
6509
6510 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006511
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006512reacquire_wakelock:
6513 sp<RecordTrack> activeTrack;
6514 {
6515 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006516 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006517 }
6518
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006519 // used to request a deferred sleep, to be executed later while mutex is unlocked
6520 uint32_t sleepUs = 0;
6521
6522 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006523 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006524 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006525
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006526 // activeTracks accumulates a copy of a subset of mActiveTracks
6527 Vector< sp<RecordTrack> > activeTracks;
6528
Glenn Kasten735f45f2014-08-18 15:51:59 -07006529 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006530 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006531
Glenn Kasten735f45f2014-08-18 15:51:59 -07006532 // reference to a fast track which is about to be removed
6533 sp<RecordTrack> fastTrackToRemove;
6534
Eric Laurent81784c32012-11-19 14:55:58 -08006535 { // scope for mLock
6536 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006537
Eric Laurent021cf962014-05-13 10:18:14 -07006538 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006539
Eric Laurent000a4192014-01-29 15:17:32 -08006540 // check exitPending here because checkForNewParameters_l() and
6541 // checkForNewParameters_l() can temporarily release mLock
6542 if (exitPending()) {
6543 break;
6544 }
6545
Eric Laurent5c25d562016-07-13 17:17:45 -07006546 // sleep with mutex unlocked
6547 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006548 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006549 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6550 ATRACE_END();
6551 sleepUs = 0;
6552 continue;
6553 }
6554
Glenn Kasten2b806402013-11-20 16:37:38 -08006555 // if no active track(s), then standby and release wakelock
6556 size_t size = mActiveTracks.size();
6557 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006558 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006559 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006560 releaseWakeLock_l();
6561 ALOGV("RecordThread: loop stopping");
6562 // go to sleep
6563 mWaitWorkCV.wait(mLock);
6564 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006565 goto reacquire_wakelock;
6566 }
6567
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006568 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006569 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006570 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006571
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006572 activeTrack = mActiveTracks[i];
6573 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006574 if (activeTrack->isFastTrack()) {
6575 ALOG_ASSERT(fastTrackToRemove == 0);
6576 fastTrackToRemove = activeTrack;
6577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006578 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006579 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006580 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006581 continue;
6582 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006583
6584 TrackBase::track_state activeTrackState = activeTrack->mState;
6585 switch (activeTrackState) {
6586
6587 case TrackBase::PAUSING:
6588 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006589 doBroadcast = true;
6590 size--;
6591 continue;
6592
6593 case TrackBase::STARTING_1:
6594 sleepUs = 10000;
6595 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006596 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 continue;
6598
6599 case TrackBase::STARTING_2:
6600 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006601 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006602 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006603 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006604 break;
6605
6606 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006607 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006608 break;
6609
6610 case TrackBase::IDLE:
6611 i++;
6612 continue;
6613
6614 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006615 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006616 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006617
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006618 activeTracks.add(activeTrack);
6619 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006620
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006621 if (activeTrack->isFastTrack()) {
6622 ALOG_ASSERT(!mFastTrackAvail);
6623 ALOG_ASSERT(fastTrack == 0);
6624 fastTrack = activeTrack;
6625 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006626 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006627
Andy Hungdae27702016-10-31 14:01:16 -07006628 mActiveTracks.updatePowerState(this);
6629
Kevin Rocard069c2712018-03-29 19:09:14 -07006630 updateMetadata_l();
6631
Eric Laurent5c25d562016-07-13 17:17:45 -07006632 if (allStopped) {
6633 standbyIfNotAlreadyInStandby();
6634 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006635 if (doBroadcast) {
6636 mStartStopCond.broadcast();
6637 }
6638
6639 // sleep if there are no active tracks to process
6640 if (activeTracks.size() == 0) {
6641 if (sleepUs == 0) {
6642 sleepUs = kRecordThreadSleepUs;
6643 }
6644 continue;
6645 }
6646 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006647
Eric Laurent81784c32012-11-19 14:55:58 -08006648 lockEffectChains_l(effectChains);
6649 }
6650
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006651 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006652
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006653 size_t size = effectChains.size();
6654 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006655 // thread mutex is not locked, but effect chain is locked
6656 effectChains[i]->process_l();
6657 }
6658
Glenn Kasten735f45f2014-08-18 15:51:59 -07006659 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006660 if (mFastCapture != 0) {
6661 FastCaptureStateQueue *sq = mFastCapture->sq();
6662 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006663 bool didModify = false;
6664 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006665 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6666 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6667 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6668 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6669 if (old == -1) {
6670 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6671 }
6672 }
6673 state->mCommand = FastCaptureState::READ_WRITE;
6674#if 0 // FIXME
6675 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006676 FastThreadDumpState::kSamplingNforLowRamDevice :
6677 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006678#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006679 didModify = true;
6680 }
6681 audio_track_cblk_t *cblkOld = state->mCblk;
6682 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6683 if (cblkNew != cblkOld) {
6684 state->mCblk = cblkNew;
6685 // block until acked if removing a fast track
6686 if (cblkOld != NULL) {
6687 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6688 }
6689 didModify = true;
6690 }
6691 sq->end(didModify);
6692 if (didModify) {
6693 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006694#if 0
6695 if (kUseFastCapture == FastCapture_Dynamic) {
6696 mNormalSource = mPipeSource;
6697 }
6698#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006699 }
6700 }
6701
Glenn Kasten735f45f2014-08-18 15:51:59 -07006702 // now run the fast track destructor with thread mutex unlocked
6703 fastTrackToRemove.clear();
6704
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006705 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6706 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6707 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6708 // If destination is non-contiguous, first read past the nominal end of buffer, then
6709 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006710
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006711 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006712 ssize_t framesRead;
6713
6714 // If an NBAIO source is present, use it to read the normal capture's data
6715 if (mPipeSource != 0) {
6716 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006717 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006718
6719 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6720 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6721 // we immediately retry the read() to get data and prevent another overflow.
6722 for (int retries = 0; retries <= 2; ++retries) {
6723 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6724 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6725 framesToRead);
6726 if (framesRead != OVERRUN) break;
6727 }
6728
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006729 const ssize_t availableToRead = mPipeSource->availableToRead();
6730 if (availableToRead >= 0) {
6731 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6732 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6733 "more frames to read than fifo size, %zd > %zu",
6734 availableToRead, mPipeFramesP2);
6735 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6736 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6737 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6738 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006739 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6740 }
6741 if (framesRead < 0) {
6742 status_t status = (status_t) framesRead;
6743 switch (status) {
6744 case OVERRUN:
6745 ALOGW("overrun on read from pipe");
6746 framesRead = 0;
6747 break;
6748 case NEGOTIATE:
6749 ALOGE("re-negotiation is needed");
6750 framesRead = -1; // Will cause an attempt to recover.
6751 break;
6752 default:
6753 ALOGE("unknown error %d on read from pipe", status);
6754 break;
6755 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006756 }
6757 // otherwise use the HAL / AudioStreamIn directly
6758 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006759 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006760 size_t bytesRead;
6761 status_t result = mInput->stream->read(
6762 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006763 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006764 if (result < 0) {
6765 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006766 } else {
6767 framesRead = bytesRead / mFrameSize;
6768 }
6769 }
6770
Andy Hung3f0c9022016-01-15 17:49:46 -08006771 // Update server timestamp with server stats
6772 // systemTime() is optional if the hardware supports timestamps.
6773 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6774 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6775
6776 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006777 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006778 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006779 if (mStandby) {
6780 mTimestampVerifier.discontinuity();
6781 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006782 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6783 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6784 // Note: In general record buffers should tend to be empty in
6785 // a properly running pipeline.
6786 //
6787 // Also, it is not advantageous to call get_presentation_position during the read
6788 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006789
6790 mTimestampVerifier.add(mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
6791 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
6792 mSampleRate);
6793 } else {
6794 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006795 }
6796 }
6797 // Use this to track timestamp information
6798 // ALOGD("%s", mTimestamp.toString().c_str());
6799
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006800 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006801 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006802 // Force input into standby so that it tries to recover at next read attempt
6803 inputStandBy();
6804 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006805 }
6806 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006807 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006808 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006809 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006810
Andy Hung8946a282018-04-19 20:04:56 -07006811#ifdef TEE_SINK
6812 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6813#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006814 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006815 {
6816 size_t part1 = mRsmpInFramesP2 - rear;
6817 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006818 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006819 (framesRead - part1) * mFrameSize);
6820 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006821 }
6822 rear = mRsmpInRear += framesRead;
6823
6824 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006825
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006826 // loop over each active track
6827 for (size_t i = 0; i < size; i++) {
6828 activeTrack = activeTracks[i];
6829
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006830 // skip fast tracks, as those are handled directly by FastCapture
6831 if (activeTrack->isFastTrack()) {
6832 continue;
6833 }
6834
Andy Hung73c02e42015-03-29 01:13:58 -07006835 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006836 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6837
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006838 enum {
6839 OVERRUN_UNKNOWN,
6840 OVERRUN_TRUE,
6841 OVERRUN_FALSE
6842 } overrun = OVERRUN_UNKNOWN;
6843
6844 // loop over getNextBuffer to handle circular sink
6845 for (;;) {
6846
6847 activeTrack->mSink.frameCount = ~0;
6848 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6849 size_t framesOut = activeTrack->mSink.frameCount;
6850 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6851
Andy Hung73c02e42015-03-29 01:13:58 -07006852 // check available frames and handle overrun conditions
6853 // if the record track isn't draining fast enough.
6854 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006855 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006856 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6857 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006858 overrun = OVERRUN_TRUE;
6859 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006860 if (framesOut == 0 || framesIn == 0) {
6861 break;
6862 }
6863
Andy Hung6770c6f2015-04-07 13:43:36 -07006864 // Don't allow framesOut to be larger than what is possible with resampling
6865 // from framesIn.
6866 // This isn't strictly necessary but helps limit buffer resizing in
6867 // RecordBufferConverter. TODO: remove when no longer needed.
6868 framesOut = min(framesOut,
6869 destinationFramesPossible(
6870 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006871
6872 if (activeTrack->isDirect()) {
6873 // No RecordBufferConverter used for compressed formats. Pass
6874 // straight from RecordThread buffer to RecordTrack buffer.
6875 AudioBufferProvider::Buffer buffer;
6876 buffer.frameCount = framesOut;
6877 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6878 if (status == OK && buffer.frameCount != 0) {
6879 ALOGV_IF(buffer.frameCount != framesOut,
6880 "%s() read less than expected (%zu vs %zu)",
6881 __func__, buffer.frameCount, framesOut);
6882 framesOut = buffer.frameCount;
6883 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6884 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6885 } else {
6886 framesOut = 0;
6887 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6888 __func__, status, buffer.frameCount);
6889 }
6890 } else {
6891 // process frames from the RecordThread buffer provider to the RecordTrack
6892 // buffer
6893 framesOut = activeTrack->mRecordBufferConverter->convert(
6894 activeTrack->mSink.raw,
6895 activeTrack->mResamplerBufferProvider,
6896 framesOut);
6897 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006898
6899 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6900 overrun = OVERRUN_FALSE;
6901 }
6902
6903 if (activeTrack->mFramesToDrop == 0) {
6904 if (framesOut > 0) {
6905 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006906 // Sanitize before releasing if the track has no access to the source data
6907 // An idle UID receives silence from non virtual devices until active
6908 if (activeTrack->isSilenced()) {
6909 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6910 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006911 activeTrack->releaseBuffer(&activeTrack->mSink);
6912 }
6913 } else {
6914 // FIXME could do a partial drop of framesOut
6915 if (activeTrack->mFramesToDrop > 0) {
6916 activeTrack->mFramesToDrop -= framesOut;
6917 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006918 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006919 }
6920 } else {
6921 activeTrack->mFramesToDrop += framesOut;
6922 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6923 activeTrack->mSyncStartEvent->isCancelled()) {
6924 ALOGW("Synced record %s, session %d, trigger session %d",
6925 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6926 activeTrack->sessionId(),
6927 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006928 activeTrack->mSyncStartEvent->triggerSession() :
6929 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006930 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006931 }
6932 }
6933 }
6934
6935 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006936 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006937 }
6938 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006939
6940 switch (overrun) {
6941 case OVERRUN_TRUE:
6942 // client isn't retrieving buffers fast enough
6943 if (!activeTrack->setOverflow()) {
6944 nsecs_t now = systemTime();
6945 // FIXME should lastWarning per track?
6946 if ((now - lastWarning) > kWarningThrottleNs) {
6947 ALOGW("RecordThread: buffer overflow");
6948 lastWarning = now;
6949 }
6950 }
6951 break;
6952 case OVERRUN_FALSE:
6953 activeTrack->clearOverflow();
6954 break;
6955 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006956 break;
6957 }
6958
Andy Hung3f0c9022016-01-15 17:49:46 -08006959 // update frame information and push timestamp out
6960 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006961 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006962 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6963 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006964 }
6965
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006966unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006967 // enable changes in effect chain
6968 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006969 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006970 }
6971
Glenn Kasten93e471f2013-08-19 08:40:07 -07006972 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006973
6974 {
6975 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006976 for (size_t i = 0; i < mTracks.size(); i++) {
6977 sp<RecordTrack> track = mTracks[i];
6978 track->invalidate();
6979 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006980 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006981 mStartStopCond.broadcast();
6982 }
6983
6984 releaseWakeLock();
6985
6986 ALOGV("RecordThread %p exiting", this);
6987 return false;
6988}
6989
Glenn Kasten93e471f2013-08-19 08:40:07 -07006990void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006991{
6992 if (!mStandby) {
6993 inputStandBy();
6994 mStandby = true;
6995 }
6996}
6997
6998void AudioFlinger::RecordThread::inputStandBy()
6999{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007000 // Idle the fast capture if it's currently running
7001 if (mFastCapture != 0) {
7002 FastCaptureStateQueue *sq = mFastCapture->sq();
7003 FastCaptureState *state = sq->begin();
7004 if (!(state->mCommand & FastCaptureState::IDLE)) {
7005 state->mCommand = FastCaptureState::COLD_IDLE;
7006 state->mColdFutexAddr = &mFastCaptureFutex;
7007 state->mColdGen++;
7008 mFastCaptureFutex = 0;
7009 sq->end();
7010 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7011 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7012#if 0
7013 if (kUseFastCapture == FastCapture_Dynamic) {
7014 // FIXME
7015 }
7016#endif
7017#ifdef AUDIO_WATCHDOG
7018 // FIXME
7019#endif
7020 } else {
7021 sq->end(false /*didModify*/);
7022 }
7023 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007024 status_t result = mInput->stream->standby();
7025 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007026
7027 // If going into standby, flush the pipe source.
7028 if (mPipeSource.get() != nullptr) {
7029 const ssize_t flushed = mPipeSource->flush();
7030 if (flushed > 0) {
7031 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7032 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7033 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7034 }
7035 }
Eric Laurent81784c32012-11-19 14:55:58 -08007036}
7037
Glenn Kasten05997e22014-03-13 15:08:33 -07007038// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007039sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007040 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007041 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007042 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007043 audio_format_t format,
7044 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007045 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007046 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007047 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007048 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007049 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007050 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007051 status_t *status,
7052 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007053{
Glenn Kasten74935e42013-12-19 08:56:45 -08007054 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007055 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007056 sp<RecordTrack> track;
7057 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007058 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007059 audio_input_flags_t requestedFlags = *flags;
7060 uint32_t sampleRate;
7061
7062 lStatus = initCheck();
7063 if (lStatus != NO_ERROR) {
7064 ALOGE("createRecordTrack_l() audio driver not initialized");
7065 goto Exit;
7066 }
7067
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007068 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7069 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7070 lStatus = BAD_VALUE;
7071 goto Exit;
7072 }
7073
Eric Laurentf14db3c2017-12-08 14:20:36 -08007074 if (*pSampleRate == 0) {
7075 *pSampleRate = mSampleRate;
7076 }
7077 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007078
7079 // special case for FAST flag considered OK if fast capture is present
7080 if (hasFastCapture()) {
7081 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7082 }
7083
Eric Laurentf14db3c2017-12-08 14:20:36 -08007084 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007085 if ((*flags & inputFlags) != *flags) {
7086 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7087 " input flags (%08x)",
7088 *flags, inputFlags);
7089 *flags = (audio_input_flags_t)(*flags & inputFlags);
7090 }
Eric Laurent81784c32012-11-19 14:55:58 -08007091
Glenn Kasten90e58b12013-07-31 16:16:02 -07007092 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007093 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007094 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007095 // we formerly checked for a callback handler (non-0 tid),
7096 // but that is no longer required for TRANSFER_OBTAIN mode
7097 //
Glenn Kasten74105912014-07-03 12:28:53 -07007098 // frame count is not specified, or is exactly the pipe depth
7099 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007100 // PCM data
7101 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007102 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007103 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007104 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007105 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007106 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007107 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007108 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007109 hasFastCapture() &&
7110 // there are sufficient fast track slots available
7111 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007112 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007113 // check compatibility with audio effects.
7114 Mutex::Autolock _l(mLock);
7115 // Do not accept FAST flag if the session has software effects
7116 sp<EffectChain> chain = getEffectChain_l(sessionId);
7117 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007118 audio_input_flags_t old = *flags;
7119 chain->checkInputFlagCompatibility(flags);
7120 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007121 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7122 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007123 }
7124 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007125 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007126 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7127 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007128 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007129 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7130 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007131 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007132 this, frameCount, mFrameCount, mPipeFramesP2,
7133 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007134 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007135 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007136 }
7137 }
7138
Eric Laurentf14db3c2017-12-08 14:20:36 -08007139 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7140 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7141 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7142 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7143 lStatus = BAD_TYPE;
7144 goto Exit;
7145 }
7146
Glenn Kasten74105912014-07-03 12:28:53 -07007147 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007148 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007149 // fast track: frame count is exactly the pipe depth
7150 frameCount = mPipeFramesP2;
7151 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007152 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007153 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007154 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7155 // or 20 ms if there is a fast capture
7156 // TODO This could be a roundupRatio inline, and const
7157 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7158 * sampleRate + mSampleRate - 1) / mSampleRate;
7159 // minimum number of notification periods is at least kMinNotifications,
7160 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7161 static const size_t kMinNotifications = 3;
7162 static const uint32_t kMinMs = 30;
7163 // TODO This could be a roundupRatio inline
7164 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7165 // TODO This could be a roundupRatio inline
7166 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7167 maxNotificationFrames;
7168 const size_t minFrameCount = maxNotificationFrames *
7169 max(kMinNotifications, minNotificationsByMs);
7170 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007171 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7172 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007173 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007174 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007175 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007176 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007177
7178 { // scope for mLock
7179 Mutex::Autolock _l(mLock);
7180
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007181 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007182 format, channelMask, frameCount,
7183 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007184 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007185
Glenn Kasten03003332013-08-06 15:40:54 -07007186 lStatus = track->initCheck();
7187 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007188 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007189 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007190 goto Exit;
7191 }
7192 mTracks.add(track);
7193
Eric Laurent05067782016-06-01 18:27:28 -07007194 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007195 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7196 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7197 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007198 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007199 }
Eric Laurent81784c32012-11-19 14:55:58 -08007200 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007201
Eric Laurent81784c32012-11-19 14:55:58 -08007202 lStatus = NO_ERROR;
7203
7204Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007205 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007206 return track;
7207}
7208
7209status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7210 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007211 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007212{
7213 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7214 sp<ThreadBase> strongMe = this;
7215 status_t status = NO_ERROR;
7216
7217 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007218 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007219 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007220 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007221 triggerSession,
7222 recordTrack->sessionId(),
7223 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007224 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007225 // Sync event can be cancelled by the trigger session if the track is not in a
7226 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007227 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007228 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007229 } else {
7230 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007231 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007232 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007233 }
7234 }
7235
7236 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007237 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007238 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007239 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7240 if (recordTrack->mState == TrackBase::PAUSING) {
7241 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007242 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007243 } else {
7244 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007245 }
7246 return status;
7247 }
7248
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007249 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7250 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7251 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007252 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007253 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007254 status_t status = NO_ERROR;
7255 if (recordTrack->isExternalTrack()) {
7256 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007257 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007258 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007259 mLock.lock();
7260 // FIXME should verify that recordTrack is still in mActiveTracks
7261 if (status != NO_ERROR) {
7262 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007263 recordTrack->clearSyncStartEvent();
7264 ALOGV("RecordThread::start error %d", status);
7265 return status;
7266 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007267 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007268 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269 // Catch up with current buffer indices if thread is already running.
7270 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7271 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7272 // see previously buffered data before it called start(), but with greater risk of overrun.
7273
Andy Hung73c02e42015-03-29 01:13:58 -07007274 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007275 if (!recordTrack->isDirect()) {
7276 // clear any converter state as new data will be discontinuous
7277 recordTrack->mRecordBufferConverter->reset();
7278 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007279 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007280 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007281 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007282 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007283 ALOGV("Record failed to start");
7284 status = BAD_VALUE;
7285 goto startError;
7286 }
Eric Laurent81784c32012-11-19 14:55:58 -08007287 return status;
7288 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007289
Eric Laurent81784c32012-11-19 14:55:58 -08007290startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007291 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007292 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007293 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007294 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007295 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007296 return status;
7297}
7298
Eric Laurent81784c32012-11-19 14:55:58 -08007299void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7300{
7301 sp<SyncEvent> strongEvent = event.promote();
7302
7303 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007304 sp<RefBase> ptr = strongEvent->cookie().promote();
7305 if (ptr != 0) {
7306 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7307 recordTrack->handleSyncStartEvent(strongEvent);
7308 }
Eric Laurent81784c32012-11-19 14:55:58 -08007309 }
7310}
7311
Glenn Kastena8356f62013-07-25 14:37:52 -07007312bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007313 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007314 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007315 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007316 return false;
7317 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007318 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007319 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007320 // signal thread to stop
7321 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007322 // do not wait for mStartStopCond if exiting
7323 if (exitPending()) {
7324 return true;
7325 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007326 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007327 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007328 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007329 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007330 ALOGV("Record stopped OK");
7331 return true;
7332 }
7333 return false;
7334}
7335
Glenn Kasten0f11b512014-01-31 16:18:54 -08007336bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007337{
7338 return false;
7339}
7340
Glenn Kasten0f11b512014-01-31 16:18:54 -08007341status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007342{
7343#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7344 if (!isValidSyncEvent(event)) {
7345 return BAD_VALUE;
7346 }
7347
Glenn Kastend848eb42016-03-08 13:42:11 -08007348 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007349 status_t ret = NAME_NOT_FOUND;
7350
7351 Mutex::Autolock _l(mLock);
7352
7353 for (size_t i = 0; i < mTracks.size(); i++) {
7354 sp<RecordTrack> track = mTracks[i];
7355 if (eventSession == track->sessionId()) {
7356 (void) track->setSyncEvent(event);
7357 ret = NO_ERROR;
7358 }
7359 }
7360 return ret;
7361#else
7362 return BAD_VALUE;
7363#endif
7364}
7365
jiabin653cc0a2018-01-17 17:54:10 -08007366status_t AudioFlinger::RecordThread::getActiveMicrophones(
7367 std::vector<media::MicrophoneInfo>* activeMicrophones)
7368{
7369 ALOGV("RecordThread::getActiveMicrophones");
7370 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007371 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7372 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007373}
7374
Kevin Rocard069c2712018-03-29 19:09:14 -07007375void AudioFlinger::RecordThread::updateMetadata_l()
7376{
7377 if (mInput == nullptr || mInput->stream == nullptr ||
7378 !mActiveTracks.readAndClearHasChanged()) {
7379 return;
7380 }
7381 StreamInHalInterface::SinkMetadata metadata;
7382 for (const sp<RecordTrack> &track : mActiveTracks) {
7383 // No track is invalid as this is called after prepareTrack_l in the same critical section
7384 metadata.tracks.push_back({
7385 .source = track->attributes().source,
7386 .gain = 1, // capture tracks do not have volumes
7387 });
7388 }
7389 mInput->stream->updateSinkMetadata(metadata);
7390}
7391
Eric Laurent81784c32012-11-19 14:55:58 -08007392// destroyTrack_l() must be called with ThreadBase::mLock held
7393void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7394{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007395 track->terminate();
7396 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007397 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007398 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007399 removeTrack_l(track);
7400 }
7401}
7402
7403void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7404{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007405 String8 result;
7406 track->appendDump(result, false /* active */);
7407 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7408
Eric Laurent81784c32012-11-19 14:55:58 -08007409 mTracks.remove(track);
7410 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007411 if (track->isFastTrack()) {
7412 ALOG_ASSERT(!mFastTrackAvail);
7413 mFastTrackAvail = true;
7414 }
Eric Laurent81784c32012-11-19 14:55:58 -08007415}
7416
7417void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7418{
7419 dumpInternals(fd, args);
7420 dumpTracks(fd, args);
7421 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007422 dprintf(fd, " Local log:\n");
7423 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007424}
7425
7426void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7427{
Glenn Kasten44182c22015-03-05 17:12:23 -08007428 dumpBase(fd, args);
7429
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007430 AudioStreamIn *input = mInput;
7431 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7432 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7433 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007434 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007435 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007436 }
Andy Hungbfa64962017-06-12 14:43:19 -07007437
7438 if (input != nullptr) {
7439 dprintf(fd, " Hal stream dump:\n");
7440 (void)input->stream->dump(fd);
7441 }
7442
Andy Hung20bd30b2018-06-01 15:39:35 -07007443 const double latencyMs = - mTimestamp.getOutputServerLatencyMs(mSampleRate);
7444 if (latencyMs != 0.) {
7445 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7446 } else {
7447 dprintf(fd, " NormalRecord latency ms: unavail\n");
7448 }
7449
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007450 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007451 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007452
Glenn Kasten2f90c512015-12-02 11:40:09 -08007453 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7454 // while we are dumping it. It may be inconsistent, but it won't mutate!
7455 // This is a large object so we place it on the heap.
7456 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7457 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7458 copy->dump(fd);
7459 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007460}
7461
Glenn Kasten0f11b512014-01-31 16:18:54 -08007462void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007463{
Eric Laurent81784c32012-11-19 14:55:58 -08007464 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007465 size_t numtracks = mTracks.size();
7466 size_t numactive = mActiveTracks.size();
7467 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007468 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007469 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007470 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007471 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007472 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007473 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007474 for (size_t i = 0; i < numtracks ; ++i) {
7475 sp<RecordTrack> track = mTracks[i];
7476 if (track != 0) {
7477 bool active = mActiveTracks.indexOf(track) >= 0;
7478 if (active) {
7479 numactiveseen++;
7480 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007481 result.append(prefix);
7482 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007483 }
Eric Laurent81784c32012-11-19 14:55:58 -08007484 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007485 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007486 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007487 }
7488
Marco Nelissenb2208842014-02-07 14:00:50 -08007489 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007490 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007491 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007492 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007493 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007494 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007495 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007496 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007497 result.append(prefix);
7498 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007499 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007500 }
Eric Laurent81784c32012-11-19 14:55:58 -08007501
7502 }
7503 write(fd, result.string(), result.size());
7504}
7505
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007506void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7507{
7508 Mutex::Autolock _l(mLock);
7509 for (size_t i = 0; i < mTracks.size() ; i++) {
7510 sp<RecordTrack> track = mTracks[i];
7511 if (track != 0 && track->uid() == uid) {
7512 track->setSilenced(silenced);
7513 }
7514 }
7515}
Andy Hung73c02e42015-03-29 01:13:58 -07007516
7517void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7518{
7519 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7520 RecordThread *recordThread = (RecordThread *) threadBase.get();
7521 mRsmpInFront = recordThread->mRsmpInRear;
7522 mRsmpInUnrel = 0;
7523}
7524
7525void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7526 size_t *framesAvailable, bool *hasOverrun)
7527{
7528 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7529 RecordThread *recordThread = (RecordThread *) threadBase.get();
7530 const int32_t rear = recordThread->mRsmpInRear;
7531 const int32_t front = mRsmpInFront;
7532 const ssize_t filled = rear - front;
7533
7534 size_t framesIn;
7535 bool overrun = false;
7536 if (filled < 0) {
7537 // should not happen, but treat like a massive overrun and re-sync
7538 framesIn = 0;
7539 mRsmpInFront = rear;
7540 overrun = true;
7541 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7542 framesIn = (size_t) filled;
7543 } else {
7544 // client is not keeping up with server, but give it latest data
7545 framesIn = recordThread->mRsmpInFrames;
7546 mRsmpInFront = /* front = */ rear - framesIn;
7547 overrun = true;
7548 }
7549 if (framesAvailable != NULL) {
7550 *framesAvailable = framesIn;
7551 }
7552 if (hasOverrun != NULL) {
7553 *hasOverrun = overrun;
7554 }
7555}
7556
Eric Laurent81784c32012-11-19 14:55:58 -08007557// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007558status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007559 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007560{
Andy Hung73c02e42015-03-29 01:13:58 -07007561 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007562 if (threadBase == 0) {
7563 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007564 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007565 return NOT_ENOUGH_DATA;
7566 }
7567 RecordThread *recordThread = (RecordThread *) threadBase.get();
7568 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007569 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007570 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007571 // FIXME should not be P2 (don't want to increase latency)
7572 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007573 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007574 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007575 front &= recordThread->mRsmpInFramesP2 - 1;
7576 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007577 if (part1 > (size_t) filled) {
7578 part1 = filled;
7579 }
7580 size_t ask = buffer->frameCount;
7581 ALOG_ASSERT(ask > 0);
7582 if (part1 > ask) {
7583 part1 = ask;
7584 }
7585 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007586 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007587 buffer->raw = NULL;
7588 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007589 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007590 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007591 }
7592
Andy Hung57446612015-04-19 23:56:46 -07007593 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007594 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007595 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007596 return NO_ERROR;
7597}
7598
7599// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007600void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7601 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007602{
Glenn Kasten85948432013-08-19 12:09:05 -07007603 size_t stepCount = buffer->frameCount;
7604 if (stepCount == 0) {
7605 return;
7606 }
Andy Hung73c02e42015-03-29 01:13:58 -07007607 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7608 mRsmpInUnrel -= stepCount;
7609 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007610 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007611 buffer->frameCount = 0;
7612}
7613
Eric Laurentd8365c52017-07-16 15:27:05 -07007614void AudioFlinger::RecordThread::checkBtNrec()
7615{
7616 Mutex::Autolock _l(mLock);
7617 checkBtNrec_l();
7618}
7619
7620void AudioFlinger::RecordThread::checkBtNrec_l()
7621{
7622 // disable AEC and NS if the device is a BT SCO headset supporting those
7623 // pre processings
7624 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7625 mAudioFlinger->btNrecIsOff();
7626 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7627 for (size_t i = 0; i < mEffectChains.size(); i++) {
7628 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7629 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7630 }
7631 }
7632}
7633
Andy Hung97a893e2015-03-29 01:03:07 -07007634
Eric Laurent10351942014-05-08 18:49:52 -07007635bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7636 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007637{
7638 bool reconfig = false;
7639
Eric Laurent10351942014-05-08 18:49:52 -07007640 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007641
Eric Laurent10351942014-05-08 18:49:52 -07007642 audio_format_t reqFormat = mFormat;
7643 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007644 // 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 -07007645 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7646
7647 AudioParameter param = AudioParameter(keyValuePair);
7648 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007649
7650 // scope for AutoPark extends to end of method
7651 AutoPark<FastCapture> park(mFastCapture);
7652
Eric Laurent10351942014-05-08 18:49:52 -07007653 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7654 // channel count change can be requested. Do we mandate the first client defines the
7655 // HAL sampling rate and channel count or do we allow changes on the fly?
7656 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7657 samplingRate = value;
7658 reconfig = true;
7659 }
7660 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007661 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007662 status = BAD_VALUE;
7663 } else {
7664 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007665 reconfig = true;
7666 }
Eric Laurent10351942014-05-08 18:49:52 -07007667 }
7668 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7669 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007670 if (!audio_is_input_channel(mask) ||
7671 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007672 status = BAD_VALUE;
7673 } else {
7674 channelMask = mask;
7675 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007676 }
Eric Laurent10351942014-05-08 18:49:52 -07007677 }
7678 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7679 // do not accept frame count changes if tracks are open as the track buffer
7680 // size depends on frame count and correct behavior would not be guaranteed
7681 // if frame count is changed after track creation
7682 if (mActiveTracks.size() > 0) {
7683 status = INVALID_OPERATION;
7684 } else {
7685 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007686 }
Eric Laurent10351942014-05-08 18:49:52 -07007687 }
7688 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7689 // forward device change to effects that have requested to be
7690 // aware of attached audio device.
7691 for (size_t i = 0; i < mEffectChains.size(); i++) {
7692 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007693 }
Eric Laurent81784c32012-11-19 14:55:58 -08007694
Eric Laurent10351942014-05-08 18:49:52 -07007695 // store input device and output device but do not forward output device to audio HAL.
7696 // Note that status is ignored by the caller for output device
7697 // (see AudioFlinger::setParameters()
7698 if (audio_is_output_devices(value)) {
7699 mOutDevice = value;
7700 status = BAD_VALUE;
7701 } else {
7702 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007703 if (value != AUDIO_DEVICE_NONE) {
7704 mPrevInDevice = value;
7705 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007706 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007707 }
Eric Laurent10351942014-05-08 18:49:52 -07007708 }
7709 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7710 mAudioSource != (audio_source_t)value) {
7711 // forward device change to effects that have requested to be
7712 // aware of attached audio device.
7713 for (size_t i = 0; i < mEffectChains.size(); i++) {
7714 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007715 }
Eric Laurent10351942014-05-08 18:49:52 -07007716 mAudioSource = (audio_source_t)value;
7717 }
Glenn Kastene198c362013-08-13 09:13:36 -07007718
Eric Laurent10351942014-05-08 18:49:52 -07007719 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007720 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007721 if (status == INVALID_OPERATION) {
7722 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007723 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007724 }
7725 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007726 if (status == BAD_VALUE) {
7727 uint32_t sRate;
7728 audio_channel_mask_t channelMask;
7729 audio_format_t format;
7730 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7731 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7732 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7733 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7734 status = NO_ERROR;
7735 }
Eric Laurent81784c32012-11-19 14:55:58 -08007736 }
Eric Laurent10351942014-05-08 18:49:52 -07007737 if (status == NO_ERROR) {
7738 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007739 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007740 }
7741 }
Eric Laurent81784c32012-11-19 14:55:58 -08007742 }
Eric Laurent10351942014-05-08 18:49:52 -07007743
Eric Laurent81784c32012-11-19 14:55:58 -08007744 return reconfig;
7745}
7746
7747String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7748{
Eric Laurent81784c32012-11-19 14:55:58 -08007749 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007750 if (initCheck() == NO_ERROR) {
7751 String8 out_s8;
7752 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7753 return out_s8;
7754 }
Eric Laurent81784c32012-11-19 14:55:58 -08007755 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007756 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007757}
7758
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007759void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007760 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7761
7762 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007763
7764 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007765 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007766 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007767 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007768 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007769 desc->mChannelMask = mChannelMask;
7770 desc->mSamplingRate = mSampleRate;
7771 desc->mFormat = mFormat;
7772 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007773 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007774 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007775 break;
7776
Eric Laurent73e26b62015-04-27 16:55:58 -07007777 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007778 default:
7779 break;
7780 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007781 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007782}
7783
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007784void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007785{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007786 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7787 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07007788 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007789 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
7790 if (audio_is_linear_pcm(mFormat)) {
7791 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
7792 mChannelCount, FCC_8);
7793 } else {
7794 // Can have more that FCC_8 channels in encoded streams.
7795 ALOGI("HAL format %#x is not linear pcm", mFormat);
7796 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007797 result = mInput->stream->getFrameSize(&mFrameSize);
7798 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7799 result = mInput->stream->getBufferSize(&mBufferSize);
7800 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007801 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007802 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7803 "mBufferSize=%lld, mFrameCount=%lld",
7804 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7805 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007806 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007807 // 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 -07007808 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007809 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007810 // A larger value should allow more old data to be read after a track calls start(),
7811 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007812 //
7813 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007814 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007815 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007816 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007817 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007818
7819 // TODO optimize audio capture buffer sizes ...
7820 // Here we calculate the size of the sliding buffer used as a source
7821 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7822 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7823 // be better to have it derived from the pipe depth in the long term.
7824 // The current value is higher than necessary. However it should not add to latency.
7825
Glenn Kasten85948432013-08-19 12:09:05 -07007826 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007827 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7828 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007829 // if posix_memalign fails, will segv here.
7830 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007831
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007832 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7833 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007834}
7835
Glenn Kasten5f972c02014-01-13 09:59:31 -08007836uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007837{
7838 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007839 uint32_t result;
7840 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7841 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007842 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007843 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007844}
7845
Eric Laurent4c415062016-06-17 16:14:16 -07007846// hasAudioSession_l() must be called with ThreadBase::mLock held
7847uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007848{
Eric Laurent81784c32012-11-19 14:55:58 -08007849 uint32_t result = 0;
7850 if (getEffectChain_l(sessionId) != 0) {
7851 result = EFFECT_SESSION;
7852 }
7853
7854 for (size_t i = 0; i < mTracks.size(); ++i) {
7855 if (sessionId == mTracks[i]->sessionId()) {
7856 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007857 if (mTracks[i]->isFastTrack()) {
7858 result |= FAST_SESSION;
7859 }
Eric Laurent81784c32012-11-19 14:55:58 -08007860 break;
7861 }
7862 }
7863
7864 return result;
7865}
7866
Glenn Kastend848eb42016-03-08 13:42:11 -08007867KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007868{
Glenn Kastend848eb42016-03-08 13:42:11 -08007869 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007870 Mutex::Autolock _l(mLock);
7871 for (size_t j = 0; j < mTracks.size(); ++j) {
7872 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007873 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007874 if (ids.indexOfKey(sessionId) < 0) {
7875 ids.add(sessionId, true);
7876 }
7877 }
7878 return ids;
7879}
7880
7881AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7882{
7883 Mutex::Autolock _l(mLock);
7884 AudioStreamIn *input = mInput;
7885 mInput = NULL;
7886 return input;
7887}
7888
7889// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007890sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007891{
7892 if (mInput == NULL) {
7893 return NULL;
7894 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007895 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007896}
7897
7898status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7899{
7900 // only one chain per input thread
7901 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007902 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007903 return INVALID_OPERATION;
7904 }
7905 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007906 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007907 chain->setInBuffer(NULL);
7908 chain->setOutBuffer(NULL);
7909
7910 checkSuspendOnAddEffectChain_l(chain);
7911
Eric Laurent1b928682014-10-02 19:41:47 -07007912 // make sure enabled pre processing effects state is communicated to the HAL as we
7913 // just moved them to a new input stream.
7914 chain->syncHalEffectsState();
7915
Eric Laurent81784c32012-11-19 14:55:58 -08007916 mEffectChains.add(chain);
7917
7918 return NO_ERROR;
7919}
7920
7921size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7922{
7923 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7924 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007925 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007926 chain.get(), mEffectChains.size(), this);
7927 if (mEffectChains.size() == 1) {
7928 mEffectChains.removeAt(0);
7929 }
7930 return 0;
7931}
7932
Eric Laurent1c333e22014-05-20 10:48:17 -07007933status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7934 audio_patch_handle_t *handle)
7935{
7936 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007937
7938 // store new device and send to effects
7939 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007940 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007941 for (size_t i = 0; i < mEffectChains.size(); i++) {
7942 mEffectChains[i]->setDevice_l(mInDevice);
7943 }
7944
Eric Laurentd8365c52017-07-16 15:27:05 -07007945 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007946
7947 // store new source and send to effects
7948 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7949 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007950 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007951 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007952 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007953 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007954
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007955 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007956 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7957 status = hwDevice->createAudioPatch(patch->num_sources,
7958 patch->sources,
7959 patch->num_sinks,
7960 patch->sinks,
7961 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007962 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007963 char *address;
7964 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7965 address = audio_device_address_to_parameter(
7966 patch->sources[0].ext.device.type,
7967 patch->sources[0].ext.device.address);
7968 } else {
7969 address = (char *)calloc(1, 1);
7970 }
7971 AudioParameter param = AudioParameter(String8(address));
7972 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007973 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007974 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007975 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007976 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007977 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007978 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007979 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007980
Eric Laurente8726fe2015-06-26 09:39:24 -07007981 if (mInDevice != mPrevInDevice) {
7982 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7983 mPrevInDevice = mInDevice;
7984 }
Eric Laurent296fb132015-05-01 11:38:42 -07007985
Eric Laurent1c333e22014-05-20 10:48:17 -07007986 return status;
7987}
7988
7989status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7990{
7991 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007992
7993 mInDevice = AUDIO_DEVICE_NONE;
7994
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007995 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007996 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7997 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007998 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007999 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008000 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008001 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008002 }
8003 return status;
8004}
8005
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008006void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008007{
8008 Mutex::Autolock _l(mLock);
8009 mTracks.add(record);
8010}
8011
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008012void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008013{
8014 Mutex::Autolock _l(mLock);
8015 destroyTrack_l(record);
8016}
8017
Mikhail Naganovdc769682018-05-04 15:34:08 -07008018void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008019{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008020 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008021 config->role = AUDIO_PORT_ROLE_SINK;
8022 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8023 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008024 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8025 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8026 config->flags.input = mInput->flags;
8027 }
Eric Laurent83b88082014-06-20 18:31:16 -07008028}
Eric Laurent1c333e22014-05-20 10:48:17 -07008029
Eric Laurent6acd1d42017-01-04 14:23:29 -08008030// ----------------------------------------------------------------------------
8031// Mmap
8032// ----------------------------------------------------------------------------
8033
8034AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8035 : mThread(thread)
8036{
Phil Burk9fabbf82017-08-03 12:02:00 -07008037 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008038}
8039
8040AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8041{
Phil Burk9fabbf82017-08-03 12:02:00 -07008042 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008043}
8044
8045status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8046 struct audio_mmap_buffer_info *info)
8047{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008048 return mThread->createMmapBuffer(minSizeFrames, info);
8049}
8050
8051status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8052{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008053 return mThread->getMmapPosition(position);
8054}
8055
Eric Laurenta54f1282017-07-01 19:39:32 -07008056status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008057 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008058
8059{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008060 return mThread->start(client, handle);
8061}
8062
8063status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8064{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008065 return mThread->stop(handle);
8066}
8067
Eric Laurent18b57012017-02-13 16:23:52 -08008068status_t AudioFlinger::MmapThreadHandle::standby()
8069{
Eric Laurent18b57012017-02-13 16:23:52 -08008070 return mThread->standby();
8071}
8072
Eric Laurent6acd1d42017-01-04 14:23:29 -08008073
8074AudioFlinger::MmapThread::MmapThread(
8075 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8076 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8077 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8078 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008079 mSessionId(AUDIO_SESSION_NONE),
8080 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008081 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008082 mActiveTracks(&this->mLocalLog),
8083 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8084 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008085{
Eric Laurent18b57012017-02-13 16:23:52 -08008086 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008087 readHalParameters_l();
8088}
8089
8090AudioFlinger::MmapThread::~MmapThread()
8091{
Eric Laurent18b57012017-02-13 16:23:52 -08008092 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008093}
8094
8095void AudioFlinger::MmapThread::onFirstRef()
8096{
8097 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8098}
8099
8100void AudioFlinger::MmapThread::disconnect()
8101{
Eric Laurent331679c2018-04-16 17:03:16 -07008102 ActiveTracks<MmapTrack> activeTracks;
8103 {
8104 Mutex::Autolock _l(mLock);
8105 for (const sp<MmapTrack> &t : mActiveTracks) {
8106 activeTracks.add(t);
8107 }
8108 }
8109 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008110 stop(t->portId());
8111 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008112 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008113 if (isOutput()) {
8114 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
8115 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008116 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008117 }
8118}
8119
8120
8121void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8122 audio_stream_type_t streamType __unused,
8123 audio_session_t sessionId,
8124 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008125 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008126 audio_port_handle_t portId)
8127{
8128 mAttr = *attr;
8129 mSessionId = sessionId;
8130 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008131 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008132 mPortId = portId;
8133}
8134
8135status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8136 struct audio_mmap_buffer_info *info)
8137{
8138 if (mHalStream == 0) {
8139 return NO_INIT;
8140 }
Eric Laurent18b57012017-02-13 16:23:52 -08008141 mStandby = true;
8142 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008143 return mHalStream->createMmapBuffer(minSizeFrames, info);
8144}
8145
8146status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8147{
8148 if (mHalStream == 0) {
8149 return NO_INIT;
8150 }
8151 return mHalStream->getMmapPosition(position);
8152}
8153
Eric Laurent331679c2018-04-16 17:03:16 -07008154status_t AudioFlinger::MmapThread::exitStandby()
8155{
8156 status_t ret = mHalStream->start();
8157 if (ret != NO_ERROR) {
8158 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8159 return ret;
8160 }
8161 mStandby = false;
8162 return NO_ERROR;
8163}
8164
Eric Laurenta54f1282017-07-01 19:39:32 -07008165status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008166 audio_port_handle_t *handle)
8167{
Eric Laurenta54f1282017-07-01 19:39:32 -07008168 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8169 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008170 if (mHalStream == 0) {
8171 return NO_INIT;
8172 }
8173
8174 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008175
Eric Laurenta54f1282017-07-01 19:39:32 -07008176 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008177 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008178 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008179 }
8180
8181 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8182
8183 audio_io_handle_t io = mId;
8184 if (isOutput()) {
8185 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8186 config.sample_rate = mSampleRate;
8187 config.channel_mask = mChannelMask;
8188 config.format = mFormat;
8189 audio_stream_type_t stream = streamType();
8190 audio_output_flags_t flags =
8191 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008192 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008193 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8194 mSessionId,
8195 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008196 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008197 client.clientUid,
8198 &config,
8199 flags,
8200 &deviceId,
8201 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008202 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008203 audio_config_base_t config;
8204 config.sample_rate = mSampleRate;
8205 config.channel_mask = mChannelMask;
8206 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008207 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008208 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8209 mSessionId,
8210 client.clientPid,
8211 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008212 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008213 &config,
8214 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8215 &deviceId,
8216 &portId);
8217 }
8218 // APM should not chose a different input or output stream for the same set of attributes
8219 // and audo configuration
8220 if (ret != NO_ERROR || io != mId) {
8221 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8222 __FUNCTION__, ret, io, mId);
8223 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008224 }
8225
Eric Laurent331679c2018-04-16 17:03:16 -07008226 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008227 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008228 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008229 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008230 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008231 }
8232
Eric Laurent331679c2018-04-16 17:03:16 -07008233 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008234 // abort if start is rejected by audio policy manager
8235 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008236 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008237 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008238 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008239 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008240 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008241 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008242 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008243 }
Eric Laurent331679c2018-04-16 17:03:16 -07008244 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008245 } else {
8246 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008247 }
8248 return PERMISSION_DENIED;
8249 }
8250
Eric Laurent67f97292018-04-20 18:05:41 -07008251 if (isOutput()) {
8252 // force volume update when a new track is added
8253 mHalVolFloat = -1.0f;
8254 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008255 for (const sp<MmapTrack> &track : mActiveTracks) {
8256 if (track->isSilenced_l() && track->uid() != client.clientUid)
8257 track->invalidate();
8258 }
8259 }
8260
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008261 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8262 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008263 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008264
Eric Laurent331679c2018-04-16 17:03:16 -07008265 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008266 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008267 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008268 if (chain != 0) {
8269 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8270 chain->incTrackCnt();
8271 chain->incActiveTrackCnt();
8272 }
8273
8274 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008275 broadcast_l();
8276
Eric Laurenta54f1282017-07-01 19:39:32 -07008277 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008278
8279 return NO_ERROR;
8280}
8281
8282status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8283{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008284 ALOGV("%s handle %d", __FUNCTION__, handle);
8285
8286 if (mHalStream == 0) {
8287 return NO_INIT;
8288 }
8289
Eric Laurenta54f1282017-07-01 19:39:32 -07008290 if (handle == mPortId) {
8291 mHalStream->stop();
8292 return NO_ERROR;
8293 }
8294
Eric Laurent331679c2018-04-16 17:03:16 -07008295 Mutex::Autolock _l(mLock);
8296
Eric Laurent6acd1d42017-01-04 14:23:29 -08008297 sp<MmapTrack> track;
8298 for (const sp<MmapTrack> &t : mActiveTracks) {
8299 if (handle == t->portId()) {
8300 track = t;
8301 break;
8302 }
8303 }
8304 if (track == 0) {
8305 return BAD_VALUE;
8306 }
8307
8308 mActiveTracks.remove(track);
8309
Eric Laurent331679c2018-04-16 17:03:16 -07008310 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008311 if (isOutput()) {
8312 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008313 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008314 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008315 AudioSystem::stopInput(track->portId());
8316 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008317 }
Eric Laurent331679c2018-04-16 17:03:16 -07008318 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008319
8320 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8321 if (chain != 0) {
8322 chain->decActiveTrackCnt();
8323 chain->decTrackCnt();
8324 }
8325
8326 broadcast_l();
8327
Eric Laurent6acd1d42017-01-04 14:23:29 -08008328 return NO_ERROR;
8329}
8330
Eric Laurent18b57012017-02-13 16:23:52 -08008331status_t AudioFlinger::MmapThread::standby()
8332{
8333 ALOGV("%s", __FUNCTION__);
8334
8335 if (mHalStream == 0) {
8336 return NO_INIT;
8337 }
8338 if (mActiveTracks.size() != 0) {
8339 return INVALID_OPERATION;
8340 }
8341 mHalStream->standby();
8342 mStandby = true;
8343 releaseWakeLock();
8344 return NO_ERROR;
8345}
8346
Eric Laurent6acd1d42017-01-04 14:23:29 -08008347
8348void AudioFlinger::MmapThread::readHalParameters_l()
8349{
8350 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8351 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8352 mFormat = mHALFormat;
8353 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8354 result = mHalStream->getFrameSize(&mFrameSize);
8355 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8356 result = mHalStream->getBufferSize(&mBufferSize);
8357 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8358 mFrameCount = mBufferSize / mFrameSize;
8359}
8360
8361bool AudioFlinger::MmapThread::threadLoop()
8362{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008363 checkSilentMode_l();
8364
8365 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8366
8367 while (!exitPending())
8368 {
8369 Mutex::Autolock _l(mLock);
8370 Vector< sp<EffectChain> > effectChains;
8371
8372 if (mSignalPending) {
8373 // A signal was raised while we were unlocked
8374 mSignalPending = false;
8375 } else {
8376 if (mConfigEvents.isEmpty()) {
8377 // we're about to wait, flush the binder command buffer
8378 IPCThreadState::self()->flushCommands();
8379
8380 if (exitPending()) {
8381 break;
8382 }
8383
Eric Laurent6acd1d42017-01-04 14:23:29 -08008384 // wait until we have something to do...
8385 ALOGV("%s going to sleep", myName.string());
8386 mWaitWorkCV.wait(mLock);
8387 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008388
8389 checkSilentMode_l();
8390
8391 continue;
8392 }
8393 }
8394
8395 processConfigEvents_l();
8396
8397 processVolume_l();
8398
8399 checkInvalidTracks_l();
8400
8401 mActiveTracks.updatePowerState(this);
8402
Kevin Rocard069c2712018-03-29 19:09:14 -07008403 updateMetadata_l();
8404
Eric Laurent6acd1d42017-01-04 14:23:29 -08008405 lockEffectChains_l(effectChains);
8406 for (size_t i = 0; i < effectChains.size(); i ++) {
8407 effectChains[i]->process_l();
8408 }
8409 // enable changes in effect chain
8410 unlockEffectChains(effectChains);
8411 // Effect chains will be actually deleted here if they were removed from
8412 // mEffectChains list during mixing or effects processing
8413 }
8414
8415 threadLoop_exit();
8416
8417 if (!mStandby) {
8418 threadLoop_standby();
8419 mStandby = true;
8420 }
8421
Eric Laurent6acd1d42017-01-04 14:23:29 -08008422 ALOGV("Thread %p type %d exiting", this, mType);
8423 return false;
8424}
8425
8426// checkForNewParameter_l() must be called with ThreadBase::mLock held
8427bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8428 status_t& status)
8429{
8430 AudioParameter param = AudioParameter(keyValuePair);
8431 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008432 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008433 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008434 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008435 // forward device change to effects that have requested to be
8436 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008437 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008438 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008439 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008440 }
8441 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008442 if (audio_is_output_devices(device)) {
8443 mOutDevice = device;
8444 if (!isOutput()) {
8445 sendToHal = false;
8446 }
8447 } else {
8448 mInDevice = device;
8449 if (device != AUDIO_DEVICE_NONE) {
8450 mPrevInDevice = value;
8451 }
8452 // TODO: implement and call checkBtNrec_l();
8453 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008454 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008455 if (sendToHal) {
8456 status = mHalStream->setParameters(keyValuePair);
8457 } else {
8458 status = NO_ERROR;
8459 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008460
8461 return false;
8462}
8463
8464String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8465{
8466 Mutex::Autolock _l(mLock);
8467 String8 out_s8;
8468 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8469 return out_s8;
8470 }
8471 return String8();
8472}
8473
8474void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8475 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8476
8477 desc->mIoHandle = mId;
8478
8479 switch (event) {
8480 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008481 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008482 case AUDIO_INPUT_CONFIG_CHANGED:
8483 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008484 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008485 case AUDIO_OUTPUT_CONFIG_CHANGED:
8486 desc->mPatch = mPatch;
8487 desc->mChannelMask = mChannelMask;
8488 desc->mSamplingRate = mSampleRate;
8489 desc->mFormat = mFormat;
8490 desc->mFrameCount = mFrameCount;
8491 desc->mFrameCountHAL = mFrameCount;
8492 desc->mLatency = 0;
8493 break;
8494
8495 case AUDIO_INPUT_CLOSED:
8496 case AUDIO_OUTPUT_CLOSED:
8497 default:
8498 break;
8499 }
8500 mAudioFlinger->ioConfigChanged(event, desc, pid);
8501}
8502
8503status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8504 audio_patch_handle_t *handle)
8505{
8506 status_t status = NO_ERROR;
8507
8508 // store new device and send to effects
8509 audio_devices_t type = AUDIO_DEVICE_NONE;
8510 audio_port_handle_t deviceId;
8511 if (isOutput()) {
8512 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8513 type |= patch->sinks[i].ext.device.type;
8514 }
8515 deviceId = patch->sinks[0].id;
8516 } else {
8517 type = patch->sources[0].ext.device.type;
8518 deviceId = patch->sources[0].id;
8519 }
8520
8521 for (size_t i = 0; i < mEffectChains.size(); i++) {
8522 mEffectChains[i]->setDevice_l(type);
8523 }
8524
8525 if (isOutput()) {
8526 mOutDevice = type;
8527 } else {
8528 mInDevice = type;
8529 // store new source and send to effects
8530 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8531 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8532 for (size_t i = 0; i < mEffectChains.size(); i++) {
8533 mEffectChains[i]->setAudioSource_l(mAudioSource);
8534 }
8535 }
8536 }
8537
8538 if (mAudioHwDev->supportsAudioPatches()) {
8539 status = mHalDevice->createAudioPatch(patch->num_sources,
8540 patch->sources,
8541 patch->num_sinks,
8542 patch->sinks,
8543 handle);
8544 } else {
8545 char *address;
8546 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8547 //FIXME: we only support address on first sink with HAL version < 3.0
8548 address = audio_device_address_to_parameter(
8549 patch->sinks[0].ext.device.type,
8550 patch->sinks[0].ext.device.address);
8551 } else {
8552 address = (char *)calloc(1, 1);
8553 }
8554 AudioParameter param = AudioParameter(String8(address));
8555 free(address);
8556 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8557 if (!isOutput()) {
8558 param.addInt(String8(AudioParameter::keyInputSource),
8559 (int)patch->sinks[0].ext.mix.usecase.source);
8560 }
8561 status = mHalStream->setParameters(param.toString());
8562 *handle = AUDIO_PATCH_HANDLE_NONE;
8563 }
8564
8565 if (isOutput() && mPrevOutDevice != mOutDevice) {
8566 mPrevOutDevice = type;
8567 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008568 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008569 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008570 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008571 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008572 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008573 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008574 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008575 }
8576 if (!isOutput() && mPrevInDevice != mInDevice) {
8577 mPrevInDevice = type;
8578 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008579 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008580 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008581 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008582 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008583 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008584 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008585 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008586 }
8587 return status;
8588}
8589
8590status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8591{
8592 status_t status = NO_ERROR;
8593
8594 mInDevice = AUDIO_DEVICE_NONE;
8595
8596 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8597 supportsAudioPatches : false;
8598
8599 if (supportsAudioPatches) {
8600 status = mHalDevice->releaseAudioPatch(handle);
8601 } else {
8602 AudioParameter param;
8603 param.addInt(String8(AudioParameter::keyRouting), 0);
8604 status = mHalStream->setParameters(param.toString());
8605 }
8606 return status;
8607}
8608
Mikhail Naganovdc769682018-05-04 15:34:08 -07008609void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008610{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008611 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008612 if (isOutput()) {
8613 config->role = AUDIO_PORT_ROLE_SOURCE;
8614 config->ext.mix.hw_module = mAudioHwDev->handle();
8615 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8616 } else {
8617 config->role = AUDIO_PORT_ROLE_SINK;
8618 config->ext.mix.hw_module = mAudioHwDev->handle();
8619 config->ext.mix.usecase.source = mAudioSource;
8620 }
8621}
8622
8623status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8624{
8625 audio_session_t session = chain->sessionId();
8626
8627 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8628 // Attach all tracks with same session ID to this chain.
8629 // indicate all active tracks in the chain
8630 for (const sp<MmapTrack> &track : mActiveTracks) {
8631 if (session == track->sessionId()) {
8632 chain->incTrackCnt();
8633 chain->incActiveTrackCnt();
8634 }
8635 }
8636
8637 chain->setThread(this);
8638 chain->setInBuffer(nullptr);
8639 chain->setOutBuffer(nullptr);
8640 chain->syncHalEffectsState();
8641
8642 mEffectChains.add(chain);
8643 checkSuspendOnAddEffectChain_l(chain);
8644 return NO_ERROR;
8645}
8646
8647size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8648{
8649 audio_session_t session = chain->sessionId();
8650
8651 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8652
8653 for (size_t i = 0; i < mEffectChains.size(); i++) {
8654 if (chain == mEffectChains[i]) {
8655 mEffectChains.removeAt(i);
8656 // detach all active tracks from the chain
8657 // detach all tracks with same session ID from this chain
8658 for (const sp<MmapTrack> &track : mActiveTracks) {
8659 if (session == track->sessionId()) {
8660 chain->decActiveTrackCnt();
8661 chain->decTrackCnt();
8662 }
8663 }
8664 break;
8665 }
8666 }
8667 return mEffectChains.size();
8668}
8669
8670// hasAudioSession_l() must be called with ThreadBase::mLock held
8671uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8672{
8673 uint32_t result = 0;
8674 if (getEffectChain_l(sessionId) != 0) {
8675 result = EFFECT_SESSION;
8676 }
8677
8678 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8679 sp<MmapTrack> track = mActiveTracks[i];
8680 if (sessionId == track->sessionId()) {
8681 result |= TRACK_SESSION;
8682 if (track->isFastTrack()) {
8683 result |= FAST_SESSION;
8684 }
8685 break;
8686 }
8687 }
8688
8689 return result;
8690}
8691
8692void AudioFlinger::MmapThread::threadLoop_standby()
8693{
8694 mHalStream->standby();
8695}
8696
8697void AudioFlinger::MmapThread::threadLoop_exit()
8698{
Phil Burk7dce7282017-09-27 13:51:41 -07008699 // Do not call callback->onTearDown() because it is redundant for thread exit
8700 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008701}
8702
8703status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8704{
8705 return BAD_VALUE;
8706}
8707
8708bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8709{
8710 return false;
8711}
8712
8713status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8714 const effect_descriptor_t *desc, audio_session_t sessionId)
8715{
8716 // No global effect sessions on mmap threads
8717 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8718 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8719 desc->name, mThreadName);
8720 return BAD_VALUE;
8721 }
8722
8723 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8724 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8725 desc->name);
8726 return BAD_VALUE;
8727 }
8728 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008729 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8730 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008731 return BAD_VALUE;
8732 }
8733
8734 // Only allow effects without processing load or latency
8735 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8736 return BAD_VALUE;
8737 }
8738
8739 return NO_ERROR;
8740
8741}
8742
8743void AudioFlinger::MmapThread::checkInvalidTracks_l()
8744{
8745 for (const sp<MmapTrack> &track : mActiveTracks) {
8746 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008747 sp<MmapStreamCallback> callback = mCallback.promote();
8748 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008749 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008750 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008751 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008752 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8753 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8754 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008755 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756 }
8757 }
8758}
8759
8760void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8761{
8762 dumpInternals(fd, args);
8763 dumpTracks(fd, args);
8764 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008765 dprintf(fd, " Local log:\n");
8766 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008767}
8768
8769void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8770{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771 dumpBase(fd, args);
8772
8773 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8774 mAttr.content_type, mAttr.usage, mAttr.source);
8775 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8776 if (mActiveTracks.size() == 0) {
8777 dprintf(fd, " No active clients\n");
8778 }
8779}
8780
8781void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8782{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008783 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008784 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008785 dprintf(fd, " %zu Tracks\n", numtracks);
8786 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008787 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008788 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008789 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008790 for (size_t i = 0; i < numtracks ; ++i) {
8791 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008792 result.append(prefix);
8793 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008794 }
8795 } else {
8796 dprintf(fd, "\n");
8797 }
8798 write(fd, result.string(), result.size());
8799}
8800
8801AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8802 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8803 AudioHwDevice *hwDev, AudioStreamOut *output,
8804 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8805 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8806 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008807 mStreamVolume(1.0),
8808 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008809 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008810{
8811 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8812 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8813 mMasterVolume = audioFlinger->masterVolume_l();
8814 mMasterMute = audioFlinger->masterMute_l();
8815 if (mAudioHwDev) {
8816 if (mAudioHwDev->canSetMasterVolume()) {
8817 mMasterVolume = 1.0;
8818 }
8819
8820 if (mAudioHwDev->canSetMasterMute()) {
8821 mMasterMute = false;
8822 }
8823 }
8824}
8825
8826void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8827 audio_stream_type_t streamType,
8828 audio_session_t sessionId,
8829 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008830 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008831 audio_port_handle_t portId)
8832{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008833 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008834 mStreamType = streamType;
8835}
8836
8837AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8838{
8839 Mutex::Autolock _l(mLock);
8840 AudioStreamOut *output = mOutput;
8841 mOutput = NULL;
8842 return output;
8843}
8844
8845void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8846{
8847 Mutex::Autolock _l(mLock);
8848 // Don't apply master volume in SW if our HAL can do it for us.
8849 if (mAudioHwDev &&
8850 mAudioHwDev->canSetMasterVolume()) {
8851 mMasterVolume = 1.0;
8852 } else {
8853 mMasterVolume = value;
8854 }
8855}
8856
8857void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8858{
8859 Mutex::Autolock _l(mLock);
8860 // Don't apply master mute in SW if our HAL can do it for us.
8861 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8862 mMasterMute = false;
8863 } else {
8864 mMasterMute = muted;
8865 }
8866}
8867
8868void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8869{
8870 Mutex::Autolock _l(mLock);
8871 if (stream == mStreamType) {
8872 mStreamVolume = value;
8873 broadcast_l();
8874 }
8875}
8876
8877float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8878{
8879 Mutex::Autolock _l(mLock);
8880 if (stream == mStreamType) {
8881 return mStreamVolume;
8882 }
8883 return 0.0f;
8884}
8885
8886void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8887{
8888 Mutex::Autolock _l(mLock);
8889 if (stream == mStreamType) {
8890 mStreamMute= muted;
8891 broadcast_l();
8892 }
8893}
8894
8895void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8896{
8897 Mutex::Autolock _l(mLock);
8898 if (streamType == mStreamType) {
8899 for (const sp<MmapTrack> &track : mActiveTracks) {
8900 track->invalidate();
8901 }
8902 broadcast_l();
8903 }
8904}
8905
8906void AudioFlinger::MmapPlaybackThread::processVolume_l()
8907{
8908 float volume;
8909
8910 if (mMasterMute || mStreamMute) {
8911 volume = 0;
8912 } else {
8913 volume = mMasterVolume * mStreamVolume;
8914 }
8915
8916 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008917
8918 // Convert volumes from float to 8.24
8919 uint32_t vol = (uint32_t)(volume * (1 << 24));
8920
8921 // Delegate volume control to effect in track effect chain if needed
8922 // only one effect chain can be present on DirectOutputThread, so if
8923 // there is one, the track is connected to it
8924 if (!mEffectChains.isEmpty()) {
8925 mEffectChains[0]->setVolume_l(&vol, &vol);
8926 volume = (float)vol / (1 << 24);
8927 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008928 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008929 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8930 mHalVolFloat = volume; // HW volume control worked, so update value.
8931 mNoCallbackWarningCount = 0;
8932 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008933 sp<MmapStreamCallback> callback = mCallback.promote();
8934 if (callback != 0) {
8935 int channelCount;
8936 if (isOutput()) {
8937 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8938 } else {
8939 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8940 }
8941 Vector<float> values;
8942 for (int i = 0; i < channelCount; i++) {
8943 values.add(volume);
8944 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008945 mHalVolFloat = volume; // SW volume control worked, so update value.
8946 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008947 mLock.unlock();
8948 callback->onVolumeChanged(mChannelMask, values);
8949 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008950 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008951 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8952 ALOGW("Could not set MMAP stream volume: no volume callback!");
8953 mNoCallbackWarningCount++;
8954 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008955 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008956 }
8957 }
8958}
8959
Kevin Rocard069c2712018-03-29 19:09:14 -07008960void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8961{
8962 if (mOutput == nullptr || mOutput->stream == nullptr ||
8963 !mActiveTracks.readAndClearHasChanged()) {
8964 return;
8965 }
8966 StreamOutHalInterface::SourceMetadata metadata;
8967 for (const sp<MmapTrack> &track : mActiveTracks) {
8968 // No track is invalid as this is called after prepareTrack_l in the same critical section
8969 metadata.tracks.push_back({
8970 .usage = track->attributes().usage,
8971 .content_type = track->attributes().content_type,
8972 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8973 });
8974 }
8975 mOutput->stream->updateSourceMetadata(metadata);
8976}
8977
Eric Laurent6acd1d42017-01-04 14:23:29 -08008978void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8979{
8980 if (!mMasterMute) {
8981 char value[PROPERTY_VALUE_MAX];
8982 if (property_get("ro.audio.silent", value, "0") > 0) {
8983 char *endptr;
8984 unsigned long ul = strtoul(value, &endptr, 0);
8985 if (*endptr == '\0' && ul != 0) {
8986 ALOGD("Silence is golden");
8987 // The setprop command will not allow a property to be changed after
8988 // the first time it is set, so we don't have to worry about un-muting.
8989 setMasterMute_l(true);
8990 }
8991 }
8992 }
8993}
8994
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008995void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
8996{
8997 MmapThread::toAudioPortConfig(config);
8998 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
8999 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9000 config->flags.output = mOutput->flags;
9001 }
9002}
9003
Eric Laurent6acd1d42017-01-04 14:23:29 -08009004void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9005{
9006 MmapThread::dumpInternals(fd, args);
9007
Glenn Kastend3bb6452016-12-05 18:14:37 -08009008 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9009 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009010 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9011}
9012
9013AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9014 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9015 AudioHwDevice *hwDev, AudioStreamIn *input,
9016 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9017 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9018 mInput(input)
9019{
9020 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9021 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9022}
9023
Eric Laurent331679c2018-04-16 17:03:16 -07009024status_t AudioFlinger::MmapCaptureThread::exitStandby()
9025{
9026 mInput->stream->setGain(1.0f);
9027 return MmapThread::exitStandby();
9028}
9029
Eric Laurent6acd1d42017-01-04 14:23:29 -08009030AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9031{
9032 Mutex::Autolock _l(mLock);
9033 AudioStreamIn *input = mInput;
9034 mInput = NULL;
9035 return input;
9036}
Kevin Rocard069c2712018-03-29 19:09:14 -07009037
Eric Laurent331679c2018-04-16 17:03:16 -07009038
9039void AudioFlinger::MmapCaptureThread::processVolume_l()
9040{
9041 bool changed = false;
9042 bool silenced = false;
9043
9044 sp<MmapStreamCallback> callback = mCallback.promote();
9045 if (callback == 0) {
9046 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9047 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9048 mNoCallbackWarningCount++;
9049 }
9050 }
9051
9052 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9053 // track is silenced and unmute otherwise
9054 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9055 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9056 changed = true;
9057 silenced = mActiveTracks[i]->isSilenced_l();
9058 }
9059 }
9060
9061 if (changed) {
9062 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9063 }
9064}
9065
Kevin Rocard069c2712018-03-29 19:09:14 -07009066void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9067{
9068 if (mInput == nullptr || mInput->stream == nullptr ||
9069 !mActiveTracks.readAndClearHasChanged()) {
9070 return;
9071 }
9072 StreamInHalInterface::SinkMetadata metadata;
9073 for (const sp<MmapTrack> &track : mActiveTracks) {
9074 // No track is invalid as this is called after prepareTrack_l in the same critical section
9075 metadata.tracks.push_back({
9076 .source = track->attributes().source,
9077 .gain = 1, // capture tracks do not have volumes
9078 });
9079 }
9080 mInput->stream->updateSinkMetadata(metadata);
9081}
9082
Eric Laurent331679c2018-04-16 17:03:16 -07009083void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9084{
9085 Mutex::Autolock _l(mLock);
9086 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9087 if (mActiveTracks[i]->uid() == uid) {
9088 mActiveTracks[i]->setSilenced_l(silenced);
9089 broadcast_l();
9090 }
9091 }
9092}
9093
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009094void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9095{
9096 MmapThread::toAudioPortConfig(config);
9097 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9098 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9099 config->flags.input = mInput->flags;
9100 }
9101}
9102
Glenn Kasten63238ef2015-03-02 15:50:29 -08009103} // namespace android