blob: ca5ae14c2b3cecfb3b5577484c95af7098550578 [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 Laurentd7fe0862018-07-14 16:48:01 -07002327 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 mLock.lock();
2329 // abort track was stopped/paused while we released the lock
2330 if (state != track->mState) {
2331 if (status == NO_ERROR) {
2332 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002333 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002334 mLock.lock();
2335 }
2336 return INVALID_OPERATION;
2337 }
2338 // abort if start is rejected by audio policy manager
2339 if (status != NO_ERROR) {
2340 return PERMISSION_DENIED;
2341 }
2342#ifdef ADD_BATTERY_DATA
2343 // to track the speaker usage
2344 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2345#endif
2346 }
2347
Eric Laurent51716182016-02-29 18:00:56 -08002348 // set retry count for buffer fill
2349 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002350 if (track->isStopping_1()) {
2351 track->mRetryCount = kMaxTrackStopRetriesOffload;
2352 } else {
2353 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2354 }
2355 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002356 } else {
2357 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002358 track->mFillingUpStatus =
2359 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002360 }
2361
Eric Laurent81784c32012-11-19 14:55:58 -08002362 track->mResetDone = false;
2363 track->mPresentationCompleteFrames = 0;
2364 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002365 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2366 if (chain != 0) {
2367 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2368 track->sessionId());
2369 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002370 }
2371
2372 status = NO_ERROR;
2373 }
2374
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002375 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002376 return status;
2377}
2378
Eric Laurentbfb1b832013-01-07 09:53:42 -08002379bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002380{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002381 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002382 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002383 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2384 track->mState = TrackBase::STOPPED;
2385 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002386 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002387 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002388 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002389 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002390
2391 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002392}
2393
2394void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2395{
2396 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002397
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002398 String8 result;
2399 track->appendDump(result, false /* active */);
2400 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002401
Eric Laurent81784c32012-11-19 14:55:58 -08002402 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002403 if (track->isFastTrack()) {
2404 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002405 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002406 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2407 mFastTrackAvailMask |= 1 << index;
2408 // redundant as track is about to be destroyed, for dumpsys only
2409 track->mFastIndex = -1;
2410 }
2411 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2412 if (chain != 0) {
2413 chain->decTrackCnt();
2414 }
2415}
2416
2417String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2418{
Eric Laurent81784c32012-11-19 14:55:58 -08002419 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002420 String8 out_s8;
2421 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2422 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002423 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002424 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002425}
2426
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002427void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002428 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2429 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002430
Eric Laurent73e26b62015-04-27 16:55:58 -07002431 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002432
2433 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002434 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002435 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002436 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002437 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002438 desc->mChannelMask = mChannelMask;
2439 desc->mSamplingRate = mSampleRate;
2440 desc->mFormat = mFormat;
2441 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002442 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002443 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002444 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002445 break;
2446
Eric Laurent73e26b62015-04-27 16:55:58 -07002447 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002448 default:
2449 break;
2450 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002451 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002452}
2453
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002454void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002455{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002456 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457}
2458
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002459void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002460{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002461 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462}
2463
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002464void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002465{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002466 mCallbackThread->setAsyncError();
2467}
2468
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002470{
2471 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002472 // reject out of sequence requests
2473 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2474 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002475 mWaitWorkCV.signal();
2476 }
2477}
2478
Eric Laurent3b4529e2013-09-05 18:09:19 -07002479void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002480{
2481 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002482 // reject out of sequence requests
2483 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002484 // Register discontinuity when HW drain is completed because that can cause
2485 // the timestamp frame position to reset to 0 for direct and offload threads.
2486 // (Out of sequence requests are ignored, since the discontinuity would be handled
2487 // elsewhere, e.g. in flush).
2488 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002489 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002490 mWaitWorkCV.signal();
2491 }
2492}
2493
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002494void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002495{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002496 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002497 mSampleRate = mOutput->getSampleRate();
2498 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002499 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002500 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002501 }
Andy Hung9a592762014-07-21 21:56:01 -07002502 if ((mType == MIXER || mType == DUPLICATING)
2503 && !isValidPcmSinkChannelMask(mChannelMask)) {
2504 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2505 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002506 }
Andy Hunge5412692014-05-16 11:25:07 -07002507 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002508
2509 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002510 status_t result = mOutput->stream->getFormat(&mHALFormat);
2511 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002512 // Get format from the shim, which will be different than the HAL format
2513 // if playing compressed audio over HDMI passthrough.
2514 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002515 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002516 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002517 }
Andy Hung6146c082014-03-18 11:56:15 -07002518 if ((mType == MIXER || mType == DUPLICATING)
2519 && !isValidPcmSinkFormat(mFormat)) {
2520 LOG_FATAL("HAL format %#x not supported for mixed output",
2521 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002522 }
Phil Burk062e67a2015-02-11 13:40:50 -08002523 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002524 result = mOutput->stream->getBufferSize(&mBufferSize);
2525 LOG_ALWAYS_FATAL_IF(result != OK,
2526 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002527 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002528 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002529 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002530 mFrameCount);
2531 }
2532
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002533 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2534 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002535 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002536 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002537 }
2538 }
2539
Eric Laurentd1f69b02014-12-15 14:33:13 -08002540 mHwSupportsPause = false;
2541 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002542 bool supportsPause = false, supportsResume = false;
2543 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2544 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002545 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002546 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002547 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002548 } else if (supportsResume) {
2549 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002550 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002551 }
2552 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002553 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2554 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2555 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002556
Andy Hungfbfc3952015-01-15 13:33:51 -08002557 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2558 // For best precision, we use float instead of the associated output
2559 // device format (typically PCM 16 bit).
2560
2561 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2562 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2563 mBufferSize = mFrameSize * mFrameCount;
2564
2565 // TODO: We currently use the associated output device channel mask and sample rate.
2566 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2567 // (if a valid mask) to avoid premature downmix.
2568 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2569 // instead of the output device sample rate to avoid loss of high frequency information.
2570 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2571 }
2572
Andy Hung09a50072014-02-27 14:30:47 -08002573 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002574 double multiplier = 1.0;
2575 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2576 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002577 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2578 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002579
Eric Laurent81784c32012-11-19 14:55:58 -08002580 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2581 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2582 maxNormalFrameCount = maxNormalFrameCount & ~15;
2583 if (maxNormalFrameCount < minNormalFrameCount) {
2584 maxNormalFrameCount = minNormalFrameCount;
2585 }
2586 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2587 if (multiplier <= 1.0) {
2588 multiplier = 1.0;
2589 } else if (multiplier <= 2.0) {
2590 if (2 * mFrameCount <= maxNormalFrameCount) {
2591 multiplier = 2.0;
2592 } else {
2593 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2594 }
2595 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002596 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002597 }
2598 }
2599 mNormalFrameCount = multiplier * mFrameCount;
2600 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002601 if (mType == MIXER || mType == DUPLICATING) {
2602 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2603 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002604 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002605 mNormalFrameCount);
2606
Andy Hung08fb1742015-05-31 23:22:10 -07002607 // Check if we want to throttle the processing to no more than 2x normal rate
2608 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002609 mThreadThrottleTimeMs = 0;
2610 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002611 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2612
Andy Hung010a1a12014-03-13 13:57:33 -07002613 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2614 // Originally this was int16_t[] array, need to remove legacy implications.
2615 free(mSinkBuffer);
2616 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002617 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2618 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2619 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002620 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002621
Andy Hung69aed5f2014-02-25 17:24:40 -08002622 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2623 // drives the output.
2624 free(mMixerBuffer);
2625 mMixerBuffer = NULL;
2626 if (mMixerBufferEnabled) {
2627 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2628 mMixerBufferSize = mNormalFrameCount * mChannelCount
2629 * audio_bytes_per_sample(mMixerBufferFormat);
2630 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2631 }
Andy Hung98ef9782014-03-04 14:46:50 -08002632 free(mEffectBuffer);
2633 mEffectBuffer = NULL;
2634 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002635 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002636 mEffectBufferSize = mNormalFrameCount * mChannelCount
2637 * audio_bytes_per_sample(mEffectBufferFormat);
2638 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2639 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002640
Eric Laurent81784c32012-11-19 14:55:58 -08002641 // force reconfiguration of effect chains and engines to take new buffer size and audio
2642 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002643 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002644 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2645 // matter.
2646 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2647 Vector< sp<EffectChain> > effectChains = mEffectChains;
2648 for (size_t i = 0; i < effectChains.size(); i ++) {
2649 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2650 }
2651}
2652
Kevin Rocard069c2712018-03-29 19:09:14 -07002653void AudioFlinger::PlaybackThread::updateMetadata_l()
2654{
Kevin Rocard12381092018-04-11 09:19:59 -07002655 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2656 return; // That should not happen
2657 }
2658 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2659 for (const sp<Track> &track : mActiveTracks) {
2660 // Do not short-circuit as all hasChanged states must be reset
2661 // as all the metadata are going to be sent
2662 hasChanged |= track->readAndClearHasChanged();
2663 }
2664 if (!hasChanged) {
2665 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002666 }
2667 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002668 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002669 for (const sp<Track> &track : mActiveTracks) {
2670 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002671 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002672 }
Kevin Rocard12381092018-04-11 09:19:59 -07002673 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002674}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002675
Kevin Rocard12381092018-04-11 09:19:59 -07002676void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2677 const StreamOutHalInterface::SourceMetadata& metadata)
2678{
2679 mOutput->stream->updateSourceMetadata(metadata);
2680};
2681
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002682status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002683{
2684 if (halFrames == NULL || dspFrames == NULL) {
2685 return BAD_VALUE;
2686 }
2687 Mutex::Autolock _l(mLock);
2688 if (initCheck() != NO_ERROR) {
2689 return INVALID_OPERATION;
2690 }
Andy Hung818e7a32016-02-16 18:08:07 -08002691 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002692 *halFrames = framesWritten;
2693
2694 if (isSuspended()) {
2695 // return an estimation of rendered frames when the output is suspended
2696 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002697 *dspFrames = (uint32_t)
2698 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002699 return NO_ERROR;
2700 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002701 status_t status;
2702 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002703 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002704 *dspFrames = (size_t)frames;
2705 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002706 }
2707}
2708
Eric Laurent4c415062016-06-17 16:14:16 -07002709// hasAudioSession_l() must be called with ThreadBase::mLock held
2710uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002711{
Eric Laurent81784c32012-11-19 14:55:58 -08002712 uint32_t result = 0;
2713 if (getEffectChain_l(sessionId) != 0) {
2714 result = EFFECT_SESSION;
2715 }
2716
2717 for (size_t i = 0; i < mTracks.size(); ++i) {
2718 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002719 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002720 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002721 if (track->isFastTrack()) {
2722 result |= FAST_SESSION;
2723 }
Eric Laurent81784c32012-11-19 14:55:58 -08002724 break;
2725 }
2726 }
2727
2728 return result;
2729}
2730
Glenn Kastend848eb42016-03-08 13:42:11 -08002731uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002732{
2733 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2734 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2735 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2736 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2737 }
2738 for (size_t i = 0; i < mTracks.size(); i++) {
2739 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002740 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002741 return AudioSystem::getStrategyForStream(track->streamType());
2742 }
2743 }
2744 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2745}
2746
2747
Phil Burk062e67a2015-02-11 13:40:50 -08002748AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002749{
2750 Mutex::Autolock _l(mLock);
2751 return mOutput;
2752}
2753
Phil Burk062e67a2015-02-11 13:40:50 -08002754AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002755{
2756 Mutex::Autolock _l(mLock);
2757 AudioStreamOut *output = mOutput;
2758 mOutput = NULL;
2759 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2760 // must push a NULL and wait for ack
2761 mOutputSink.clear();
2762 mPipeSink.clear();
2763 mNormalSink.clear();
2764 return output;
2765}
2766
2767// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002768sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
2770 if (mOutput == NULL) {
2771 return NULL;
2772 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002773 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002774}
2775
2776uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2777{
2778 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2779}
2780
2781status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2782{
2783 if (!isValidSyncEvent(event)) {
2784 return BAD_VALUE;
2785 }
2786
2787 Mutex::Autolock _l(mLock);
2788
2789 for (size_t i = 0; i < mTracks.size(); ++i) {
2790 sp<Track> track = mTracks[i];
2791 if (event->triggerSession() == track->sessionId()) {
2792 (void) track->setSyncEvent(event);
2793 return NO_ERROR;
2794 }
2795 }
2796
2797 return NAME_NOT_FOUND;
2798}
2799
2800bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2801{
2802 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2803}
2804
2805void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2806 const Vector< sp<Track> >& tracksToRemove)
2807{
2808 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002809 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002810 for (size_t i = 0 ; i < count ; i++) {
2811 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002812 if (track->isExternalTrack()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002813 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814#ifdef ADD_BATTERY_DATA
2815 // to track the speaker usage
2816 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2817#endif
2818 if (track->isTerminated()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07002819 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002820 }
Eric Laurent81784c32012-11-19 14:55:58 -08002821 }
2822 }
2823 }
Eric Laurent81784c32012-11-19 14:55:58 -08002824}
2825
2826void AudioFlinger::PlaybackThread::checkSilentMode_l()
2827{
2828 if (!mMasterMute) {
2829 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002830 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2831 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2832 return;
2833 }
Eric Laurent81784c32012-11-19 14:55:58 -08002834 if (property_get("ro.audio.silent", value, "0") > 0) {
2835 char *endptr;
2836 unsigned long ul = strtoul(value, &endptr, 0);
2837 if (*endptr == '\0' && ul != 0) {
2838 ALOGD("Silence is golden");
2839 // The setprop command will not allow a property to be changed after
2840 // the first time it is set, so we don't have to worry about un-muting.
2841 setMasterMute_l(true);
2842 }
2843 }
2844 }
2845}
2846
2847// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002848ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002849{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002850 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002851 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002852 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002853 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002854
2855 // If an NBAIO sink is present, use it to write the normal mixer's submix
2856 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002857
Andy Hung010a1a12014-03-13 13:57:33 -07002858 const size_t count = mBytesRemaining / mFrameSize;
2859
Simon Wilson2d590962012-11-29 15:18:50 -08002860 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002861 // update the setpoint when AudioFlinger::mScreenState changes
2862 uint32_t screenState = AudioFlinger::mScreenState;
2863 if (screenState != mScreenState) {
2864 mScreenState = screenState;
2865 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2866 if (pipe != NULL) {
2867 pipe->setAvgFrames((mScreenState & 1) ?
2868 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2869 }
2870 }
Andy Hung010a1a12014-03-13 13:57:33 -07002871 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002872 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002873 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002874 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002875#ifdef TEE_SINK
2876 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2877#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002878 } else {
2879 bytesWritten = framesWritten;
2880 }
2881 // otherwise use the HAL / AudioStreamOut directly
2882 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002884
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002886 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2887 mWriteAckSequence += 2;
2888 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002890 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002892 // FIXME We should have an implementation of timestamps for direct output threads.
2893 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002894 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002895
Eric Laurentbfb1b832013-01-07 09:53:42 -08002896 if (mUseAsyncWrite &&
2897 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2898 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002899 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002901 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902 }
Eric Laurent81784c32012-11-19 14:55:58 -08002903 }
2904
Eric Laurent81784c32012-11-19 14:55:58 -08002905 mNumWrites++;
2906 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002907 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 return bytesWritten;
2909}
2910
2911void AudioFlinger::PlaybackThread::threadLoop_drain()
2912{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002913 bool supportsDrain = false;
2914 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2916 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002917 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2918 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002920 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002922 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002923 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 }
2925}
2926
2927void AudioFlinger::PlaybackThread::threadLoop_exit()
2928{
Eric Laurent275e8e92014-11-30 15:14:47 -08002929 {
2930 Mutex::Autolock _l(mLock);
2931 for (size_t i = 0; i < mTracks.size(); i++) {
2932 sp<Track> track = mTracks[i];
2933 track->invalidate();
2934 }
Andy Hungdae27702016-10-31 14:01:16 -07002935 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2936 // After we exit there are no more track changes sent to BatteryNotifier
2937 // because that requires an active threadLoop.
2938 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2939 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002940 }
Eric Laurent81784c32012-11-19 14:55:58 -08002941}
2942
2943/*
2944The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002945 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002946 - mActiveSleepTimeUs from activeSleepTimeUs()
2947 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002948 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2949 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002950 - maxPeriod from frame count and sample rate (MIXER only)
2951
2952The parameters that affect these derived values are:
2953 - frame count
2954 - frame size
2955 - sample rate
2956 - device type: A2DP or not
2957 - device latency
2958 - format: PCM or not
2959 - active sleep time
2960 - idle sleep time
2961*/
2962
2963void AudioFlinger::PlaybackThread::cacheParameters_l()
2964{
Andy Hung25c2dac2014-02-27 14:56:00 -08002965 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002966 mActiveSleepTimeUs = activeSleepTimeUs();
2967 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002968
2969 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2970 // truncating audio when going to standby.
2971 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2972 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2973 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2974 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2975 }
2976 }
Eric Laurent81784c32012-11-19 14:55:58 -08002977}
2978
Eric Laurent13084622016-05-17 10:51:49 -07002979bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002980{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002981 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002982 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002983 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002984 size_t size = mTracks.size();
2985 for (size_t i = 0; i < size; i++) {
2986 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002987 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002988 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002989 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002990 }
2991 }
Eric Laurent13084622016-05-17 10:51:49 -07002992 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002993}
2994
Haynes Mathew George05317d22016-05-03 16:34:26 -07002995void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2996{
2997 Mutex::Autolock _l(mLock);
2998 invalidateTracks_l(streamType);
2999}
3000
Eric Laurent81784c32012-11-19 14:55:58 -08003001status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3002{
Glenn Kastend848eb42016-03-08 13:42:11 -08003003 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003004 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003005 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003006 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3007 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3008 &halInBuffer);
3009 if (result != OK) return result;
3010 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003011 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003012 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003013 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003014 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003015 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003016 if (mType != DIRECT) {
3017 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003018 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003019 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003020 &halInBuffer);
3021 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003022#ifdef FLOAT_EFFECT_CHAIN
3023 buffer = halInBuffer->audioBuffer()->f32;
3024#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003025 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003026#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003027 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3028 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003029 }
3030
3031 // Attach all tracks with same session ID to this chain.
3032 for (size_t i = 0; i < mTracks.size(); ++i) {
3033 sp<Track> track = mTracks[i];
3034 if (session == track->sessionId()) {
3035 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3036 buffer);
3037 track->setMainBuffer(buffer);
3038 chain->incTrackCnt();
3039 }
3040 }
3041
3042 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003043 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003044 if (session == track->sessionId()) {
3045 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3046 chain->incActiveTrackCnt();
3047 }
3048 }
3049 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003050 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003051 chain->setInBuffer(halInBuffer);
3052 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003053 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003054 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003055 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3056 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003057 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003058 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003059 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003060 // Effect chain for other sessions are inserted at beginning of effect
3061 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003062 // sessions is not important.
3063 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3064 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3065 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003066 size_t size = mEffectChains.size();
3067 size_t i = 0;
3068 for (i = 0; i < size; i++) {
3069 if (mEffectChains[i]->sessionId() < session) {
3070 break;
3071 }
3072 }
3073 mEffectChains.insertAt(chain, i);
3074 checkSuspendOnAddEffectChain_l(chain);
3075
3076 return NO_ERROR;
3077}
3078
3079size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3080{
Glenn Kastend848eb42016-03-08 13:42:11 -08003081 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003082
3083 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3084
3085 for (size_t i = 0; i < mEffectChains.size(); i++) {
3086 if (chain == mEffectChains[i]) {
3087 mEffectChains.removeAt(i);
3088 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003089 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003090 if (session == track->sessionId()) {
3091 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3092 chain.get(), session);
3093 chain->decActiveTrackCnt();
3094 }
3095 }
3096
3097 // detach all tracks with same session ID from this chain
3098 for (size_t i = 0; i < mTracks.size(); ++i) {
3099 sp<Track> track = mTracks[i];
3100 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003101 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003102 chain->decTrackCnt();
3103 }
3104 }
3105 break;
3106 }
3107 }
3108 return mEffectChains.size();
3109}
3110
3111status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003112 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003113{
3114 Mutex::Autolock _l(mLock);
3115 return attachAuxEffect_l(track, EffectId);
3116}
3117
3118status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003119 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003120{
3121 status_t status = NO_ERROR;
3122
3123 if (EffectId == 0) {
3124 track->setAuxBuffer(0, NULL);
3125 } else {
3126 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3127 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3128 if (effect != 0) {
3129 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3130 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3131 } else {
3132 status = INVALID_OPERATION;
3133 }
3134 } else {
3135 status = BAD_VALUE;
3136 }
3137 }
3138 return status;
3139}
3140
3141void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3142{
3143 for (size_t i = 0; i < mTracks.size(); ++i) {
3144 sp<Track> track = mTracks[i];
3145 if (track->auxEffectId() == effectId) {
3146 attachAuxEffect_l(track, 0);
3147 }
3148 }
3149}
3150
3151bool AudioFlinger::PlaybackThread::threadLoop()
3152{
Glenn Kasten388d5712017-04-07 14:38:41 -07003153 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003154
Eric Laurent81784c32012-11-19 14:55:58 -08003155 Vector< sp<Track> > tracksToRemove;
3156
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003157 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003158 nsecs_t lastWriteFinished = -1; // time last server write completed
3159 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003160
3161 // MIXER
3162 nsecs_t lastWarning = 0;
3163
3164 // DUPLICATING
3165 // FIXME could this be made local to while loop?
3166 writeFrames = 0;
3167
3168 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003169 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003170
3171 if (mType == MIXER) {
3172 sleepTimeShift = 0;
3173 }
3174
3175 CpuStats cpuStats;
3176 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3177
3178 acquireWakeLock();
3179
Glenn Kasteneef598c2017-04-03 14:41:13 -07003180 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3181 // thread associated with this PlaybackThread.
3182 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3183 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003184 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3185 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003186 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003187 const char *logString = NULL;
3188
rago1bb90822017-05-02 18:31:48 -07003189 // Estimated time for next buffer to be written to hal. This is used only on
3190 // suspended mode (for now) to help schedule the wait time until next iteration.
3191 nsecs_t timeLoopNextNs = 0;
3192
Eric Laurent664539d2013-09-23 18:24:31 -07003193 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003194
Andy Hungf3234512018-07-03 14:51:47 -07003195 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3196 // TODO: add confirmation checks:
3197 // 1) DIRECT threads and linear PCM format really resets to 0?
3198 // 2) Is frame count really valid if not linear pcm?
3199 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3200 if (mType == OFFLOAD || mType == DIRECT) {
3201 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3202 }
3203
Eric Laurent81784c32012-11-19 14:55:58 -08003204 while (!exitPending())
3205 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003206 // Log merge requests are performed during AudioFlinger binder transactions, but
3207 // that does not cover audio playback. It's requested here for that reason.
3208 mAudioFlinger->requestLogMerge();
3209
Eric Laurent81784c32012-11-19 14:55:58 -08003210 cpuStats.sample(myName);
3211
3212 Vector< sp<EffectChain> > effectChains;
3213
Eric Laurent81784c32012-11-19 14:55:58 -08003214 { // scope for mLock
3215
3216 Mutex::Autolock _l(mLock);
3217
Eric Laurent021cf962014-05-13 10:18:14 -07003218 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003219
Glenn Kasteneef598c2017-04-03 14:41:13 -07003220 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003221 if (logString != NULL) {
3222 mNBLogWriter->logTimestamp();
3223 mNBLogWriter->log(logString);
3224 logString = NULL;
3225 }
3226
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003227 // Collect timestamp statistics for the Playback Thread types that support it.
3228 if (mType == MIXER
3229 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003230 || mType == DIRECT
3231 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003232 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003233 // and associate with the sink frames written out. We need
3234 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003235 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003236 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003237 if (mStandby) {
3238 mTimestampVerifier.discontinuity();
3239 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3240 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3241 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3242 mSampleRate);
Andy Hung818e7a32016-02-16 18:08:07 -08003243 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003244 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003245
3246 // We keep track of the last valid kernel position in case we are in underrun
3247 // and the normal mixer period is the same as the fast mixer period, or there
3248 // is some error from the HAL.
3249 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3250 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3251 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3252 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3253 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3254
3255 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3256 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3257 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3258 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003259 }
3260
3261 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3262 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003263 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003264 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003265 }
3266
Andy Hung818e7a32016-02-16 18:08:07 -08003267 // copy over kernel info
3268 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003269 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3270 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003271 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3272 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003273 } else {
3274 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003275 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003276
Andy Hungc54b1ff2016-02-23 14:07:07 -08003277 // mFramesWritten for non-offloaded tracks are contiguous
3278 // even after standby() is called. This is useful for the track frame
3279 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003280 bool serverLocationUpdate = false;
3281 if (mFramesWritten != lastFramesWritten) {
3282 serverLocationUpdate = true;
3283 lastFramesWritten = mFramesWritten;
3284 }
3285 // Only update timestamps if there is a meaningful change.
3286 // Either the kernel timestamp must be valid or we have written something.
3287 if (kernelLocationUpdate || serverLocationUpdate) {
3288 if (serverLocationUpdate) {
3289 // use the time before we called the HAL write - it is a bit more accurate
3290 // to when the server last read data than the current time here.
3291 //
3292 // If we haven't written anything, mLastWriteTime will be -1
3293 // and we use systemTime().
3294 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3295 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3296 ? systemTime() : mLastWriteTime;
3297 }
Andy Hungdae27702016-10-31 14:01:16 -07003298
3299 for (const sp<Track> &t : mActiveTracks) {
3300 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003301 t->updateTrackFrameInfo(
3302 t->mAudioTrackServerProxy->framesReleased(),
3303 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003304 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003305 mTimestamp);
3306 }
Andy Hunge10393e2015-06-12 13:59:33 -07003307 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003308 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003309 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003310#if 0
3311 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003312 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003313 timespec ts;
3314 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003315 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003316 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003317 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003318 }
3319 ++z;
3320#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003321 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003322 if (mSignalPending) {
3323 // A signal was raised while we were unlocked
3324 mSignalPending = false;
3325 } else if (waitingAsyncCallback_l()) {
3326 if (exitPending()) {
3327 break;
3328 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003329 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003330 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003331 releaseWakeLock_l();
3332 released = true;
3333 }
Andy Hung10cbff12017-02-21 17:30:14 -08003334
3335 const int64_t waitNs = computeWaitTimeNs_l();
3336 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3337 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3338 if (status == TIMED_OUT) {
3339 mSignalPending = true; // if timeout recheck everything
3340 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003341 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003342 if (released) {
3343 acquireWakeLock_l();
3344 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003345 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3346 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003347
3348 continue;
3349 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003350 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003351 isSuspended()) {
3352 // put audio hardware into standby after short delay
3353 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003354
3355 threadLoop_standby();
3356
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003357 // This is where we go into standby
3358 if (!mStandby) {
3359 LOG_AUDIO_STATE();
3360 }
Eric Laurent81784c32012-11-19 14:55:58 -08003361 mStandby = true;
3362 }
3363
3364 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3365 // we're about to wait, flush the binder command buffer
3366 IPCThreadState::self()->flushCommands();
3367
3368 clearOutputTracks();
3369
3370 if (exitPending()) {
3371 break;
3372 }
3373
3374 releaseWakeLock_l();
3375 // wait until we have something to do...
3376 ALOGV("%s going to sleep", myName.string());
3377 mWaitWorkCV.wait(mLock);
3378 ALOGV("%s waking up", myName.string());
3379 acquireWakeLock_l();
3380
3381 mMixerStatus = MIXER_IDLE;
3382 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3383 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003384 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003385 checkSilentMode_l();
3386
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003387 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3388 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003389 if (mType == MIXER) {
3390 sleepTimeShift = 0;
3391 }
3392
3393 continue;
3394 }
3395 }
Eric Laurent81784c32012-11-19 14:55:58 -08003396 // mMixerStatusIgnoringFastTracks is also updated internally
3397 mMixerStatus = prepareTracks_l(&tracksToRemove);
3398
Andy Hungdae27702016-10-31 14:01:16 -07003399 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003400
Kevin Rocard069c2712018-03-29 19:09:14 -07003401 updateMetadata_l();
3402
Eric Laurent81784c32012-11-19 14:55:58 -08003403 // prevent any changes in effect chain list and in each effect chain
3404 // during mixing and effect process as the audio buffers could be deleted
3405 // or modified if an effect is created or deleted
3406 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003407 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003408
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 if (mBytesRemaining == 0) {
3410 mCurrentWriteLength = 0;
3411 if (mMixerStatus == MIXER_TRACKS_READY) {
3412 // threadLoop_mix() sets mCurrentWriteLength
3413 threadLoop_mix();
3414 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3415 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003416 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417 // must be written to HAL
3418 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003419 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003420 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003421 }
3422 }
Andy Hung98ef9782014-03-04 14:46:50 -08003423 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003424 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003425 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3426 // or mSinkBuffer (if there are no effects).
3427 //
3428 // This is done pre-effects computation; if effects change to
3429 // support higher precision, this needs to move.
3430 //
3431 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003432 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003433 if (mMixerBufferValid) {
3434 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3435 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3436
Andy Hung2ddee192015-12-18 17:34:44 -08003437 // mono blend occurs for mixer threads only (not direct or offloaded)
3438 // and is handled here if we're going directly to the sink.
3439 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003440 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3441 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003442 }
3443
Andy Hung98ef9782014-03-04 14:46:50 -08003444 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3445 mNormalFrameCount * mChannelCount);
3446 }
3447
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 mBytesRemaining = mCurrentWriteLength;
3449 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003450 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3451 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3452 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3453 mBytesWritten += mBytesRemaining;
3454 mFramesWritten += framesRemaining;
3455 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 mBytesRemaining = 0;
3457 }
Eric Laurent81784c32012-11-19 14:55:58 -08003458
Eric Laurentbfb1b832013-01-07 09:53:42 -08003459 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003460 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003461 for (size_t i = 0; i < effectChains.size(); i ++) {
3462 effectChains[i]->process_l();
3463 }
Eric Laurent81784c32012-11-19 14:55:58 -08003464 }
3465 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003466 // Process effect chains for offloaded thread even if no audio
3467 // was read from audio track: process only updates effect state
3468 // and thus does have to be synchronized with audio writes but may have
3469 // to be called while waiting for async write callback
3470 if (mType == OFFLOAD) {
3471 for (size_t i = 0; i < effectChains.size(); i ++) {
3472 effectChains[i]->process_l();
3473 }
3474 }
Eric Laurent81784c32012-11-19 14:55:58 -08003475
Andy Hung98ef9782014-03-04 14:46:50 -08003476 // Only if the Effects buffer is enabled and there is data in the
3477 // Effects buffer (buffer valid), we need to
3478 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003479 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003480 if (mEffectBufferValid) {
3481 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003482
3483 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003484 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3485 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003486 }
3487
Andy Hung98ef9782014-03-04 14:46:50 -08003488 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3489 mNormalFrameCount * mChannelCount);
3490 }
3491
Eric Laurent81784c32012-11-19 14:55:58 -08003492 // enable changes in effect chain
3493 unlockEffectChains(effectChains);
3494
Eric Laurentbfb1b832013-01-07 09:53:42 -08003495 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003496 // mSleepTimeUs == 0 means we must write to audio hardware
3497 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003498 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003499 // We save lastWriteFinished here, as previousLastWriteFinished,
3500 // for throttling. On thread start, previousLastWriteFinished will be
3501 // set to -1, which properly results in no throttling after the first write.
3502 nsecs_t previousLastWriteFinished = lastWriteFinished;
3503 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003504 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003505 // FIXME rewrite to reduce number of system calls
3506 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003507 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003508 lastWriteFinished = systemTime();
3509 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 if (ret < 0) {
3511 mBytesRemaining = 0;
3512 } else {
3513 mBytesWritten += ret;
3514 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003515 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 }
3517 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3518 (mMixerStatus == MIXER_DRAIN_ALL)) {
3519 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003520 }
Andy Hung08fb1742015-05-31 23:22:10 -07003521 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003522 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003523 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003524 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003525 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003526 ATRACE_NAME("underrun");
3527 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003528 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003529 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003530 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003531 }
Andy Hung08fb1742015-05-31 23:22:10 -07003532
3533 if (mThreadThrottle
3534 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3535 && ret > 0) { // we wrote something
3536 // Limit MixerThread data processing to no more than twice the
3537 // expected processing rate.
3538 //
3539 // This helps prevent underruns with NuPlayer and other applications
3540 // which may set up buffers that are close to the minimum size, or use
3541 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3542 //
3543 // The throttle smooths out sudden large data drains from the device,
3544 // e.g. when it comes out of standby, which often causes problems with
3545 // (1) mixer threads without a fast mixer (which has its own warm-up)
3546 // (2) minimum buffer sized tracks (even if the track is full,
3547 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003548 //
3549 // Total time spent in last processing cycle equals time spent in
3550 // 1. threadLoop_write, as well as time spent in
3551 // 2. threadLoop_mix (significant for heavy mixing, especially
3552 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003553
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003554 // it's OK if deltaMs (and deltaNs) is an overestimate.
3555 nsecs_t deltaNs;
3556 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3557 __builtin_sub_overflow(
3558 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3559 const int32_t deltaMs = deltaNs / 1000000;
3560
Ivan Lozanoea04d392017-11-07 14:37:07 -08003561 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003562 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3563 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003564 // notify of throttle start on verbose log
3565 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3566 "mixer(%p) throttle begin:"
3567 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003568 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003569 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003570 // Throttle must be attributed to the previous mixer loop's write time
3571 // to allow back-to-back throttling.
3572 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003573 } else {
3574 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3575 if (diff > 0) {
3576 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003577 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003578 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3579 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003580 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003581 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3582 }
Andy Hung08fb1742015-05-31 23:22:10 -07003583 }
3584 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003585 }
Eric Laurent81784c32012-11-19 14:55:58 -08003586
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003588 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003589 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003590 // suspended requires accurate metering of sleep time.
3591 if (isSuspended()) {
3592 // advance by expected sleepTime
3593 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3594 const nsecs_t nowNs = systemTime();
3595
3596 // compute expected next time vs current time.
3597 // (negative deltas are treated as delays).
3598 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3599 if (deltaNs < -kMaxNextBufferDelayNs) {
3600 // Delays longer than the max allowed trigger a reset.
3601 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3602 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3603 timeLoopNextNs = nowNs + deltaNs;
3604 } else if (deltaNs < 0) {
3605 // Delays within the max delay allowed: zero the delta/sleepTime
3606 // to help the system catch up in the next iteration(s)
3607 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3608 deltaNs = 0;
3609 }
3610 // update sleep time (which is >= 0)
3611 mSleepTimeUs = deltaNs / 1000;
3612 }
Eric Laurente93cc032016-05-05 10:15:10 -07003613 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3614 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003615 }
Glenn Kastene7754022014-10-31 12:11:26 -07003616 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 }
Eric Laurent81784c32012-11-19 14:55:58 -08003618 }
3619
3620 // Finally let go of removed track(s), without the lock held
3621 // since we can't guarantee the destructors won't acquire that
3622 // same lock. This will also mutate and push a new fast mixer state.
3623 threadLoop_removeTracks(tracksToRemove);
3624 tracksToRemove.clear();
3625
3626 // FIXME I don't understand the need for this here;
3627 // it was in the original code but maybe the
3628 // assignment in saveOutputTracks() makes this unnecessary?
3629 clearOutputTracks();
3630
3631 // Effect chains will be actually deleted here if they were removed from
3632 // mEffectChains list during mixing or effects processing
3633 effectChains.clear();
3634
3635 // FIXME Note that the above .clear() is no longer necessary since effectChains
3636 // is now local to this block, but will keep it for now (at least until merge done).
3637 }
3638
Eric Laurentbfb1b832013-01-07 09:53:42 -08003639 threadLoop_exit();
3640
Eric Laurentcf817a22014-08-04 20:36:31 -07003641 if (!mStandby) {
3642 threadLoop_standby();
3643 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003644 }
3645
3646 releaseWakeLock();
3647
3648 ALOGV("Thread %p type %d exiting", this, mType);
3649 return false;
3650}
3651
Eric Laurentbfb1b832013-01-07 09:53:42 -08003652// removeTracks_l() must be called with ThreadBase::mLock held
3653void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3654{
3655 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003656 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003657 for (size_t i=0 ; i<count ; i++) {
3658 const sp<Track>& track = tracksToRemove.itemAt(i);
3659 mActiveTracks.remove(track);
3660 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3661 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3662 if (chain != 0) {
3663 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3664 track->sessionId());
3665 chain->decActiveTrackCnt();
3666 }
3667 if (track->isTerminated()) {
3668 removeTrack_l(track);
3669 }
3670 }
3671 }
3672
3673}
Eric Laurent81784c32012-11-19 14:55:58 -08003674
Eric Laurentaccc1472013-09-20 09:36:34 -07003675status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3676{
3677 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003678 ExtendedTimestamp ets;
3679 status_t status = mNormalSink->getTimestamp(ets);
3680 if (status == NO_ERROR) {
3681 status = ets.getBestTimestamp(&timestamp);
3682 }
3683 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003684 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003685 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003686 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003687 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003688 timestamp.mPosition = (uint32_t)position64;
3689 return NO_ERROR;
3690 }
3691 }
3692 return INVALID_OPERATION;
3693}
Eric Laurent1c333e22014-05-20 10:48:17 -07003694
Eric Laurent054d9d32015-04-24 08:48:48 -07003695status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3696 audio_patch_handle_t *handle)
3697{
Andy Hungf60abce2016-08-26 11:37:54 -07003698 status_t status;
3699 if (property_get_bool("af.patch_park", false /* default_value */)) {
3700 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3701 // or if HAL does not properly lock against access.
3702 AutoPark<FastMixer> park(mFastMixer);
3703 status = PlaybackThread::createAudioPatch_l(patch, handle);
3704 } else {
3705 status = PlaybackThread::createAudioPatch_l(patch, handle);
3706 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003707 return status;
3708}
3709
Eric Laurent1c333e22014-05-20 10:48:17 -07003710status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3711 audio_patch_handle_t *handle)
3712{
3713 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003714
3715 // store new device and send to effects
3716 audio_devices_t type = AUDIO_DEVICE_NONE;
3717 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3718 type |= patch->sinks[i].ext.device.type;
3719 }
3720
3721#ifdef ADD_BATTERY_DATA
3722 // when changing the audio output device, call addBatteryData to notify
3723 // the change
3724 if (mOutDevice != type) {
3725 uint32_t params = 0;
3726 // check whether speaker is on
3727 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3728 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003729 }
3730
Eric Laurent054d9d32015-04-24 08:48:48 -07003731 audio_devices_t deviceWithoutSpeaker
3732 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3733 // check if any other device (except speaker) is on
3734 if (type & deviceWithoutSpeaker) {
3735 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3736 }
3737
3738 if (params != 0) {
3739 addBatteryData(params);
3740 }
3741 }
3742#endif
3743
3744 for (size_t i = 0; i < mEffectChains.size(); i++) {
3745 mEffectChains[i]->setDevice_l(type);
3746 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003747
3748 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3749 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3750 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003751 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003752 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003753
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003754 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003755 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3756 status = hwDevice->createAudioPatch(patch->num_sources,
3757 patch->sources,
3758 patch->num_sinks,
3759 patch->sinks,
3760 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003761 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003762 char *address;
3763 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3764 //FIXME: we only support address on first sink with HAL version < 3.0
3765 address = audio_device_address_to_parameter(
3766 patch->sinks[0].ext.device.type,
3767 patch->sinks[0].ext.device.address);
3768 } else {
3769 address = (char *)calloc(1, 1);
3770 }
3771 AudioParameter param = AudioParameter(String8(address));
3772 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003773 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003774 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003775 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003776 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003777 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003778 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003779 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3780 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003781 return status;
3782}
3783
Eric Laurent054d9d32015-04-24 08:48:48 -07003784status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3785{
Andy Hungf60abce2016-08-26 11:37:54 -07003786 status_t status;
3787 if (property_get_bool("af.patch_park", false /* default_value */)) {
3788 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3789 // or if HAL does not properly lock against access.
3790 AutoPark<FastMixer> park(mFastMixer);
3791 status = PlaybackThread::releaseAudioPatch_l(handle);
3792 } else {
3793 status = PlaybackThread::releaseAudioPatch_l(handle);
3794 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003795 return status;
3796}
3797
Eric Laurent1c333e22014-05-20 10:48:17 -07003798status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3799{
3800 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003801
3802 mOutDevice = AUDIO_DEVICE_NONE;
3803
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003804 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003805 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3806 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003807 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003808 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003809 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003810 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003811 }
3812 return status;
3813}
3814
Eric Laurent83b88082014-06-20 18:31:16 -07003815void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3816{
3817 Mutex::Autolock _l(mLock);
3818 mTracks.add(track);
3819}
3820
3821void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3822{
3823 Mutex::Autolock _l(mLock);
3824 destroyTrack_l(track);
3825}
3826
Mikhail Naganovdc769682018-05-04 15:34:08 -07003827void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003828{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003829 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003830 config->role = AUDIO_PORT_ROLE_SOURCE;
3831 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3832 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003833 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3834 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3835 config->flags.output = mOutput->flags;
3836 }
Eric Laurent83b88082014-06-20 18:31:16 -07003837}
3838
Eric Laurent81784c32012-11-19 14:55:58 -08003839// ----------------------------------------------------------------------------
3840
3841AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003842 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3843 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003844 // mAudioMixer below
3845 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003846 mFastMixerFutex(0),
3847 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003848 // mOutputSink below
3849 // mPipeSink below
3850 // mNormalSink below
3851{
3852 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003853 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003854 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003855 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3856 mNormalFrameCount);
3857 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3858
Andy Hungfbfc3952015-01-15 13:33:51 -08003859 if (type == DUPLICATING) {
3860 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3861 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3862 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3863 return;
3864 }
Eric Laurent81784c32012-11-19 14:55:58 -08003865 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003866 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003867 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003868 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003869#if !LOG_NDEBUG
3870 ssize_t index =
3871#else
3872 (void)
3873#endif
3874 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 ALOG_ASSERT(index == 0);
3876
3877 // initialize fast mixer depending on configuration
3878 bool initFastMixer;
3879 switch (kUseFastMixer) {
3880 case FastMixer_Never:
3881 initFastMixer = false;
3882 break;
3883 case FastMixer_Always:
3884 initFastMixer = true;
3885 break;
3886 case FastMixer_Static:
3887 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003888 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3889 // where the period is less than an experimentally determined threshold that can be
3890 // scheduled reliably with CFS. However, the BT A2DP HAL is
3891 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3892 initFastMixer = mFrameCount < mNormalFrameCount
3893 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003894 break;
3895 }
Andy Hungfda69402017-02-15 14:33:12 -08003896 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3897 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3898 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003899 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003900 audio_format_t fastMixerFormat;
3901 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3902 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3903 } else {
3904 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3905 }
3906 if (mFormat != fastMixerFormat) {
3907 // change our Sink format to accept our intermediate precision
3908 mFormat = fastMixerFormat;
3909 free(mSinkBuffer);
3910 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3911 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3912 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3913 }
Eric Laurent81784c32012-11-19 14:55:58 -08003914
3915 // create a MonoPipe to connect our submix to FastMixer
3916 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003917
Andy Hung1258c1a2014-05-23 21:22:17 -07003918 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003919 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003920 format.mFormat = fastMixerFormat;
3921 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3922
Eric Laurent81784c32012-11-19 14:55:58 -08003923 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3924 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3925 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3926 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3927 const NBAIO_Format offers[1] = {format};
3928 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003929#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003930 ssize_t index =
3931#else
3932 (void)
3933#endif
3934 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003935 ALOG_ASSERT(index == 0);
3936 monoPipe->setAvgFrames((mScreenState & 1) ?
3937 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3938 mPipeSink = monoPipe;
3939
Eric Laurent81784c32012-11-19 14:55:58 -08003940 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003941 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003942 FastMixerStateQueue *sq = mFastMixer->sq();
3943#ifdef STATE_QUEUE_DUMP
3944 sq->setObserverDump(&mStateQueueObserverDump);
3945 sq->setMutatorDump(&mStateQueueMutatorDump);
3946#endif
3947 FastMixerState *state = sq->begin();
3948 FastTrack *fastTrack = &state->mFastTracks[0];
3949 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3950 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3951 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003952 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3953 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003954 fastTrack->mGeneration++;
3955 state->mFastTracksGen++;
3956 state->mTrackMask = 1;
3957 // fast mixer will use the HAL output sink
3958 state->mOutputSink = mOutputSink.get();
3959 state->mOutputSinkGen++;
3960 state->mFrameCount = mFrameCount;
3961 state->mCommand = FastMixerState::COLD_IDLE;
3962 // already done in constructor initialization list
3963 //mFastMixerFutex = 0;
3964 state->mColdFutexAddr = &mFastMixerFutex;
3965 state->mColdGen++;
3966 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003967 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3968 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003969 sq->end();
3970 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3971
3972 // start the fast mixer
3973 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3974 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003975 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003976 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003977
3978#ifdef AUDIO_WATCHDOG
3979 // create and start the watchdog
3980 mAudioWatchdog = new AudioWatchdog();
3981 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3982 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3983 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003984 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003985#endif
Andy Hung8946a282018-04-19 20:04:56 -07003986 } else {
3987#ifdef TEE_SINK
3988 // Only use the MixerThread tee if there is no FastMixer.
3989 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3990 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3991#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003992 }
3993
3994 switch (kUseFastMixer) {
3995 case FastMixer_Never:
3996 case FastMixer_Dynamic:
3997 mNormalSink = mOutputSink;
3998 break;
3999 case FastMixer_Always:
4000 mNormalSink = mPipeSink;
4001 break;
4002 case FastMixer_Static:
4003 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4004 break;
4005 }
4006}
4007
4008AudioFlinger::MixerThread::~MixerThread()
4009{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004010 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004011 FastMixerStateQueue *sq = mFastMixer->sq();
4012 FastMixerState *state = sq->begin();
4013 if (state->mCommand == FastMixerState::COLD_IDLE) {
4014 int32_t old = android_atomic_inc(&mFastMixerFutex);
4015 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004016 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004017 }
4018 }
4019 state->mCommand = FastMixerState::EXIT;
4020 sq->end();
4021 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4022 mFastMixer->join();
4023 // Though the fast mixer thread has exited, it's state queue is still valid.
4024 // We'll use that extract the final state which contains one remaining fast track
4025 // corresponding to our sub-mix.
4026 state = sq->begin();
4027 ALOG_ASSERT(state->mTrackMask == 1);
4028 FastTrack *fastTrack = &state->mFastTracks[0];
4029 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4030 delete fastTrack->mBufferProvider;
4031 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004032 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004033#ifdef AUDIO_WATCHDOG
4034 if (mAudioWatchdog != 0) {
4035 mAudioWatchdog->requestExit();
4036 mAudioWatchdog->requestExitAndWait();
4037 mAudioWatchdog.clear();
4038 }
4039#endif
4040 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004041 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004042 delete mAudioMixer;
4043}
4044
4045
4046uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4047{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004048 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004049 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4050 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4051 }
4052 return latency;
4053}
4054
4055
4056void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4057{
4058 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4059}
4060
Eric Laurentbfb1b832013-01-07 09:53:42 -08004061ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004062{
4063 // FIXME we should only do one push per cycle; confirm this is true
4064 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004065 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004066 FastMixerStateQueue *sq = mFastMixer->sq();
4067 FastMixerState *state = sq->begin();
4068 if (state->mCommand != FastMixerState::MIX_WRITE &&
4069 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4070 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004071
4072 // FIXME workaround for first HAL write being CPU bound on some devices
4073 ATRACE_BEGIN("write");
4074 mOutput->write((char *)mSinkBuffer, 0);
4075 ATRACE_END();
4076
Eric Laurent81784c32012-11-19 14:55:58 -08004077 int32_t old = android_atomic_inc(&mFastMixerFutex);
4078 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004079 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004080 }
4081#ifdef AUDIO_WATCHDOG
4082 if (mAudioWatchdog != 0) {
4083 mAudioWatchdog->resume();
4084 }
4085#endif
4086 }
4087 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004088#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004089 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004090 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004091#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004092 sq->end();
4093 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4094 if (kUseFastMixer == FastMixer_Dynamic) {
4095 mNormalSink = mPipeSink;
4096 }
4097 } else {
4098 sq->end(false /*didModify*/);
4099 }
4100 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004101 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004102}
4103
4104void AudioFlinger::MixerThread::threadLoop_standby()
4105{
4106 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004107 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004108 FastMixerStateQueue *sq = mFastMixer->sq();
4109 FastMixerState *state = sq->begin();
4110 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004111 // Report any frames trapped in the Monopipe
4112 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4113 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4114 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4115 "monoPipeWritten:%lld monoPipeLeft:%lld",
4116 (long long)mFramesWritten, (long long)mSuspendedFrames,
4117 (long long)mPipeSink->framesWritten(), pipeFrames);
4118 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4119
Eric Laurent81784c32012-11-19 14:55:58 -08004120 state->mCommand = FastMixerState::COLD_IDLE;
4121 state->mColdFutexAddr = &mFastMixerFutex;
4122 state->mColdGen++;
4123 mFastMixerFutex = 0;
4124 sq->end();
4125 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4126 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4127 if (kUseFastMixer == FastMixer_Dynamic) {
4128 mNormalSink = mOutputSink;
4129 }
4130#ifdef AUDIO_WATCHDOG
4131 if (mAudioWatchdog != 0) {
4132 mAudioWatchdog->pause();
4133 }
4134#endif
4135 } else {
4136 sq->end(false /*didModify*/);
4137 }
4138 }
4139 PlaybackThread::threadLoop_standby();
4140}
4141
Eric Laurentbfb1b832013-01-07 09:53:42 -08004142bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4143{
4144 return false;
4145}
4146
4147bool AudioFlinger::PlaybackThread::shouldStandby_l()
4148{
4149 return !mStandby;
4150}
4151
4152bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4153{
4154 Mutex::Autolock _l(mLock);
4155 return waitingAsyncCallback_l();
4156}
4157
Eric Laurent81784c32012-11-19 14:55:58 -08004158// shared by MIXER and DIRECT, overridden by DUPLICATING
4159void AudioFlinger::PlaybackThread::threadLoop_standby()
4160{
4161 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004162 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004164 // discard any pending drain or write ack by incrementing sequence
4165 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4166 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004167 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004168 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4169 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004171 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004172}
4173
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004174void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4175{
4176 ALOGV("signal playback thread");
4177 broadcast_l();
4178}
4179
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004180void AudioFlinger::PlaybackThread::onAsyncError()
4181{
4182 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4183 invalidateTracks((audio_stream_type_t)i);
4184 }
4185}
4186
Eric Laurent81784c32012-11-19 14:55:58 -08004187void AudioFlinger::MixerThread::threadLoop_mix()
4188{
Eric Laurent81784c32012-11-19 14:55:58 -08004189 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004190 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004191 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004192 // increase sleep time progressively when application underrun condition clears.
4193 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4194 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4195 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004196 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004197 sleepTimeShift--;
4198 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004199 mSleepTimeUs = 0;
4200 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004201 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004202
Eric Laurent81784c32012-11-19 14:55:58 -08004203}
4204
4205void AudioFlinger::MixerThread::threadLoop_sleepTime()
4206{
4207 // If no tracks are ready, sleep once for the duration of an output
4208 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004209 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004210 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004211 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4212 // Using the Monopipe availableToWrite, we estimate the
4213 // sleep time to retry for more data (before we underrun).
4214 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4215 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4216 const size_t pipeFrames = monoPipe->maxFrames();
4217 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4218 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4219 const size_t framesDelay = std::min(
4220 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4221 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4222 pipeFrames, framesLeft, framesDelay);
4223 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4224 } else {
4225 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4226 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4227 mSleepTimeUs = kMinThreadSleepTimeUs;
4228 }
4229 // reduce sleep time in case of consecutive application underruns to avoid
4230 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4231 // duration we would end up writing less data than needed by the audio HAL if
4232 // the condition persists.
4233 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4234 sleepTimeShift++;
4235 }
Eric Laurent81784c32012-11-19 14:55:58 -08004236 }
4237 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004238 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004239 }
4240 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004241 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4242 // before effects processing or output.
4243 if (mMixerBufferValid) {
4244 memset(mMixerBuffer, 0, mMixerBufferSize);
4245 } else {
4246 memset(mSinkBuffer, 0, mSinkBufferSize);
4247 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004248 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004249 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4250 "anticipated start");
4251 }
4252 // TODO add standby time extension fct of effect tail
4253}
4254
4255// prepareTracks_l() must be called with ThreadBase::mLock held
4256AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4257 Vector< sp<Track> > *tracksToRemove)
4258{
Andy Hung1bc088a2018-02-09 15:57:31 -08004259 // clean up deleted track names in AudioMixer before allocating new tracks
4260 (void)mTracks.processDeletedTrackNames([this](int name) {
4261 // for each name, destroy it in the AudioMixer
4262 if (mAudioMixer->exists(name)) {
4263 mAudioMixer->destroy(name);
4264 }
4265 });
4266 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004267
4268 mixer_state mixerStatus = MIXER_IDLE;
4269 // find out which tracks need to be processed
4270 size_t count = mActiveTracks.size();
4271 size_t mixedTracks = 0;
4272 size_t tracksWithEffect = 0;
4273 // counts only _active_ fast tracks
4274 size_t fastTracks = 0;
4275 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4276
4277 float masterVolume = mMasterVolume;
4278 bool masterMute = mMasterMute;
4279
4280 if (masterMute) {
4281 masterVolume = 0;
4282 }
4283 // Delegate master volume control to effect in output mix effect chain if needed
4284 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4285 if (chain != 0) {
4286 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4287 chain->setVolume_l(&v, &v);
4288 masterVolume = (float)((v + (1 << 23)) >> 24);
4289 chain.clear();
4290 }
4291
4292 // prepare a new state to push
4293 FastMixerStateQueue *sq = NULL;
4294 FastMixerState *state = NULL;
4295 bool didModify = false;
4296 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004297 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004298 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004299 sq = mFastMixer->sq();
4300 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004301 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004302 }
4303
Andy Hung69aed5f2014-02-25 17:24:40 -08004304 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004305 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004306
Andy Hungbd3b2b02018-05-21 10:53:11 -07004307 // DeferredOperations handles statistics after setting mixerStatus.
4308 class DeferredOperations {
4309 public:
4310 DeferredOperations(mixer_state *mixerStatus)
4311 : mMixerStatus(mixerStatus) { }
4312
4313 // when leaving scope, tally frames properly.
4314 ~DeferredOperations() {
4315 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4316 // because that is when the underrun occurs.
4317 // We do not distinguish between FastTracks and NormalTracks here.
4318 if (*mMixerStatus == MIXER_TRACKS_READY) {
4319 for (const auto &underrun : mUnderrunFrames) {
4320 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4321 underrun.second);
4322 }
4323 }
4324 }
4325
4326 // tallyUnderrunFrames() is called to update the track counters
4327 // with the number of underrun frames for a particular mixer period.
4328 // We defer tallying until we know the final mixer status.
4329 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4330 mUnderrunFrames.emplace_back(track, underrunFrames);
4331 }
4332
4333 private:
4334 const mixer_state * const mMixerStatus;
4335 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4336 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4337
Eric Laurent81784c32012-11-19 14:55:58 -08004338 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004339 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004340
4341 // this const just means the local variable doesn't change
4342 Track* const track = t.get();
4343
4344 // process fast tracks
4345 if (track->isFastTrack()) {
4346
4347 // It's theoretically possible (though unlikely) for a fast track to be created
4348 // and then removed within the same normal mix cycle. This is not a problem, as
4349 // the track never becomes active so it's fast mixer slot is never touched.
4350 // The converse, of removing an (active) track and then creating a new track
4351 // at the identical fast mixer slot within the same normal mix cycle,
4352 // is impossible because the slot isn't marked available until the end of each cycle.
4353 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004354 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004355 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4356 FastTrack *fastTrack = &state->mFastTracks[j];
4357
4358 // Determine whether the track is currently in underrun condition,
4359 // and whether it had a recent underrun.
4360 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4361 FastTrackUnderruns underruns = ftDump->mUnderruns;
4362 uint32_t recentFull = (underruns.mBitFields.mFull -
4363 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4364 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4365 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4366 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4367 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4368 uint32_t recentUnderruns = recentPartial + recentEmpty;
4369 track->mObservedUnderruns = underruns;
4370 // don't count underruns that occur while stopping or pausing
4371 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004372 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004373 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4374 recentUnderruns > 0) {
4375 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004376 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004377 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004378 // Immediately account for FastTrack underruns.
4379 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004380
4381 // This is similar to the state machine for normal tracks,
4382 // with a few modifications for fast tracks.
4383 bool isActive = true;
4384 switch (track->mState) {
4385 case TrackBase::STOPPING_1:
4386 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004387 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004388 track->mState = TrackBase::STOPPING_2;
4389 }
4390 break;
4391 case TrackBase::PAUSING:
4392 // ramp down is not yet implemented
4393 track->setPaused();
4394 break;
4395 case TrackBase::RESUMING:
4396 // ramp up is not yet implemented
4397 track->mState = TrackBase::ACTIVE;
4398 break;
4399 case TrackBase::ACTIVE:
4400 if (recentFull > 0 || recentPartial > 0) {
4401 // track has provided at least some frames recently: reset retry count
4402 track->mRetryCount = kMaxTrackRetries;
4403 }
4404 if (recentUnderruns == 0) {
4405 // no recent underruns: stay active
4406 break;
4407 }
4408 // there has recently been an underrun of some kind
4409 if (track->sharedBuffer() == 0) {
4410 // were any of the recent underruns "empty" (no frames available)?
4411 if (recentEmpty == 0) {
4412 // no, then ignore the partial underruns as they are allowed indefinitely
4413 break;
4414 }
4415 // there has recently been an "empty" underrun: decrement the retry counter
4416 if (--(track->mRetryCount) > 0) {
4417 break;
4418 }
4419 // indicate to client process that the track was disabled because of underrun;
4420 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004421 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004422 // remove from active list, but state remains ACTIVE [confusing but true]
4423 isActive = false;
4424 break;
4425 }
4426 // fall through
4427 case TrackBase::STOPPING_2:
4428 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004429 case TrackBase::STOPPED:
4430 case TrackBase::FLUSHED: // flush() while active
4431 // Check for presentation complete if track is inactive
4432 // We have consumed all the buffers of this track.
4433 // This would be incomplete if we auto-paused on underrun
4434 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004435 uint32_t latency = 0;
4436 status_t result = mOutput->stream->getLatency(&latency);
4437 ALOGE_IF(result != OK,
4438 "Error when retrieving output stream latency: %d", result);
4439 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004440 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004441 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4442 // track stays in active list until presentation is complete
4443 break;
4444 }
4445 }
4446 if (track->isStopping_2()) {
4447 track->mState = TrackBase::STOPPED;
4448 }
4449 if (track->isStopped()) {
4450 // Can't reset directly, as fast mixer is still polling this track
4451 // track->reset();
4452 // So instead mark this track as needing to be reset after push with ack
4453 resetMask |= 1 << i;
4454 }
4455 isActive = false;
4456 break;
4457 case TrackBase::IDLE:
4458 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004459 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004460 }
4461
4462 if (isActive) {
4463 // was it previously inactive?
4464 if (!(state->mTrackMask & (1 << j))) {
4465 ExtendedAudioBufferProvider *eabp = track;
4466 VolumeProvider *vp = track;
4467 fastTrack->mBufferProvider = eabp;
4468 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004469 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004470 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004471 fastTrack->mGeneration++;
4472 state->mTrackMask |= 1 << j;
4473 didModify = true;
4474 // no acknowledgement required for newly active tracks
4475 }
Kevin Rocard12381092018-04-11 09:19:59 -07004476 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004477 // cache the combined master volume and stream type volume for fast mixer; this
4478 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004479 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004480 proxy->framesReleased()).first;
4481 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004482 * mStreamTypes[track->streamType()].volume
4483 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004484 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004485 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4486 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4487 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4488 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004489 ++fastTracks;
4490 } else {
4491 // was it previously active?
4492 if (state->mTrackMask & (1 << j)) {
4493 fastTrack->mBufferProvider = NULL;
4494 fastTrack->mGeneration++;
4495 state->mTrackMask &= ~(1 << j);
4496 didModify = true;
4497 // If any fast tracks were removed, we must wait for acknowledgement
4498 // because we're about to decrement the last sp<> on those tracks.
4499 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4500 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004501 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4502 // AudioTrack may start (which may not be with a start() but with a write()
4503 // after underrun) and immediately paused or released. In that case the
4504 // FastTrack state hasn't had time to update.
4505 // TODO Remove the ALOGW when this theory is confirmed.
4506 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004507 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4508 j, track->mState, state->mTrackMask, recentUnderruns,
4509 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004510 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004511 }
4512 tracksToRemove->add(track);
4513 // Avoids a misleading display in dumpsys
4514 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4515 }
4516 continue;
4517 }
4518
4519 { // local variable scope to avoid goto warning
4520
4521 audio_track_cblk_t* cblk = track->cblk();
4522
4523 // The first time a track is added we wait
4524 // for all its buffers to be filled before processing it
4525 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004526
4527 // if an active track doesn't exist in the AudioMixer, create it.
4528 if (!mAudioMixer->exists(name)) {
4529 status_t status = mAudioMixer->create(
4530 name,
4531 track->mChannelMask,
4532 track->mFormat,
4533 track->mSessionId);
4534 if (status != OK) {
4535 ALOGW("%s: cannot create track name"
4536 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4537 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4538 tracksToRemove->add(track);
4539 track->invalidate(); // consider it dead.
4540 continue;
4541 }
4542 }
4543
Eric Laurent81784c32012-11-19 14:55:58 -08004544 // make sure that we have enough frames to mix one full buffer.
4545 // enforce this condition only once to enable draining the buffer in case the client
4546 // app does not call stop() and relies on underrun to stop:
4547 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4548 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004549 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004550 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004551 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004552
4553 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004554 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004555 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4556 // add frames already consumed but not yet released by the resampler
4557 // because mAudioTrackServerProxy->framesReady() will include these frames
4558 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4559
Eric Laurent81784c32012-11-19 14:55:58 -08004560 uint32_t minFrames = 1;
4561 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4562 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004563 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004564 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004565
4566 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004567 if (ATRACE_ENABLED()) {
4568 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004569 std::string traceName("nRdy");
4570 traceName += std::to_string(track->name());
4571 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004572 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004573 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004574 !track->isPaused() && !track->isTerminated())
4575 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004576 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004577
4578 mixedTracks++;
4579
Andy Hung69aed5f2014-02-25 17:24:40 -08004580 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4581 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004582 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004583 if (track->mainBuffer() != mSinkBuffer &&
4584 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004585 if (mEffectBufferEnabled) {
4586 mEffectBufferValid = true; // Later can set directly.
4587 }
Eric Laurent81784c32012-11-19 14:55:58 -08004588 chain = getEffectChain_l(track->sessionId());
4589 // Delegate volume control to effect in track effect chain if needed
4590 if (chain != 0) {
4591 tracksWithEffect++;
4592 } else {
4593 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4594 "session %d",
4595 name, track->sessionId());
4596 }
4597 }
4598
4599
4600 int param = AudioMixer::VOLUME;
4601 if (track->mFillingUpStatus == Track::FS_FILLED) {
4602 // no ramp for the first volume setting
4603 track->mFillingUpStatus = Track::FS_ACTIVE;
4604 if (track->mState == TrackBase::RESUMING) {
4605 track->mState = TrackBase::ACTIVE;
4606 param = AudioMixer::RAMP_VOLUME;
4607 }
4608 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004609 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004610 // FIXME should not make a decision based on mServer
4611 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004612 // If the track is stopped before the first frame was mixed,
4613 // do not apply ramp
4614 param = AudioMixer::RAMP_VOLUME;
4615 }
4616
4617 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004618 uint32_t vl, vr; // in U8.24 integer format
4619 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004620 // read original volumes with volume control
4621 float typeVolume = mStreamTypes[track->streamType()].volume;
4622 float v = masterVolume * typeVolume;
4623
Glenn Kastene4756fe2012-11-29 13:38:14 -08004624 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004625 vl = vr = 0;
4626 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004627 if (track->isPausing()) {
4628 track->setPaused();
4629 }
4630 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004631 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004632 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004633 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4634 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004635 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004636 if (vlf > GAIN_FLOAT_UNITY) {
4637 ALOGV("Track left volume out of range: %.3g", vlf);
4638 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004639 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004640 if (vrf > GAIN_FLOAT_UNITY) {
4641 ALOGV("Track right volume out of range: %.3g", vrf);
4642 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004643 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004644 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004645 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004646 // now apply the master volume and stream type volume and shaper volume
4647 vlf *= v * vh;
4648 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004649 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004650 // then derive vl and vr as U8.24 versions for the effect chain
4651 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4652 vl = (uint32_t) (scaleto8_24 * vlf);
4653 vr = (uint32_t) (scaleto8_24 * vrf);
4654 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004655 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004656 // send level comes from shared memory and so may be corrupt
4657 if (sendLevel > MAX_GAIN_INT) {
4658 ALOGV("Track send level out of range: %04X", sendLevel);
4659 sendLevel = MAX_GAIN_INT;
4660 }
Andy Hung6be49402014-05-30 10:42:03 -07004661 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4662 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004663 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004664
Kevin Rocard12381092018-04-11 09:19:59 -07004665 track->setFinalVolume((vrf + vlf) / 2.f);
4666
Eric Laurent81784c32012-11-19 14:55:58 -08004667 // Delegate volume control to effect in track effect chain if needed
4668 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4669 // Do not ramp volume if volume is controlled by effect
4670 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004671 // Update remaining floating point volume levels
4672 vlf = (float)vl / (1 << 24);
4673 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004674 track->mHasVolumeController = true;
4675 } else {
4676 // force no volume ramp when volume controller was just disabled or removed
4677 // from effect chain to avoid volume spike
4678 if (track->mHasVolumeController) {
4679 param = AudioMixer::VOLUME;
4680 }
4681 track->mHasVolumeController = false;
4682 }
4683
Eric Laurent7c29ec92017-09-20 17:54:22 -07004684 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4685 // still applied by the mixer.
4686 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4687 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4688 if (v != mLeftVolFloat) {
4689 status_t result = mOutput->stream->setVolume(v, v);
4690 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4691 if (result == OK) {
4692 mLeftVolFloat = v;
4693 }
4694 }
4695 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4696 // remove stream volume contribution from software volume.
4697 if (v != 0.0f && mLeftVolFloat == v) {
4698 vlf = min(1.0f, vlf / v);
4699 vrf = min(1.0f, vrf / v);
4700 vaf = min(1.0f, vaf / v);
4701 }
4702 }
Eric Laurent81784c32012-11-19 14:55:58 -08004703 // XXX: these things DON'T need to be done each time
4704 mAudioMixer->setBufferProvider(name, track);
4705 mAudioMixer->enable(name);
4706
Andy Hung6be49402014-05-30 10:42:03 -07004707 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4708 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4709 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004710 mAudioMixer->setParameter(
4711 name,
4712 AudioMixer::TRACK,
4713 AudioMixer::FORMAT, (void *)track->format());
4714 mAudioMixer->setParameter(
4715 name,
4716 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004717 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004718 mAudioMixer->setParameter(
4719 name,
4720 AudioMixer::TRACK,
4721 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004722 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004723 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004724 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004725 if (reqSampleRate == 0) {
4726 reqSampleRate = mSampleRate;
4727 } else if (reqSampleRate > maxSampleRate) {
4728 reqSampleRate = maxSampleRate;
4729 }
Eric Laurent81784c32012-11-19 14:55:58 -08004730 mAudioMixer->setParameter(
4731 name,
4732 AudioMixer::RESAMPLE,
4733 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004734 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004735
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004736 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004737 mAudioMixer->setParameter(
4738 name,
4739 AudioMixer::TIMESTRETCH,
4740 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004741 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004742
Andy Hung69aed5f2014-02-25 17:24:40 -08004743 /*
4744 * Select the appropriate output buffer for the track.
4745 *
Andy Hung98ef9782014-03-04 14:46:50 -08004746 * Tracks with effects go into their own effects chain buffer
4747 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004748 *
4749 * Other tracks can use mMixerBuffer for higher precision
4750 * channel accumulation. If this buffer is enabled
4751 * (mMixerBufferEnabled true), then selected tracks will accumulate
4752 * into it.
4753 *
4754 */
4755 if (mMixerBufferEnabled
4756 && (track->mainBuffer() == mSinkBuffer
4757 || track->mainBuffer() == mMixerBuffer)) {
4758 mAudioMixer->setParameter(
4759 name,
4760 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004761 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004762 mAudioMixer->setParameter(
4763 name,
4764 AudioMixer::TRACK,
4765 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4766 // TODO: override track->mainBuffer()?
4767 mMixerBufferValid = true;
4768 } else {
4769 mAudioMixer->setParameter(
4770 name,
4771 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004772 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004773 mAudioMixer->setParameter(
4774 name,
4775 AudioMixer::TRACK,
4776 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4777 }
Eric Laurent81784c32012-11-19 14:55:58 -08004778 mAudioMixer->setParameter(
4779 name,
4780 AudioMixer::TRACK,
4781 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4782
4783 // reset retry count
4784 track->mRetryCount = kMaxTrackRetries;
4785
4786 // If one track is ready, set the mixer ready if:
4787 // - the mixer was not ready during previous round OR
4788 // - no other track is not ready
4789 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4790 mixerStatus != MIXER_TRACKS_ENABLED) {
4791 mixerStatus = MIXER_TRACKS_READY;
4792 }
4793 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004794 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004795 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004796 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4797 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004798 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004799 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004800 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004801
Eric Laurent81784c32012-11-19 14:55:58 -08004802 // clear effect chain input buffer if an active track underruns to avoid sending
4803 // previous audio buffer again to effects
4804 chain = getEffectChain_l(track->sessionId());
4805 if (chain != 0) {
4806 chain->clearInputBuffer();
4807 }
4808
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004809 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004810 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4811 track->isStopped() || track->isPaused()) {
4812 // We have consumed all the buffers of this track.
4813 // Remove it from the list of active tracks.
4814 // TODO: use actual buffer filling status instead of latency when available from
4815 // audio HAL
4816 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004817 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004818 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4819 if (track->isStopped()) {
4820 track->reset();
4821 }
4822 tracksToRemove->add(track);
4823 }
4824 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004825 // No buffers for this track. Give it a few chances to
4826 // fill a buffer, then remove it from active list.
4827 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004828 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004829 tracksToRemove->add(track);
4830 // indicate to client process that the track was disabled because of underrun;
4831 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004832 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004833 // If one track is not ready, mark the mixer also not ready if:
4834 // - the mixer was ready during previous round OR
4835 // - no other track is ready
4836 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4837 mixerStatus != MIXER_TRACKS_READY) {
4838 mixerStatus = MIXER_TRACKS_ENABLED;
4839 }
4840 }
4841 mAudioMixer->disable(name);
4842 }
4843
4844 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004845
4846 }
4847
4848 // Push the new FastMixer state if necessary
4849 bool pauseAudioWatchdog = false;
4850 if (didModify) {
4851 state->mFastTracksGen++;
4852 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4853 if (kUseFastMixer == FastMixer_Dynamic &&
4854 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4855 state->mCommand = FastMixerState::COLD_IDLE;
4856 state->mColdFutexAddr = &mFastMixerFutex;
4857 state->mColdGen++;
4858 mFastMixerFutex = 0;
4859 if (kUseFastMixer == FastMixer_Dynamic) {
4860 mNormalSink = mOutputSink;
4861 }
4862 // If we go into cold idle, need to wait for acknowledgement
4863 // so that fast mixer stops doing I/O.
4864 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4865 pauseAudioWatchdog = true;
4866 }
Eric Laurent81784c32012-11-19 14:55:58 -08004867 }
4868 if (sq != NULL) {
4869 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004870 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4871 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4872 // when bringing the output sink into standby.)
4873 //
4874 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4875 //
4876 // This occurs with BT suspend when we idle the FastMixer with
4877 // active tracks, which may be added or removed.
4878 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004879 }
4880#ifdef AUDIO_WATCHDOG
4881 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4882 mAudioWatchdog->pause();
4883 }
4884#endif
4885
4886 // Now perform the deferred reset on fast tracks that have stopped
4887 while (resetMask != 0) {
4888 size_t i = __builtin_ctz(resetMask);
4889 ALOG_ASSERT(i < count);
4890 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004891 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004892 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4893 track->reset();
4894 }
4895
Andy Hung80d03d22018-04-10 10:32:11 -07004896 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4897 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4898 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4899 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4900 // See also the implementation of destroyTrack_l().
4901 for (const auto &track : *tracksToRemove) {
4902 const int name = track->name();
4903 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4904 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4905 }
4906 }
4907
Eric Laurent81784c32012-11-19 14:55:58 -08004908 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004909 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004910
Eric Laurent97d547d2014-09-02 14:45:53 -07004911 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4912 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004913 }
4914
4915 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004916 // as long as there are effects we should clear the effects buffer, to avoid
4917 // passing a non-clean buffer to the effect chain
4918 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004919 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004920 // sink or mix buffer must be cleared if all tracks are connected to an
4921 // effect chain as in this case the mixer will not write to the sink or mix buffer
4922 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004923 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4924 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004925 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004926 if (mMixerBufferValid) {
4927 memset(mMixerBuffer, 0, mMixerBufferSize);
4928 // TODO: In testing, mSinkBuffer below need not be cleared because
4929 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4930 // after mixing.
4931 //
4932 // To enforce this guarantee:
4933 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4934 // (mixedTracks == 0 && fastTracks > 0))
4935 // must imply MIXER_TRACKS_READY.
4936 // Later, we may clear buffers regardless, and skip much of this logic.
4937 }
Andy Hung98ef9782014-03-04 14:46:50 -08004938 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004939 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004940 }
4941
4942 // if any fast tracks, then status is ready
4943 mMixerStatusIgnoringFastTracks = mixerStatus;
4944 if (fastTracks > 0) {
4945 mixerStatus = MIXER_TRACKS_READY;
4946 }
4947 return mixerStatus;
4948}
4949
Eric Laurentad7dd962016-09-22 12:38:37 -07004950// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004951uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004952{
4953 uint32_t trackCount = 0;
4954 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004955 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004956 trackCount++;
4957 }
4958 }
4959 return trackCount;
4960}
4961
Andy Hung1bc088a2018-02-09 15:57:31 -08004962// isTrackAllowed_l() must be called with ThreadBase::mLock held
4963bool AudioFlinger::MixerThread::isTrackAllowed_l(
4964 audio_channel_mask_t channelMask, audio_format_t format,
4965 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004966{
Andy Hung1bc088a2018-02-09 15:57:31 -08004967 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4968 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004969 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004970 // Check validity as we don't call AudioMixer::create() here.
4971 if (!AudioMixer::isValidFormat(format)) {
4972 ALOGW("%s: invalid format: %#x", __func__, format);
4973 return false;
4974 }
4975 if (!AudioMixer::isValidChannelMask(channelMask)) {
4976 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4977 return false;
4978 }
4979 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004980}
4981
Eric Laurent10351942014-05-08 18:49:52 -07004982// checkForNewParameter_l() must be called with ThreadBase::mLock held
4983bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4984 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004985{
Eric Laurent81784c32012-11-19 14:55:58 -08004986 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004987 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004988
Eric Laurent10351942014-05-08 18:49:52 -07004989 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004990
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004991 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004992
Eric Laurent10351942014-05-08 18:49:52 -07004993 AudioParameter param = AudioParameter(keyValuePair);
4994 int value;
4995 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4996 reconfig = true;
4997 }
4998 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004999 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005000 status = BAD_VALUE;
5001 } else {
5002 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005003 reconfig = true;
5004 }
Eric Laurent10351942014-05-08 18:49:52 -07005005 }
5006 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005007 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005008 status = BAD_VALUE;
5009 } else {
5010 // no need to save value, since it's constant
5011 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005012 }
Eric Laurent10351942014-05-08 18:49:52 -07005013 }
5014 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5015 // do not accept frame count changes if tracks are open as the track buffer
5016 // size depends on frame count and correct behavior would not be guaranteed
5017 // if frame count is changed after track creation
5018 if (!mTracks.isEmpty()) {
5019 status = INVALID_OPERATION;
5020 } else {
5021 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005022 }
Eric Laurent10351942014-05-08 18:49:52 -07005023 }
5024 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005025#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005026 // when changing the audio output device, call addBatteryData to notify
5027 // the change
5028 if (mOutDevice != value) {
5029 uint32_t params = 0;
5030 // check whether speaker is on
5031 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5032 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005033 }
Eric Laurent10351942014-05-08 18:49:52 -07005034
5035 audio_devices_t deviceWithoutSpeaker
5036 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5037 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005038 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005039 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5040 }
5041
5042 if (params != 0) {
5043 addBatteryData(params);
5044 }
5045 }
Eric Laurent81784c32012-11-19 14:55:58 -08005046#endif
5047
Eric Laurent10351942014-05-08 18:49:52 -07005048 // forward device change to effects that have requested to be
5049 // aware of attached audio device.
5050 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005051 a2dpDeviceChanged =
5052 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005053 mOutDevice = value;
5054 for (size_t i = 0; i < mEffectChains.size(); i++) {
5055 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005056 }
5057 }
Eric Laurent10351942014-05-08 18:49:52 -07005058 }
Eric Laurent81784c32012-11-19 14:55:58 -08005059
Eric Laurent10351942014-05-08 18:49:52 -07005060 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005061 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005062 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005063 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005064 mStandby = true;
5065 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005066 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005067 }
Eric Laurent10351942014-05-08 18:49:52 -07005068 if (status == NO_ERROR && reconfig) {
5069 readOutputParameters_l();
5070 delete mAudioMixer;
5071 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005072 for (const auto &track : mTracks) {
5073 const int name = track->name();
5074 status_t status = mAudioMixer->create(
5075 name,
5076 track->mChannelMask,
5077 track->mFormat,
5078 track->mSessionId);
5079 ALOGW_IF(status != NO_ERROR,
5080 "%s: cannot create track name"
5081 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5082 __func__,
5083 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005084 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005085 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005086 }
Eric Laurent81784c32012-11-19 14:55:58 -08005087 }
5088
Eric Laurent42537be2016-01-08 17:16:42 -08005089 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005090}
5091
5092
5093void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5094{
Eric Laurent81784c32012-11-19 14:55:58 -08005095 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005096 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005097 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005098 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005099 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005100 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005101 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005102 } else {
5103 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005104 }
Eric Laurent81784c32012-11-19 14:55:58 -08005105
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005106 if (hasFastMixer()) {
5107 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5108
5109 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5110 // while we are dumping it. It may be inconsistent, but it won't mutate!
5111 // This is a large object so we place it on the heap.
5112 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5113 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
5114 copy->dump(fd);
5115 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08005116
5117#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005118 // Similar for state queue
5119 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5120 observerCopy.dump(fd);
5121 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5122 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005123#endif
5124
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005125#ifdef AUDIO_WATCHDOG
5126 if (mAudioWatchdog != 0) {
5127 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5128 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5129 wdCopy.dump(fd);
5130 }
5131#endif
5132
5133 } else {
5134 dprintf(fd, " No FastMixer\n");
5135 }
Eric Laurent81784c32012-11-19 14:55:58 -08005136}
5137
5138uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5139{
5140 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5141}
5142
5143uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5144{
5145 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5146}
5147
5148void AudioFlinger::MixerThread::cacheParameters_l()
5149{
5150 PlaybackThread::cacheParameters_l();
5151
5152 // FIXME: Relaxed timing because of a certain device that can't meet latency
5153 // Should be reduced to 2x after the vendor fixes the driver issue
5154 // increase threshold again due to low power audio mode. The way this warning
5155 // threshold is calculated and its usefulness should be reconsidered anyway.
5156 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5157}
5158
5159// ----------------------------------------------------------------------------
5160
5161AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005162 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5163 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005164{
5165}
5166
Eric Laurentbfb1b832013-01-07 09:53:42 -08005167AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5168 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005169 ThreadBase::type_t type, bool systemReady)
5170 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005171 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005172{
5173}
5174
Eric Laurent81784c32012-11-19 14:55:58 -08005175AudioFlinger::DirectOutputThread::~DirectOutputThread()
5176{
5177}
5178
Eric Laurent5850c4c2016-11-10 13:04:31 -08005179void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005180{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005181 float left, right;
5182
5183 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5184 left = right = 0;
5185 } else {
5186 float typeVolume = mStreamTypes[track->streamType()].volume;
5187 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005188 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005189
Andy Hung10cbff12017-02-21 17:30:14 -08005190 // Get volumeshaper scaling
5191 std::pair<float /* volume */, bool /* active */>
5192 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005193 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005194 v *= vh.first;
5195 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005196
Glenn Kastenc56f3422014-03-21 17:53:17 -07005197 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5198 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5199 if (left > GAIN_FLOAT_UNITY) {
5200 left = GAIN_FLOAT_UNITY;
5201 }
5202 left *= v;
5203 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5204 if (right > GAIN_FLOAT_UNITY) {
5205 right = GAIN_FLOAT_UNITY;
5206 }
5207 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005208 }
5209
5210 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005211 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005212 if (left != mLeftVolFloat || right != mRightVolFloat) {
5213 mLeftVolFloat = left;
5214 mRightVolFloat = right;
5215
5216 // Convert volumes from float to 8.24
5217 uint32_t vl = (uint32_t)(left * (1 << 24));
5218 uint32_t vr = (uint32_t)(right * (1 << 24));
5219
5220 // Delegate volume control to effect in track effect chain if needed
5221 // only one effect chain can be present on DirectOutputThread, so if
5222 // there is one, the track is connected to it
5223 if (!mEffectChains.isEmpty()) {
5224 mEffectChains[0]->setVolume_l(&vl, &vr);
5225 left = (float)vl / (1 << 24);
5226 right = (float)vr / (1 << 24);
5227 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005228 status_t result = mOutput->stream->setVolume(left, right);
5229 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005230 }
5231 }
5232}
5233
Phil Burk43b4dcc2015-06-09 16:53:44 -07005234void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5235{
5236 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005237 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005238
Eric Laurent0f0631e2015-07-06 18:01:25 -07005239 if (previousTrack != 0 && latestTrack != 0) {
5240 if (mType == DIRECT) {
5241 if (previousTrack.get() != latestTrack.get()) {
5242 mFlushPending = true;
5243 }
5244 } else /* mType == OFFLOAD */ {
5245 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5246 mFlushPending = true;
5247 }
5248 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005249 }
5250 PlaybackThread::onAddNewTrack_l();
5251}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005252
Eric Laurent81784c32012-11-19 14:55:58 -08005253AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5254 Vector< sp<Track> > *tracksToRemove
5255)
5256{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005257 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005258 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005259 bool doHwPause = false;
5260 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005261
5262 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005263 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005264 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005265 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005266 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005267 continue;
5268 }
5269
Eric Laurent5850c4c2016-11-10 13:04:31 -08005270 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005271#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005272 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005273#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005274 // Only consider last track started for volume and mixer state control.
5275 // In theory an older track could underrun and restart after the new one starts
5276 // but as we only care about the transition phase between two tracks on a
5277 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005278 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005279 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005280
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005281 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005282 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005283 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005284 doHwPause = true;
5285 mHwPaused = true;
5286 }
5287 tracksToRemove->add(track);
5288 } else if (track->isFlushPending()) {
5289 track->flushAck();
5290 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005291 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005292 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005293 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005294 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005295 if (last) {
5296 mLeftVolFloat = mRightVolFloat = -1.0;
5297 if (mHwPaused) {
5298 doHwResume = true;
5299 mHwPaused = false;
5300 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005301 }
5302 }
5303
Eric Laurent81784c32012-11-19 14:55:58 -08005304 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005305 // for all its buffers to be filled before processing it.
5306 // Allow draining the buffer in case the client
5307 // app does not call stop() and relies on underrun to stop:
5308 // hence the test on (track->mRetryCount > 1).
5309 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005310 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005311 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005312 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005313 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005314 minFrames = mNormalFrameCount;
5315 } else {
5316 minFrames = 1;
5317 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005318
Eric Laurentab5cdba2014-06-09 17:22:27 -07005319 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5320 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005321 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005322 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005323
5324 if (track->mFillingUpStatus == Track::FS_FILLED) {
5325 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005326 if (last) {
5327 // make sure processVolume_l() will apply new volume even if 0
5328 mLeftVolFloat = mRightVolFloat = -1.0;
5329 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005330 if (!mHwSupportsPause) {
5331 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005332 }
5333 }
5334
5335 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005336 processVolume_l(track, last);
5337 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005338 sp<Track> previousTrack = mPreviousTrack.promote();
5339 if (previousTrack != 0) {
5340 if (track != previousTrack.get()) {
5341 // Flush any data still being written from last track
5342 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005343 // Invalidate previous track to force a seek when resuming.
5344 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005345 }
5346 }
5347 mPreviousTrack = track;
5348
Eric Laurentd595b7c2013-04-03 17:27:56 -07005349 // reset retry count
5350 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005351 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005352 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005353 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005354 doHwResume = true;
5355 mHwPaused = false;
5356 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005357 }
Eric Laurent81784c32012-11-19 14:55:58 -08005358 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005359 // clear effect chain input buffer if the last active track started underruns
5360 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005361 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005362 mEffectChains[0]->clearInputBuffer();
5363 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005364 if (track->isStopping_1()) {
5365 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005366 if (last && mHwPaused) {
5367 doHwResume = true;
5368 mHwPaused = false;
5369 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005370 }
5371 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5372 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005373 // We have consumed all the buffers of this track.
5374 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005375 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005376 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005377 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5378 } else {
5379 audioHALFrames = 0;
5380 }
5381
Andy Hung818e7a32016-02-16 18:08:07 -08005382 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005383 if (mStandby || !last ||
5384 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005385 if (track->isStopping_2()) {
5386 track->mState = TrackBase::STOPPED;
5387 }
Eric Laurent81784c32012-11-19 14:55:58 -08005388 if (track->isStopped()) {
5389 track->reset();
5390 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005391 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005392 }
5393 } else {
5394 // No buffers for this track. Give it a few chances to
5395 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005396 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005397 if (--(track->mRetryCount) <= 0) {
5398 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005399 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005400 // indicate to client process that the track was disabled because of underrun;
5401 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005402 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005403 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005404 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5405 "minFrames = %u, mFormat = %#x",
5406 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005407 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005408 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005409 doHwPause = true;
5410 mHwPaused = true;
5411 }
Eric Laurent81784c32012-11-19 14:55:58 -08005412 }
5413 }
5414 }
5415 }
5416
Eric Laurentd1f69b02014-12-15 14:33:13 -08005417 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005418 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005419 for (size_t i = 0; i < mTracks.size(); i++) {
5420 if (mTracks[i]->isFlushPending()) {
5421 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005422 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005423 }
5424 }
5425 }
5426
5427 // make sure the pause/flush/resume sequence is executed in the right order.
5428 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5429 // before flush and then resume HW. This can happen in case of pause/flush/resume
5430 // if resume is received before pause is executed.
5431 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005432 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005433 status_t result = mOutput->stream->pause();
5434 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005435 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005436 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005437 flushHw_l();
5438 }
5439 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005440 status_t result = mOutput->stream->resume();
5441 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005442 }
Eric Laurent81784c32012-11-19 14:55:58 -08005443 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005444 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005445
5446 return mixerStatus;
5447}
5448
5449void AudioFlinger::DirectOutputThread::threadLoop_mix()
5450{
Eric Laurent81784c32012-11-19 14:55:58 -08005451 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005452 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005453 // output audio to hardware
5454 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005455 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005456 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005457 status_t status = mActiveTrack->getNextBuffer(&buffer);
5458 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005459 // no need to pad with 0 for compressed audio
5460 if (audio_has_proportional_frames(mFormat)) {
5461 memset(curBuf, 0, frameCount * mFrameSize);
5462 }
Eric Laurent81784c32012-11-19 14:55:58 -08005463 break;
5464 }
5465 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5466 frameCount -= buffer.frameCount;
5467 curBuf += buffer.frameCount * mFrameSize;
5468 mActiveTrack->releaseBuffer(&buffer);
5469 }
Andy Hung2098f272014-02-27 14:00:06 -08005470 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005471 mSleepTimeUs = 0;
5472 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005473 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005474}
5475
5476void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5477{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005478 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005479 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005480 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005481 return;
5482 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005483 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005484 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005485 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005486 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005487 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005488 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005489 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005490 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005491 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005492 }
5493}
5494
Eric Laurentd1f69b02014-12-15 14:33:13 -08005495void AudioFlinger::DirectOutputThread::threadLoop_exit()
5496{
5497 {
5498 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005499 for (size_t i = 0; i < mTracks.size(); i++) {
5500 if (mTracks[i]->isFlushPending()) {
5501 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005502 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005503 }
5504 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005505 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005506 flushHw_l();
5507 }
5508 }
5509 PlaybackThread::threadLoop_exit();
5510}
5511
5512// must be called with thread mutex locked
5513bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5514{
5515 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005516 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005517
vivek mehta9cd7ad12016-03-17 00:18:29 -07005518 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5519 return !mStandby;
5520 }
5521
Eric Laurentd1f69b02014-12-15 14:33:13 -08005522 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5523 // after a timeout and we will enter standby then.
5524 if (mTracks.size() > 0) {
5525 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005526 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5527 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005528 }
5529
Eric Laurent5cff4032015-05-26 13:49:58 -07005530 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005531}
5532
Eric Laurent10351942014-05-08 18:49:52 -07005533// checkForNewParameter_l() must be called with ThreadBase::mLock held
5534bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5535 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005536{
5537 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005538 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005539
Eric Laurent10351942014-05-08 18:49:52 -07005540 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005541
Eric Laurent10351942014-05-08 18:49:52 -07005542 AudioParameter param = AudioParameter(keyValuePair);
5543 int value;
5544 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5545 // forward device change to effects that have requested to be
5546 // aware of attached audio device.
5547 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005548 a2dpDeviceChanged =
5549 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005550 mOutDevice = value;
5551 for (size_t i = 0; i < mEffectChains.size(); i++) {
5552 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005553 }
5554 }
Eric Laurent81784c32012-11-19 14:55:58 -08005555 }
Eric Laurent10351942014-05-08 18:49:52 -07005556 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5557 // do not accept frame count changes if tracks are open as the track buffer
5558 // size depends on frame count and correct behavior would not be garantied
5559 // if frame count is changed after track creation
5560 if (!mTracks.isEmpty()) {
5561 status = INVALID_OPERATION;
5562 } else {
5563 reconfig = true;
5564 }
5565 }
5566 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005567 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005568 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005569 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005570 mStandby = true;
5571 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005572 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005573 }
5574 if (status == NO_ERROR && reconfig) {
5575 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005576 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005577 }
5578 }
5579
Eric Laurent42537be2016-01-08 17:16:42 -08005580 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005581}
5582
5583uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5584{
5585 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005586 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005587 time = PlaybackThread::activeSleepTimeUs();
5588 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005589 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005590 }
5591 return time;
5592}
5593
5594uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5595{
5596 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005597 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005598 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5599 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005600 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005601 }
5602 return time;
5603}
5604
5605uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5606{
5607 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005608 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005609 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5610 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005611 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005612 }
5613 return time;
5614}
5615
5616void AudioFlinger::DirectOutputThread::cacheParameters_l()
5617{
5618 PlaybackThread::cacheParameters_l();
5619
5620 // use shorter standby delay as on normal output to release
5621 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005622 // no delay on outputs with HW A/V sync
5623 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005624 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005625 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005626 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005627 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005628 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005629 }
Eric Laurent81784c32012-11-19 14:55:58 -08005630}
5631
Eric Laurente659ef42014-09-29 13:06:46 -07005632void AudioFlinger::DirectOutputThread::flushHw_l()
5633{
Phil Burk062e67a2015-02-11 13:40:50 -08005634 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005635 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005636 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005637 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005638}
5639
Andy Hung10cbff12017-02-21 17:30:14 -08005640int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5641 // If a VolumeShaper is active, we must wake up periodically to update volume.
5642 const int64_t NS_PER_MS = 1000000;
5643 return mVolumeShaperActive ?
5644 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5645}
5646
Eric Laurent81784c32012-11-19 14:55:58 -08005647// ----------------------------------------------------------------------------
5648
Eric Laurentbfb1b832013-01-07 09:53:42 -08005649AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005650 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005651 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005652 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005653 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005654 mDrainSequence(0),
5655 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005656{
5657}
5658
5659AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5660{
5661}
5662
5663void AudioFlinger::AsyncCallbackThread::onFirstRef()
5664{
5665 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5666}
5667
5668bool AudioFlinger::AsyncCallbackThread::threadLoop()
5669{
5670 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005671 uint32_t writeAckSequence;
5672 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005673 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674
5675 {
5676 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005677 while (!((mWriteAckSequence & 1) ||
5678 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005679 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005680 exitPending())) {
5681 mWaitWorkCV.wait(mLock);
5682 }
5683
Eric Laurentbfb1b832013-01-07 09:53:42 -08005684 if (exitPending()) {
5685 break;
5686 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005687 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5688 mWriteAckSequence, mDrainSequence);
5689 writeAckSequence = mWriteAckSequence;
5690 mWriteAckSequence &= ~1;
5691 drainSequence = mDrainSequence;
5692 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005693 asyncError = mAsyncError;
5694 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005695 }
5696 {
Eric Laurent4de95592013-09-26 15:28:21 -07005697 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5698 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005699 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005700 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005701 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005702 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005703 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005704 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005705 if (asyncError) {
5706 playbackThread->onAsyncError();
5707 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708 }
5709 }
5710 }
5711 return false;
5712}
5713
5714void AudioFlinger::AsyncCallbackThread::exit()
5715{
5716 ALOGV("AsyncCallbackThread::exit");
5717 Mutex::Autolock _l(mLock);
5718 requestExit();
5719 mWaitWorkCV.broadcast();
5720}
5721
Eric Laurent3b4529e2013-09-05 18:09:19 -07005722void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005723{
5724 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005725 // bit 0 is cleared
5726 mWriteAckSequence = sequence << 1;
5727}
5728
5729void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5730{
5731 Mutex::Autolock _l(mLock);
5732 // ignore unexpected callbacks
5733 if (mWriteAckSequence & 2) {
5734 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005735 mWaitWorkCV.signal();
5736 }
5737}
5738
Eric Laurent3b4529e2013-09-05 18:09:19 -07005739void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005740{
5741 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005742 // bit 0 is cleared
5743 mDrainSequence = sequence << 1;
5744}
5745
5746void AudioFlinger::AsyncCallbackThread::resetDraining()
5747{
5748 Mutex::Autolock _l(mLock);
5749 // ignore unexpected callbacks
5750 if (mDrainSequence & 2) {
5751 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005752 mWaitWorkCV.signal();
5753 }
5754}
5755
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005756void AudioFlinger::AsyncCallbackThread::setAsyncError()
5757{
5758 Mutex::Autolock _l(mLock);
5759 mAsyncError = true;
5760 mWaitWorkCV.signal();
5761}
5762
Eric Laurentbfb1b832013-01-07 09:53:42 -08005763
5764// ----------------------------------------------------------------------------
5765AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005766 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5767 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005768 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5769 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005770{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005771 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005772 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005773 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005774}
5775
Eric Laurentbfb1b832013-01-07 09:53:42 -08005776void AudioFlinger::OffloadThread::threadLoop_exit()
5777{
5778 if (mFlushPending || mHwPaused) {
5779 // If a flush is pending or track was paused, just discard buffered data
5780 flushHw_l();
5781 } else {
5782 mMixerStatus = MIXER_DRAIN_ALL;
5783 threadLoop_drain();
5784 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005785 if (mUseAsyncWrite) {
5786 ALOG_ASSERT(mCallbackThread != 0);
5787 mCallbackThread->exit();
5788 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005789 PlaybackThread::threadLoop_exit();
5790}
5791
5792AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5793 Vector< sp<Track> > *tracksToRemove
5794)
5795{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005796 size_t count = mActiveTracks.size();
5797
5798 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005799 bool doHwPause = false;
5800 bool doHwResume = false;
5801
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005802 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005803
Eric Laurentbfb1b832013-01-07 09:53:42 -08005804 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005805 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005806 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005807#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005808 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005809#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005810 // Only consider last track started for volume and mixer state control.
5811 // In theory an older track could underrun and restart after the new one starts
5812 // but as we only care about the transition phase between two tracks on a
5813 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005814 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005815 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005816
Haynes Mathew George7844f672014-01-15 12:32:55 -08005817 if (track->isInvalid()) {
5818 ALOGW("An invalidated track shouldn't be in active list");
5819 tracksToRemove->add(track);
5820 continue;
5821 }
5822
5823 if (track->mState == TrackBase::IDLE) {
5824 ALOGW("An idle track shouldn't be in active list");
5825 continue;
5826 }
5827
Eric Laurentbfb1b832013-01-07 09:53:42 -08005828 if (track->isPausing()) {
5829 track->setPaused();
5830 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005831 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005832 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005833 mHwPaused = true;
5834 }
5835 // If we were part way through writing the mixbuffer to
5836 // the HAL we must save this until we resume
5837 // BUG - this will be wrong if a different track is made active,
5838 // in that case we want to discard the pending data in the
5839 // mixbuffer and tell the client to present it again when the
5840 // track is resumed
5841 mPausedWriteLength = mCurrentWriteLength;
5842 mPausedBytesRemaining = mBytesRemaining;
5843 mBytesRemaining = 0; // stop writing
5844 }
5845 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005846 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005847 if (track->isStopping_1()) {
5848 track->mRetryCount = kMaxTrackStopRetriesOffload;
5849 } else {
5850 track->mRetryCount = kMaxTrackRetriesOffload;
5851 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005852 track->flushAck();
5853 if (last) {
5854 mFlushPending = true;
5855 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005856 } else if (track->isResumePending()){
5857 track->resumeAck();
5858 if (last) {
5859 if (mPausedBytesRemaining) {
5860 // Need to continue write that was interrupted
5861 mCurrentWriteLength = mPausedWriteLength;
5862 mBytesRemaining = mPausedBytesRemaining;
5863 mPausedBytesRemaining = 0;
5864 }
5865 if (mHwPaused) {
5866 doHwResume = true;
5867 mHwPaused = false;
5868 // threadLoop_mix() will handle the case that we need to
5869 // resume an interrupted write
5870 }
5871 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005872 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005873
Eric Laurent3df841a2016-07-15 15:15:40 -07005874 mLeftVolFloat = mRightVolFloat = -1.0;
5875
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005876 // Do not handle new data in this iteration even if track->framesReady()
5877 mixerStatus = MIXER_TRACKS_ENABLED;
5878 }
5879 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005880 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005881 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005882 if (track->mFillingUpStatus == Track::FS_FILLED) {
5883 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005884 if (last) {
5885 // make sure processVolume_l() will apply new volume even if 0
5886 mLeftVolFloat = mRightVolFloat = -1.0;
5887 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005888 }
5889
5890 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005891 sp<Track> previousTrack = mPreviousTrack.promote();
5892 if (previousTrack != 0) {
5893 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005894 // Flush any data still being written from last track
5895 mBytesRemaining = 0;
5896 if (mPausedBytesRemaining) {
5897 // Last track was paused so we also need to flush saved
5898 // mixbuffer state and invalidate track so that it will
5899 // re-submit that unwritten data when it is next resumed
5900 mPausedBytesRemaining = 0;
5901 // Invalidate is a bit drastic - would be more efficient
5902 // to have a flag to tell client that some of the
5903 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005904 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005905 }
5906 // flush data already sent to the DSP if changing audio session as audio
5907 // comes from a different source. Also invalidate previous track to force a
5908 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005909 if (previousTrack->sessionId() != track->sessionId()) {
5910 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005911 }
5912 }
5913 }
5914 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005915 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005916 if (track->isStopping_1()) {
5917 track->mRetryCount = kMaxTrackStopRetriesOffload;
5918 } else {
5919 track->mRetryCount = kMaxTrackRetriesOffload;
5920 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005921 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005922 mixerStatus = MIXER_TRACKS_READY;
5923 }
5924 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005925 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005926 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005927 if (--(track->mRetryCount) <= 0) {
5928 // Hardware buffer can hold a large amount of audio so we must
5929 // wait for all current track's data to drain before we say
5930 // that the track is stopped.
5931 if (mBytesRemaining == 0) {
5932 // Only start draining when all data in mixbuffer
5933 // has been written
5934 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5935 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5936 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5937 if (last && !mStandby) {
5938 // do not modify drain sequence if we are already draining. This happens
5939 // when resuming from pause after drain.
5940 if ((mDrainSequence & 1) == 0) {
5941 mSleepTimeUs = 0;
5942 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5943 mixerStatus = MIXER_DRAIN_TRACK;
5944 mDrainSequence += 2;
5945 }
5946 if (mHwPaused) {
5947 // It is possible to move from PAUSED to STOPPING_1 without
5948 // a resume so we must ensure hardware is running
5949 doHwResume = true;
5950 mHwPaused = false;
5951 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005952 }
5953 }
Eric Laurente93cc032016-05-05 10:15:10 -07005954 } else if (last) {
5955 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5956 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005957 }
5958 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005959 // Drain has completed or we are in standby, signal presentation complete
5960 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005961 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005962 uint32_t latency = 0;
5963 status_t result = mOutput->stream->getLatency(&latency);
5964 ALOGE_IF(result != OK,
5965 "Error when retrieving output stream latency: %d", result);
5966 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005967 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005968 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005969 track->presentationComplete(framesWritten, audioHALFrames);
5970 track->reset();
5971 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07005972 // DIRECT and OFFLOADED stop resets frame counts.
5973 if (!mUseAsyncWrite) {
5974 // If we don't get explicit drain notification we must
5975 // register discontinuity regardless of whether this is
5976 // the previous (!last) or the upcoming (last) track
5977 // to avoid skipping the discontinuity.
5978 mTimestampVerifier.discontinuity();
5979 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005980 }
5981 } else {
5982 // No buffers for this track. Give it a few chances to
5983 // fill a buffer, then remove it from active list.
5984 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005985 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005986 uint64_t position = 0;
5987 struct timespec unused;
5988 // The running check restarts the retry counter at least once.
5989 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5990 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5991 running = true;
5992 mOffloadUnderrunPosition = position;
5993 }
5994 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005995 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5996 (long long)position, (long long)mOffloadUnderrunPosition);
5997 }
5998 if (running) { // still running, give us more time.
5999 track->mRetryCount = kMaxTrackRetriesOffload;
6000 } else {
6001 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
6002 track->name());
6003 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006004 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006005 // it will then automatically call start() when data is available
6006 track->disable();
6007 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006008 } else if (last){
6009 mixerStatus = MIXER_TRACKS_ENABLED;
6010 }
6011 }
6012 }
6013 // compute volume for this track
6014 processVolume_l(track, last);
6015 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006016
Eric Laurentea0fade2013-10-04 16:23:48 -07006017 // make sure the pause/flush/resume sequence is executed in the right order.
6018 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6019 // before flush and then resume HW. This can happen in case of pause/flush/resume
6020 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006021 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006022 status_t result = mOutput->stream->pause();
6023 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006024 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006025 if (mFlushPending) {
6026 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006027 }
Eric Laurentfd477972013-10-25 18:10:40 -07006028 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006029 status_t result = mOutput->stream->resume();
6030 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006031 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006032
Eric Laurentbfb1b832013-01-07 09:53:42 -08006033 // remove all the tracks that need to be...
6034 removeTracks_l(*tracksToRemove);
6035
6036 return mixerStatus;
6037}
6038
Eric Laurentbfb1b832013-01-07 09:53:42 -08006039// must be called with thread mutex locked
6040bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6041{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006042 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6043 mWriteAckSequence, mDrainSequence);
6044 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006045 return true;
6046 }
6047 return false;
6048}
6049
Eric Laurentbfb1b832013-01-07 09:53:42 -08006050bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6051{
6052 Mutex::Autolock _l(mLock);
6053 return waitingAsyncCallback_l();
6054}
6055
6056void AudioFlinger::OffloadThread::flushHw_l()
6057{
Eric Laurente659ef42014-09-29 13:06:46 -07006058 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006059 // Flush anything still waiting in the mixbuffer
6060 mCurrentWriteLength = 0;
6061 mBytesRemaining = 0;
6062 mPausedWriteLength = 0;
6063 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006064 // reset bytes written count to reflect that DSP buffers are empty after flush.
6065 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006066 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006067
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006069 // discard any pending drain or write ack by incrementing sequence
6070 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6071 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006072 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006073 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6074 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006075 }
6076}
6077
Haynes Mathew George05317d22016-05-03 16:34:26 -07006078void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6079{
6080 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006081 if (PlaybackThread::invalidateTracks_l(streamType)) {
6082 mFlushPending = true;
6083 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006084}
6085
Eric Laurentbfb1b832013-01-07 09:53:42 -08006086// ----------------------------------------------------------------------------
6087
Eric Laurent81784c32012-11-19 14:55:58 -08006088AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006089 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006090 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006091 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006092 mWaitTimeMs(UINT_MAX)
6093{
6094 addOutputTrack(mainThread);
6095}
6096
6097AudioFlinger::DuplicatingThread::~DuplicatingThread()
6098{
6099 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6100 mOutputTracks[i]->destroy();
6101 }
6102}
6103
6104void AudioFlinger::DuplicatingThread::threadLoop_mix()
6105{
6106 // mix buffers...
6107 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006108 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006109 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006110 if (mMixerBufferValid) {
6111 memset(mMixerBuffer, 0, mMixerBufferSize);
6112 } else {
6113 memset(mSinkBuffer, 0, mSinkBufferSize);
6114 }
Eric Laurent81784c32012-11-19 14:55:58 -08006115 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006116 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006117 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006118 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006119 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006120}
6121
6122void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6123{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006124 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006125 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006126 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006127 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006128 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006129 }
6130 } else if (mBytesWritten != 0) {
6131 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6132 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006133 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006134 } else {
6135 // flush remaining overflow buffers in output tracks
6136 writeFrames = 0;
6137 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006138 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006139 }
6140}
6141
Eric Laurentbfb1b832013-01-07 09:53:42 -08006142ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006143{
6144 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006145 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6146
6147 // Consider the first OutputTrack for timestamp and frame counting.
6148
6149 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6150 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6151 // we always claim success.
6152 if (i == 0) {
6153 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6154 ALOGD_IF(correction != 0 && writeFrames != 0,
6155 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6156 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6157 mFramesWritten -= correction;
6158 }
6159
6160 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006161 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006162 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006163 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006164}
6165
6166void AudioFlinger::DuplicatingThread::threadLoop_standby()
6167{
6168 // DuplicatingThread implements standby by stopping all tracks
6169 for (size_t i = 0; i < outputTracks.size(); i++) {
6170 outputTracks[i]->stop();
6171 }
6172}
6173
Andy Hung1bc088a2018-02-09 15:57:31 -08006174void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6175{
6176 MixerThread::dumpInternals(fd, args);
6177
6178 std::stringstream ss;
6179 const size_t numTracks = mOutputTracks.size();
6180 ss << " " << numTracks << " OutputTracks";
6181 if (numTracks > 0) {
6182 ss << ":";
6183 for (const auto &track : mOutputTracks) {
6184 const sp<ThreadBase> thread = track->thread().promote();
6185 ss << " (" << track->name() << " : ";
6186 if (thread.get() != nullptr) {
6187 ss << thread.get() << ", " << thread->id();
6188 } else {
6189 ss << "null";
6190 }
6191 ss << ")";
6192 }
6193 }
6194 ss << "\n";
6195 std::string result = ss.str();
6196 write(fd, result.c_str(), result.size());
6197}
6198
Eric Laurent81784c32012-11-19 14:55:58 -08006199void AudioFlinger::DuplicatingThread::saveOutputTracks()
6200{
6201 outputTracks = mOutputTracks;
6202}
6203
6204void AudioFlinger::DuplicatingThread::clearOutputTracks()
6205{
6206 outputTracks.clear();
6207}
6208
6209void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6210{
6211 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006212 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6213 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6214 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6215 const size_t frameCount =
6216 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6217 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6218 // from different OutputTracks and their associated MixerThreads (e.g. one may
6219 // nearly empty and the other may be dropping data).
6220
6221 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006222 this,
6223 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006224 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006225 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006226 frameCount,
6227 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006228 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6229 if (status != NO_ERROR) {
6230 ALOGE("addOutputTrack() initCheck failed %d", status);
6231 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006232 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006233 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6234 mOutputTracks.add(outputTrack);
6235 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6236 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006237}
6238
6239void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6240{
6241 Mutex::Autolock _l(mLock);
6242 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6243 if (mOutputTracks[i]->thread() == thread) {
6244 mOutputTracks[i]->destroy();
6245 mOutputTracks.removeAt(i);
6246 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006247 if (thread->getOutput() == mOutput) {
6248 mOutput = NULL;
6249 }
Eric Laurent81784c32012-11-19 14:55:58 -08006250 return;
6251 }
6252 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006253 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006254}
6255
6256// caller must hold mLock
6257void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6258{
6259 mWaitTimeMs = UINT_MAX;
6260 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6261 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6262 if (strong != 0) {
6263 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6264 if (waitTimeMs < mWaitTimeMs) {
6265 mWaitTimeMs = waitTimeMs;
6266 }
6267 }
6268 }
6269}
6270
6271
6272bool AudioFlinger::DuplicatingThread::outputsReady(
6273 const SortedVector< sp<OutputTrack> > &outputTracks)
6274{
6275 for (size_t i = 0; i < outputTracks.size(); i++) {
6276 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6277 if (thread == 0) {
6278 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6279 outputTracks[i].get());
6280 return false;
6281 }
6282 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6283 // see note at standby() declaration
6284 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6285 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6286 thread.get());
6287 return false;
6288 }
6289 }
6290 return true;
6291}
6292
Kevin Rocard12381092018-04-11 09:19:59 -07006293void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6294 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006295{
Kevin Rocard12381092018-04-11 09:19:59 -07006296 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6297 outputTrack->setMetadatas(metadata.tracks);
6298 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006299}
6300
Eric Laurent81784c32012-11-19 14:55:58 -08006301uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6302{
6303 return (mWaitTimeMs * 1000) / 2;
6304}
6305
6306void AudioFlinger::DuplicatingThread::cacheParameters_l()
6307{
6308 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6309 updateWaitTime_l();
6310
6311 MixerThread::cacheParameters_l();
6312}
6313
Eric Laurent6acd1d42017-01-04 14:23:29 -08006314
Eric Laurent81784c32012-11-19 14:55:58 -08006315// ----------------------------------------------------------------------------
6316// Record
6317// ----------------------------------------------------------------------------
6318
6319AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6320 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006321 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006322 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006323 audio_devices_t inDevice,
6324 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006325 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006326 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006327 mInput(input),
6328 mActiveTracks(&this->mLocalLog),
6329 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006330 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006331 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006332 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6333 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006334 // mFastCapture below
6335 , mFastCaptureFutex(0)
6336 // mInputSource
6337 // mPipeSink
6338 // mPipeSource
6339 , mPipeFramesP2(0)
6340 // mPipeMemory
6341 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006342 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006343 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006344{
Glenn Kastend7dca052015-03-05 16:05:54 -08006345 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6346 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006347
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006348 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006349
6350 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006351 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006352 size_t numCounterOffers = 0;
6353 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006354#if !LOG_NDEBUG
6355 ssize_t index =
6356#else
6357 (void)
6358#endif
6359 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006360 ALOG_ASSERT(index == 0);
6361
6362 // initialize fast capture depending on configuration
6363 bool initFastCapture;
6364 switch (kUseFastCapture) {
6365 case FastCapture_Never:
6366 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006367 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006368 break;
6369 case FastCapture_Always:
6370 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006371 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006372 break;
6373 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006374 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006375 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6376 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6377 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006378 break;
6379 // case FastCapture_Dynamic:
6380 }
6381
6382 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006383 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006384 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006385 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6386 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006387 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006388 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006389 const sp<MemoryDealer> roHeap(readOnlyHeap());
6390 sp<IMemory> pipeMemory;
6391 if ((roHeap == 0) ||
6392 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006393 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6394 ALOGE("not enough memory for pipe buffer size=%zu; "
6395 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6396 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6397 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006398 goto failed;
6399 }
6400 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6401 memset(pipeBuffer, 0, pipeSize);
6402 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6403 const NBAIO_Format offers[1] = {format};
6404 size_t numCounterOffers = 0;
6405 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6406 ALOG_ASSERT(index == 0);
6407 mPipeSink = pipe;
6408 PipeReader *pipeReader = new PipeReader(*pipe);
6409 numCounterOffers = 0;
6410 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6411 ALOG_ASSERT(index == 0);
6412 mPipeSource = pipeReader;
6413 mPipeFramesP2 = pipeFramesP2;
6414 mPipeMemory = pipeMemory;
6415
6416 // create fast capture
6417 mFastCapture = new FastCapture();
6418 FastCaptureStateQueue *sq = mFastCapture->sq();
6419#ifdef STATE_QUEUE_DUMP
6420 // FIXME
6421#endif
6422 FastCaptureState *state = sq->begin();
6423 state->mCblk = NULL;
6424 state->mInputSource = mInputSource.get();
6425 state->mInputSourceGen++;
6426 state->mPipeSink = pipe;
6427 state->mPipeSinkGen++;
6428 state->mFrameCount = mFrameCount;
6429 state->mCommand = FastCaptureState::COLD_IDLE;
6430 // already done in constructor initialization list
6431 //mFastCaptureFutex = 0;
6432 state->mColdFutexAddr = &mFastCaptureFutex;
6433 state->mColdGen++;
6434 state->mDumpState = &mFastCaptureDumpState;
6435#ifdef TEE_SINK
6436 // FIXME
6437#endif
6438 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6439 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6440 sq->end();
6441 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6442
6443 // start the fast capture
6444 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6445 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006446 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006447 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006448#ifdef AUDIO_WATCHDOG
6449 // FIXME
6450#endif
6451
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006452 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006453 }
Andy Hung8946a282018-04-19 20:04:56 -07006454#ifdef TEE_SINK
6455 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6456 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6457#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006458failed: ;
6459
6460 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006461}
6462
Eric Laurent81784c32012-11-19 14:55:58 -08006463AudioFlinger::RecordThread::~RecordThread()
6464{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006465 if (mFastCapture != 0) {
6466 FastCaptureStateQueue *sq = mFastCapture->sq();
6467 FastCaptureState *state = sq->begin();
6468 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6469 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6470 if (old == -1) {
6471 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6472 }
6473 }
6474 state->mCommand = FastCaptureState::EXIT;
6475 sq->end();
6476 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6477 mFastCapture->join();
6478 mFastCapture.clear();
6479 }
6480 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006481 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006482 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006483}
6484
6485void AudioFlinger::RecordThread::onFirstRef()
6486{
Glenn Kastend7dca052015-03-05 16:05:54 -08006487 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006488}
6489
Eric Laurent555530a2017-02-07 18:17:24 -08006490void AudioFlinger::RecordThread::preExit()
6491{
6492 ALOGV(" preExit()");
6493 Mutex::Autolock _l(mLock);
6494 for (size_t i = 0; i < mTracks.size(); i++) {
6495 sp<RecordTrack> track = mTracks[i];
6496 track->invalidate();
6497 }
6498 mActiveTracks.clear();
6499 mStartStopCond.broadcast();
6500}
6501
Eric Laurent81784c32012-11-19 14:55:58 -08006502bool AudioFlinger::RecordThread::threadLoop()
6503{
Eric Laurent81784c32012-11-19 14:55:58 -08006504 nsecs_t lastWarning = 0;
6505
6506 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006507
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006508reacquire_wakelock:
6509 sp<RecordTrack> activeTrack;
6510 {
6511 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006512 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006513 }
6514
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006515 // used to request a deferred sleep, to be executed later while mutex is unlocked
6516 uint32_t sleepUs = 0;
6517
6518 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006519 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006520 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006521
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006522 // activeTracks accumulates a copy of a subset of mActiveTracks
6523 Vector< sp<RecordTrack> > activeTracks;
6524
Glenn Kasten735f45f2014-08-18 15:51:59 -07006525 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006526 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006527
Glenn Kasten735f45f2014-08-18 15:51:59 -07006528 // reference to a fast track which is about to be removed
6529 sp<RecordTrack> fastTrackToRemove;
6530
Eric Laurent81784c32012-11-19 14:55:58 -08006531 { // scope for mLock
6532 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006533
Eric Laurent021cf962014-05-13 10:18:14 -07006534 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006535
Eric Laurent000a4192014-01-29 15:17:32 -08006536 // check exitPending here because checkForNewParameters_l() and
6537 // checkForNewParameters_l() can temporarily release mLock
6538 if (exitPending()) {
6539 break;
6540 }
6541
Eric Laurent5c25d562016-07-13 17:17:45 -07006542 // sleep with mutex unlocked
6543 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006544 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006545 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6546 ATRACE_END();
6547 sleepUs = 0;
6548 continue;
6549 }
6550
Glenn Kasten2b806402013-11-20 16:37:38 -08006551 // if no active track(s), then standby and release wakelock
6552 size_t size = mActiveTracks.size();
6553 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006554 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006555 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006556 releaseWakeLock_l();
6557 ALOGV("RecordThread: loop stopping");
6558 // go to sleep
6559 mWaitWorkCV.wait(mLock);
6560 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006561 goto reacquire_wakelock;
6562 }
6563
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006564 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006565 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006566 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006567
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006568 activeTrack = mActiveTracks[i];
6569 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006570 if (activeTrack->isFastTrack()) {
6571 ALOG_ASSERT(fastTrackToRemove == 0);
6572 fastTrackToRemove = activeTrack;
6573 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006574 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006575 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006576 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006577 continue;
6578 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006579
6580 TrackBase::track_state activeTrackState = activeTrack->mState;
6581 switch (activeTrackState) {
6582
6583 case TrackBase::PAUSING:
6584 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006585 doBroadcast = true;
6586 size--;
6587 continue;
6588
6589 case TrackBase::STARTING_1:
6590 sleepUs = 10000;
6591 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006592 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006593 continue;
6594
6595 case TrackBase::STARTING_2:
6596 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006597 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006598 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006599 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006600 break;
6601
6602 case 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::IDLE:
6607 i++;
6608 continue;
6609
6610 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006611 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006612 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006613
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006614 activeTracks.add(activeTrack);
6615 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006616
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006617 if (activeTrack->isFastTrack()) {
6618 ALOG_ASSERT(!mFastTrackAvail);
6619 ALOG_ASSERT(fastTrack == 0);
6620 fastTrack = activeTrack;
6621 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006622 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006623
Andy Hungdae27702016-10-31 14:01:16 -07006624 mActiveTracks.updatePowerState(this);
6625
Kevin Rocard069c2712018-03-29 19:09:14 -07006626 updateMetadata_l();
6627
Eric Laurent5c25d562016-07-13 17:17:45 -07006628 if (allStopped) {
6629 standbyIfNotAlreadyInStandby();
6630 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006631 if (doBroadcast) {
6632 mStartStopCond.broadcast();
6633 }
6634
6635 // sleep if there are no active tracks to process
6636 if (activeTracks.size() == 0) {
6637 if (sleepUs == 0) {
6638 sleepUs = kRecordThreadSleepUs;
6639 }
6640 continue;
6641 }
6642 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006643
Eric Laurent81784c32012-11-19 14:55:58 -08006644 lockEffectChains_l(effectChains);
6645 }
6646
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006647 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006648
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006649 size_t size = effectChains.size();
6650 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006651 // thread mutex is not locked, but effect chain is locked
6652 effectChains[i]->process_l();
6653 }
6654
Glenn Kasten735f45f2014-08-18 15:51:59 -07006655 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006656 if (mFastCapture != 0) {
6657 FastCaptureStateQueue *sq = mFastCapture->sq();
6658 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006659 bool didModify = false;
6660 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006661 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6662 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6663 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6664 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6665 if (old == -1) {
6666 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6667 }
6668 }
6669 state->mCommand = FastCaptureState::READ_WRITE;
6670#if 0 // FIXME
6671 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006672 FastThreadDumpState::kSamplingNforLowRamDevice :
6673 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006674#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006675 didModify = true;
6676 }
6677 audio_track_cblk_t *cblkOld = state->mCblk;
6678 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6679 if (cblkNew != cblkOld) {
6680 state->mCblk = cblkNew;
6681 // block until acked if removing a fast track
6682 if (cblkOld != NULL) {
6683 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6684 }
6685 didModify = true;
6686 }
6687 sq->end(didModify);
6688 if (didModify) {
6689 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006690#if 0
6691 if (kUseFastCapture == FastCapture_Dynamic) {
6692 mNormalSource = mPipeSource;
6693 }
6694#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006695 }
6696 }
6697
Glenn Kasten735f45f2014-08-18 15:51:59 -07006698 // now run the fast track destructor with thread mutex unlocked
6699 fastTrackToRemove.clear();
6700
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006701 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6702 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6703 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6704 // If destination is non-contiguous, first read past the nominal end of buffer, then
6705 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006706
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006707 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006708 ssize_t framesRead;
6709
6710 // If an NBAIO source is present, use it to read the normal capture's data
6711 if (mPipeSource != 0) {
6712 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006713 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006714
6715 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6716 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6717 // we immediately retry the read() to get data and prevent another overflow.
6718 for (int retries = 0; retries <= 2; ++retries) {
6719 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6720 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6721 framesToRead);
6722 if (framesRead != OVERRUN) break;
6723 }
6724
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006725 const ssize_t availableToRead = mPipeSource->availableToRead();
6726 if (availableToRead >= 0) {
6727 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6728 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6729 "more frames to read than fifo size, %zd > %zu",
6730 availableToRead, mPipeFramesP2);
6731 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6732 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6733 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6734 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006735 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6736 }
6737 if (framesRead < 0) {
6738 status_t status = (status_t) framesRead;
6739 switch (status) {
6740 case OVERRUN:
6741 ALOGW("overrun on read from pipe");
6742 framesRead = 0;
6743 break;
6744 case NEGOTIATE:
6745 ALOGE("re-negotiation is needed");
6746 framesRead = -1; // Will cause an attempt to recover.
6747 break;
6748 default:
6749 ALOGE("unknown error %d on read from pipe", status);
6750 break;
6751 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006752 }
6753 // otherwise use the HAL / AudioStreamIn directly
6754 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006755 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006756 size_t bytesRead;
6757 status_t result = mInput->stream->read(
6758 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006759 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006760 if (result < 0) {
6761 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006762 } else {
6763 framesRead = bytesRead / mFrameSize;
6764 }
6765 }
6766
Andy Hung3f0c9022016-01-15 17:49:46 -08006767 // Update server timestamp with server stats
6768 // systemTime() is optional if the hardware supports timestamps.
6769 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6770 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6771
6772 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006773 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006774 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006775 if (mStandby) {
6776 mTimestampVerifier.discontinuity();
6777 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006778 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6779 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6780 // Note: In general record buffers should tend to be empty in
6781 // a properly running pipeline.
6782 //
6783 // Also, it is not advantageous to call get_presentation_position during the read
6784 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006785
6786 mTimestampVerifier.add(mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
6787 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
6788 mSampleRate);
6789 } else {
6790 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006791 }
6792 }
6793 // Use this to track timestamp information
6794 // ALOGD("%s", mTimestamp.toString().c_str());
6795
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006796 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006797 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006798 // Force input into standby so that it tries to recover at next read attempt
6799 inputStandBy();
6800 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006801 }
6802 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006803 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006804 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006805 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006806
Andy Hung8946a282018-04-19 20:04:56 -07006807#ifdef TEE_SINK
6808 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6809#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006810 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006811 {
6812 size_t part1 = mRsmpInFramesP2 - rear;
6813 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006814 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006815 (framesRead - part1) * mFrameSize);
6816 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006817 }
6818 rear = mRsmpInRear += framesRead;
6819
6820 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006821
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006822 // loop over each active track
6823 for (size_t i = 0; i < size; i++) {
6824 activeTrack = activeTracks[i];
6825
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006826 // skip fast tracks, as those are handled directly by FastCapture
6827 if (activeTrack->isFastTrack()) {
6828 continue;
6829 }
6830
Andy Hung73c02e42015-03-29 01:13:58 -07006831 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006832 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6833
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006834 enum {
6835 OVERRUN_UNKNOWN,
6836 OVERRUN_TRUE,
6837 OVERRUN_FALSE
6838 } overrun = OVERRUN_UNKNOWN;
6839
6840 // loop over getNextBuffer to handle circular sink
6841 for (;;) {
6842
6843 activeTrack->mSink.frameCount = ~0;
6844 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6845 size_t framesOut = activeTrack->mSink.frameCount;
6846 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6847
Andy Hung73c02e42015-03-29 01:13:58 -07006848 // check available frames and handle overrun conditions
6849 // if the record track isn't draining fast enough.
6850 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006851 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006852 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6853 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006854 overrun = OVERRUN_TRUE;
6855 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006856 if (framesOut == 0 || framesIn == 0) {
6857 break;
6858 }
6859
Andy Hung6770c6f2015-04-07 13:43:36 -07006860 // Don't allow framesOut to be larger than what is possible with resampling
6861 // from framesIn.
6862 // This isn't strictly necessary but helps limit buffer resizing in
6863 // RecordBufferConverter. TODO: remove when no longer needed.
6864 framesOut = min(framesOut,
6865 destinationFramesPossible(
6866 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006867
6868 if (activeTrack->isDirect()) {
6869 // No RecordBufferConverter used for compressed formats. Pass
6870 // straight from RecordThread buffer to RecordTrack buffer.
6871 AudioBufferProvider::Buffer buffer;
6872 buffer.frameCount = framesOut;
6873 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6874 if (status == OK && buffer.frameCount != 0) {
6875 ALOGV_IF(buffer.frameCount != framesOut,
6876 "%s() read less than expected (%zu vs %zu)",
6877 __func__, buffer.frameCount, framesOut);
6878 framesOut = buffer.frameCount;
6879 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6880 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6881 } else {
6882 framesOut = 0;
6883 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6884 __func__, status, buffer.frameCount);
6885 }
6886 } else {
6887 // process frames from the RecordThread buffer provider to the RecordTrack
6888 // buffer
6889 framesOut = activeTrack->mRecordBufferConverter->convert(
6890 activeTrack->mSink.raw,
6891 activeTrack->mResamplerBufferProvider,
6892 framesOut);
6893 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006894
6895 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6896 overrun = OVERRUN_FALSE;
6897 }
6898
6899 if (activeTrack->mFramesToDrop == 0) {
6900 if (framesOut > 0) {
6901 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006902 // Sanitize before releasing if the track has no access to the source data
6903 // An idle UID receives silence from non virtual devices until active
6904 if (activeTrack->isSilenced()) {
6905 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6906 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006907 activeTrack->releaseBuffer(&activeTrack->mSink);
6908 }
6909 } else {
6910 // FIXME could do a partial drop of framesOut
6911 if (activeTrack->mFramesToDrop > 0) {
6912 activeTrack->mFramesToDrop -= framesOut;
6913 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006914 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006915 }
6916 } else {
6917 activeTrack->mFramesToDrop += framesOut;
6918 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6919 activeTrack->mSyncStartEvent->isCancelled()) {
6920 ALOGW("Synced record %s, session %d, trigger session %d",
6921 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6922 activeTrack->sessionId(),
6923 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006924 activeTrack->mSyncStartEvent->triggerSession() :
6925 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006926 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006927 }
6928 }
6929 }
6930
6931 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006932 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006933 }
6934 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006935
6936 switch (overrun) {
6937 case OVERRUN_TRUE:
6938 // client isn't retrieving buffers fast enough
6939 if (!activeTrack->setOverflow()) {
6940 nsecs_t now = systemTime();
6941 // FIXME should lastWarning per track?
6942 if ((now - lastWarning) > kWarningThrottleNs) {
6943 ALOGW("RecordThread: buffer overflow");
6944 lastWarning = now;
6945 }
6946 }
6947 break;
6948 case OVERRUN_FALSE:
6949 activeTrack->clearOverflow();
6950 break;
6951 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006952 break;
6953 }
6954
Andy Hung3f0c9022016-01-15 17:49:46 -08006955 // update frame information and push timestamp out
6956 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006957 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006958 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6959 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006960 }
6961
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006962unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006963 // enable changes in effect chain
6964 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006965 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006966 }
6967
Glenn Kasten93e471f2013-08-19 08:40:07 -07006968 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006969
6970 {
6971 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006972 for (size_t i = 0; i < mTracks.size(); i++) {
6973 sp<RecordTrack> track = mTracks[i];
6974 track->invalidate();
6975 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006976 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006977 mStartStopCond.broadcast();
6978 }
6979
6980 releaseWakeLock();
6981
6982 ALOGV("RecordThread %p exiting", this);
6983 return false;
6984}
6985
Glenn Kasten93e471f2013-08-19 08:40:07 -07006986void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006987{
6988 if (!mStandby) {
6989 inputStandBy();
6990 mStandby = true;
6991 }
6992}
6993
6994void AudioFlinger::RecordThread::inputStandBy()
6995{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006996 // Idle the fast capture if it's currently running
6997 if (mFastCapture != 0) {
6998 FastCaptureStateQueue *sq = mFastCapture->sq();
6999 FastCaptureState *state = sq->begin();
7000 if (!(state->mCommand & FastCaptureState::IDLE)) {
7001 state->mCommand = FastCaptureState::COLD_IDLE;
7002 state->mColdFutexAddr = &mFastCaptureFutex;
7003 state->mColdGen++;
7004 mFastCaptureFutex = 0;
7005 sq->end();
7006 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7007 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7008#if 0
7009 if (kUseFastCapture == FastCapture_Dynamic) {
7010 // FIXME
7011 }
7012#endif
7013#ifdef AUDIO_WATCHDOG
7014 // FIXME
7015#endif
7016 } else {
7017 sq->end(false /*didModify*/);
7018 }
7019 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007020 status_t result = mInput->stream->standby();
7021 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007022
7023 // If going into standby, flush the pipe source.
7024 if (mPipeSource.get() != nullptr) {
7025 const ssize_t flushed = mPipeSource->flush();
7026 if (flushed > 0) {
7027 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7028 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7029 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7030 }
7031 }
Eric Laurent81784c32012-11-19 14:55:58 -08007032}
7033
Glenn Kasten05997e22014-03-13 15:08:33 -07007034// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007035sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007036 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007037 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007038 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007039 audio_format_t format,
7040 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007041 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007042 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007043 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007044 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007045 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007046 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007047 status_t *status,
7048 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007049{
Glenn Kasten74935e42013-12-19 08:56:45 -08007050 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007051 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007052 sp<RecordTrack> track;
7053 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007054 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007055 audio_input_flags_t requestedFlags = *flags;
7056 uint32_t sampleRate;
7057
7058 lStatus = initCheck();
7059 if (lStatus != NO_ERROR) {
7060 ALOGE("createRecordTrack_l() audio driver not initialized");
7061 goto Exit;
7062 }
7063
7064 if (*pSampleRate == 0) {
7065 *pSampleRate = mSampleRate;
7066 }
7067 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007068
7069 // special case for FAST flag considered OK if fast capture is present
7070 if (hasFastCapture()) {
7071 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7072 }
7073
Eric Laurentf14db3c2017-12-08 14:20:36 -08007074 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007075 if ((*flags & inputFlags) != *flags) {
7076 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7077 " input flags (%08x)",
7078 *flags, inputFlags);
7079 *flags = (audio_input_flags_t)(*flags & inputFlags);
7080 }
Eric Laurent81784c32012-11-19 14:55:58 -08007081
Glenn Kasten90e58b12013-07-31 16:16:02 -07007082 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007083 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007084 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007085 // we formerly checked for a callback handler (non-0 tid),
7086 // but that is no longer required for TRANSFER_OBTAIN mode
7087 //
Glenn Kasten74105912014-07-03 12:28:53 -07007088 // frame count is not specified, or is exactly the pipe depth
7089 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007090 // PCM data
7091 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007092 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007093 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007094 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007095 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007096 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007097 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007098 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007099 hasFastCapture() &&
7100 // there are sufficient fast track slots available
7101 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007102 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007103 // check compatibility with audio effects.
7104 Mutex::Autolock _l(mLock);
7105 // Do not accept FAST flag if the session has software effects
7106 sp<EffectChain> chain = getEffectChain_l(sessionId);
7107 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007108 audio_input_flags_t old = *flags;
7109 chain->checkInputFlagCompatibility(flags);
7110 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007111 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7112 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007113 }
7114 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007115 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007116 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7117 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007118 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007119 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7120 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007121 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007122 this, frameCount, mFrameCount, mPipeFramesP2,
7123 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007124 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007125 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007126 }
7127 }
7128
Eric Laurentf14db3c2017-12-08 14:20:36 -08007129 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7130 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7131 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7132 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7133 lStatus = BAD_TYPE;
7134 goto Exit;
7135 }
7136
Glenn Kasten74105912014-07-03 12:28:53 -07007137 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007138 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007139 // fast track: frame count is exactly the pipe depth
7140 frameCount = mPipeFramesP2;
7141 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007142 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007143 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007144 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7145 // or 20 ms if there is a fast capture
7146 // TODO This could be a roundupRatio inline, and const
7147 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7148 * sampleRate + mSampleRate - 1) / mSampleRate;
7149 // minimum number of notification periods is at least kMinNotifications,
7150 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7151 static const size_t kMinNotifications = 3;
7152 static const uint32_t kMinMs = 30;
7153 // TODO This could be a roundupRatio inline
7154 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7155 // TODO This could be a roundupRatio inline
7156 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7157 maxNotificationFrames;
7158 const size_t minFrameCount = maxNotificationFrames *
7159 max(kMinNotifications, minNotificationsByMs);
7160 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007161 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7162 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007163 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007164 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007165 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007166 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007167
7168 { // scope for mLock
7169 Mutex::Autolock _l(mLock);
7170
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007171 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007172 format, channelMask, frameCount,
7173 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007174 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007175
Glenn Kasten03003332013-08-06 15:40:54 -07007176 lStatus = track->initCheck();
7177 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007178 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007179 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007180 goto Exit;
7181 }
7182 mTracks.add(track);
7183
Eric Laurent05067782016-06-01 18:27:28 -07007184 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007185 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7186 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7187 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007188 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007189 }
Eric Laurent81784c32012-11-19 14:55:58 -08007190 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007191
Eric Laurent81784c32012-11-19 14:55:58 -08007192 lStatus = NO_ERROR;
7193
7194Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007195 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007196 return track;
7197}
7198
7199status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7200 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007201 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007202{
7203 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7204 sp<ThreadBase> strongMe = this;
7205 status_t status = NO_ERROR;
7206
7207 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007208 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007209 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007210 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007211 triggerSession,
7212 recordTrack->sessionId(),
7213 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007214 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007215 // Sync event can be cancelled by the trigger session if the track is not in a
7216 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007217 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007218 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007219 } else {
7220 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007221 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007222 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007223 }
7224 }
7225
7226 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007227 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007228 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007229 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7230 if (recordTrack->mState == TrackBase::PAUSING) {
7231 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007232 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007233 } else {
7234 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007235 }
7236 return status;
7237 }
7238
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007239 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7240 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7241 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007242 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007243 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007244 status_t status = NO_ERROR;
7245 if (recordTrack->isExternalTrack()) {
7246 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007247 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007248 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007249 mLock.lock();
7250 // FIXME should verify that recordTrack is still in mActiveTracks
7251 if (status != NO_ERROR) {
7252 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007253 recordTrack->clearSyncStartEvent();
7254 ALOGV("RecordThread::start error %d", status);
7255 return status;
7256 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007257 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007258 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007259 // Catch up with current buffer indices if thread is already running.
7260 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7261 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7262 // see previously buffered data before it called start(), but with greater risk of overrun.
7263
Andy Hung73c02e42015-03-29 01:13:58 -07007264 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007265 if (!recordTrack->isDirect()) {
7266 // clear any converter state as new data will be discontinuous
7267 recordTrack->mRecordBufferConverter->reset();
7268 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007269 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007270 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007271 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007272 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007273 ALOGV("Record failed to start");
7274 status = BAD_VALUE;
7275 goto startError;
7276 }
Eric Laurent81784c32012-11-19 14:55:58 -08007277 return status;
7278 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007279
Eric Laurent81784c32012-11-19 14:55:58 -08007280startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007281 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007282 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007283 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007284 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007285 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007286 return status;
7287}
7288
Eric Laurent81784c32012-11-19 14:55:58 -08007289void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7290{
7291 sp<SyncEvent> strongEvent = event.promote();
7292
7293 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007294 sp<RefBase> ptr = strongEvent->cookie().promote();
7295 if (ptr != 0) {
7296 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7297 recordTrack->handleSyncStartEvent(strongEvent);
7298 }
Eric Laurent81784c32012-11-19 14:55:58 -08007299 }
7300}
7301
Glenn Kastena8356f62013-07-25 14:37:52 -07007302bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007303 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007304 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007305 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007306 return false;
7307 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007308 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007309 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007310 // signal thread to stop
7311 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007312 // do not wait for mStartStopCond if exiting
7313 if (exitPending()) {
7314 return true;
7315 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007316 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007317 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007318 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007319 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007320 ALOGV("Record stopped OK");
7321 return true;
7322 }
7323 return false;
7324}
7325
Glenn Kasten0f11b512014-01-31 16:18:54 -08007326bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007327{
7328 return false;
7329}
7330
Glenn Kasten0f11b512014-01-31 16:18:54 -08007331status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007332{
7333#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7334 if (!isValidSyncEvent(event)) {
7335 return BAD_VALUE;
7336 }
7337
Glenn Kastend848eb42016-03-08 13:42:11 -08007338 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007339 status_t ret = NAME_NOT_FOUND;
7340
7341 Mutex::Autolock _l(mLock);
7342
7343 for (size_t i = 0; i < mTracks.size(); i++) {
7344 sp<RecordTrack> track = mTracks[i];
7345 if (eventSession == track->sessionId()) {
7346 (void) track->setSyncEvent(event);
7347 ret = NO_ERROR;
7348 }
7349 }
7350 return ret;
7351#else
7352 return BAD_VALUE;
7353#endif
7354}
7355
jiabin653cc0a2018-01-17 17:54:10 -08007356status_t AudioFlinger::RecordThread::getActiveMicrophones(
7357 std::vector<media::MicrophoneInfo>* activeMicrophones)
7358{
7359 ALOGV("RecordThread::getActiveMicrophones");
7360 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007361 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7362 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007363}
7364
Kevin Rocard069c2712018-03-29 19:09:14 -07007365void AudioFlinger::RecordThread::updateMetadata_l()
7366{
7367 if (mInput == nullptr || mInput->stream == nullptr ||
7368 !mActiveTracks.readAndClearHasChanged()) {
7369 return;
7370 }
7371 StreamInHalInterface::SinkMetadata metadata;
7372 for (const sp<RecordTrack> &track : mActiveTracks) {
7373 // No track is invalid as this is called after prepareTrack_l in the same critical section
7374 metadata.tracks.push_back({
7375 .source = track->attributes().source,
7376 .gain = 1, // capture tracks do not have volumes
7377 });
7378 }
7379 mInput->stream->updateSinkMetadata(metadata);
7380}
7381
Eric Laurent81784c32012-11-19 14:55:58 -08007382// destroyTrack_l() must be called with ThreadBase::mLock held
7383void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7384{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385 track->terminate();
7386 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007387 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007388 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007389 removeTrack_l(track);
7390 }
7391}
7392
7393void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7394{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007395 String8 result;
7396 track->appendDump(result, false /* active */);
7397 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7398
Eric Laurent81784c32012-11-19 14:55:58 -08007399 mTracks.remove(track);
7400 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007401 if (track->isFastTrack()) {
7402 ALOG_ASSERT(!mFastTrackAvail);
7403 mFastTrackAvail = true;
7404 }
Eric Laurent81784c32012-11-19 14:55:58 -08007405}
7406
7407void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7408{
7409 dumpInternals(fd, args);
7410 dumpTracks(fd, args);
7411 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007412 dprintf(fd, " Local log:\n");
7413 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007414}
7415
7416void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7417{
Glenn Kasten44182c22015-03-05 17:12:23 -08007418 dumpBase(fd, args);
7419
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007420 AudioStreamIn *input = mInput;
7421 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7422 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7423 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007424 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007425 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007426 }
Andy Hungbfa64962017-06-12 14:43:19 -07007427
7428 if (input != nullptr) {
7429 dprintf(fd, " Hal stream dump:\n");
7430 (void)input->stream->dump(fd);
7431 }
7432
Andy Hung20bd30b2018-06-01 15:39:35 -07007433 const double latencyMs = - mTimestamp.getOutputServerLatencyMs(mSampleRate);
7434 if (latencyMs != 0.) {
7435 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7436 } else {
7437 dprintf(fd, " NormalRecord latency ms: unavail\n");
7438 }
7439
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007440 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007441 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007442
Glenn Kasten2f90c512015-12-02 11:40:09 -08007443 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7444 // while we are dumping it. It may be inconsistent, but it won't mutate!
7445 // This is a large object so we place it on the heap.
7446 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7447 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7448 copy->dump(fd);
7449 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007450}
7451
Glenn Kasten0f11b512014-01-31 16:18:54 -08007452void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007453{
Eric Laurent81784c32012-11-19 14:55:58 -08007454 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007455 size_t numtracks = mTracks.size();
7456 size_t numactive = mActiveTracks.size();
7457 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007458 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007459 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007460 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007461 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007462 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007463 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007464 for (size_t i = 0; i < numtracks ; ++i) {
7465 sp<RecordTrack> track = mTracks[i];
7466 if (track != 0) {
7467 bool active = mActiveTracks.indexOf(track) >= 0;
7468 if (active) {
7469 numactiveseen++;
7470 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007471 result.append(prefix);
7472 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007473 }
Eric Laurent81784c32012-11-19 14:55:58 -08007474 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007475 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007476 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007477 }
7478
Marco Nelissenb2208842014-02-07 14:00:50 -08007479 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007480 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007481 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007482 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007483 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007484 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007485 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007486 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007487 result.append(prefix);
7488 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007489 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007490 }
Eric Laurent81784c32012-11-19 14:55:58 -08007491
7492 }
7493 write(fd, result.string(), result.size());
7494}
7495
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007496void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7497{
7498 Mutex::Autolock _l(mLock);
7499 for (size_t i = 0; i < mTracks.size() ; i++) {
7500 sp<RecordTrack> track = mTracks[i];
7501 if (track != 0 && track->uid() == uid) {
7502 track->setSilenced(silenced);
7503 }
7504 }
7505}
Andy Hung73c02e42015-03-29 01:13:58 -07007506
7507void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7508{
7509 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7510 RecordThread *recordThread = (RecordThread *) threadBase.get();
7511 mRsmpInFront = recordThread->mRsmpInRear;
7512 mRsmpInUnrel = 0;
7513}
7514
7515void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7516 size_t *framesAvailable, bool *hasOverrun)
7517{
7518 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7519 RecordThread *recordThread = (RecordThread *) threadBase.get();
7520 const int32_t rear = recordThread->mRsmpInRear;
7521 const int32_t front = mRsmpInFront;
7522 const ssize_t filled = rear - front;
7523
7524 size_t framesIn;
7525 bool overrun = false;
7526 if (filled < 0) {
7527 // should not happen, but treat like a massive overrun and re-sync
7528 framesIn = 0;
7529 mRsmpInFront = rear;
7530 overrun = true;
7531 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7532 framesIn = (size_t) filled;
7533 } else {
7534 // client is not keeping up with server, but give it latest data
7535 framesIn = recordThread->mRsmpInFrames;
7536 mRsmpInFront = /* front = */ rear - framesIn;
7537 overrun = true;
7538 }
7539 if (framesAvailable != NULL) {
7540 *framesAvailable = framesIn;
7541 }
7542 if (hasOverrun != NULL) {
7543 *hasOverrun = overrun;
7544 }
7545}
7546
Eric Laurent81784c32012-11-19 14:55:58 -08007547// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007548status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007549 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007550{
Andy Hung73c02e42015-03-29 01:13:58 -07007551 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007552 if (threadBase == 0) {
7553 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007554 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007555 return NOT_ENOUGH_DATA;
7556 }
7557 RecordThread *recordThread = (RecordThread *) threadBase.get();
7558 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007559 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007560 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007561 // FIXME should not be P2 (don't want to increase latency)
7562 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007563 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007564 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007565 front &= recordThread->mRsmpInFramesP2 - 1;
7566 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007567 if (part1 > (size_t) filled) {
7568 part1 = filled;
7569 }
7570 size_t ask = buffer->frameCount;
7571 ALOG_ASSERT(ask > 0);
7572 if (part1 > ask) {
7573 part1 = ask;
7574 }
7575 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007576 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007577 buffer->raw = NULL;
7578 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007579 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007580 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007581 }
7582
Andy Hung57446612015-04-19 23:56:46 -07007583 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007584 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007585 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007586 return NO_ERROR;
7587}
7588
7589// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007590void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7591 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007592{
Glenn Kasten85948432013-08-19 12:09:05 -07007593 size_t stepCount = buffer->frameCount;
7594 if (stepCount == 0) {
7595 return;
7596 }
Andy Hung73c02e42015-03-29 01:13:58 -07007597 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7598 mRsmpInUnrel -= stepCount;
7599 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007600 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007601 buffer->frameCount = 0;
7602}
7603
Eric Laurentd8365c52017-07-16 15:27:05 -07007604void AudioFlinger::RecordThread::checkBtNrec()
7605{
7606 Mutex::Autolock _l(mLock);
7607 checkBtNrec_l();
7608}
7609
7610void AudioFlinger::RecordThread::checkBtNrec_l()
7611{
7612 // disable AEC and NS if the device is a BT SCO headset supporting those
7613 // pre processings
7614 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7615 mAudioFlinger->btNrecIsOff();
7616 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7617 for (size_t i = 0; i < mEffectChains.size(); i++) {
7618 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7619 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7620 }
7621 }
7622}
7623
Andy Hung97a893e2015-03-29 01:03:07 -07007624
Eric Laurent10351942014-05-08 18:49:52 -07007625bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7626 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007627{
7628 bool reconfig = false;
7629
Eric Laurent10351942014-05-08 18:49:52 -07007630 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007631
Eric Laurent10351942014-05-08 18:49:52 -07007632 audio_format_t reqFormat = mFormat;
7633 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007634 // 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 -07007635 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7636
7637 AudioParameter param = AudioParameter(keyValuePair);
7638 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007639
7640 // scope for AutoPark extends to end of method
7641 AutoPark<FastCapture> park(mFastCapture);
7642
Eric Laurent10351942014-05-08 18:49:52 -07007643 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7644 // channel count change can be requested. Do we mandate the first client defines the
7645 // HAL sampling rate and channel count or do we allow changes on the fly?
7646 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7647 samplingRate = value;
7648 reconfig = true;
7649 }
7650 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007651 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007652 status = BAD_VALUE;
7653 } else {
7654 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007655 reconfig = true;
7656 }
Eric Laurent10351942014-05-08 18:49:52 -07007657 }
7658 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7659 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007660 if (!audio_is_input_channel(mask) ||
7661 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007662 status = BAD_VALUE;
7663 } else {
7664 channelMask = mask;
7665 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007666 }
Eric Laurent10351942014-05-08 18:49:52 -07007667 }
7668 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7669 // do not accept frame count changes if tracks are open as the track buffer
7670 // size depends on frame count and correct behavior would not be guaranteed
7671 // if frame count is changed after track creation
7672 if (mActiveTracks.size() > 0) {
7673 status = INVALID_OPERATION;
7674 } else {
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::keyRouting), value) == NO_ERROR) {
7679 // forward device change to effects that have requested to be
7680 // aware of attached audio device.
7681 for (size_t i = 0; i < mEffectChains.size(); i++) {
7682 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007683 }
Eric Laurent81784c32012-11-19 14:55:58 -08007684
Eric Laurent10351942014-05-08 18:49:52 -07007685 // store input device and output device but do not forward output device to audio HAL.
7686 // Note that status is ignored by the caller for output device
7687 // (see AudioFlinger::setParameters()
7688 if (audio_is_output_devices(value)) {
7689 mOutDevice = value;
7690 status = BAD_VALUE;
7691 } else {
7692 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007693 if (value != AUDIO_DEVICE_NONE) {
7694 mPrevInDevice = value;
7695 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007696 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007697 }
Eric Laurent10351942014-05-08 18:49:52 -07007698 }
7699 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7700 mAudioSource != (audio_source_t)value) {
7701 // forward device change to effects that have requested to be
7702 // aware of attached audio device.
7703 for (size_t i = 0; i < mEffectChains.size(); i++) {
7704 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007705 }
Eric Laurent10351942014-05-08 18:49:52 -07007706 mAudioSource = (audio_source_t)value;
7707 }
Glenn Kastene198c362013-08-13 09:13:36 -07007708
Eric Laurent10351942014-05-08 18:49:52 -07007709 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007710 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007711 if (status == INVALID_OPERATION) {
7712 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007713 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007714 }
7715 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007716 if (status == BAD_VALUE) {
7717 uint32_t sRate;
7718 audio_channel_mask_t channelMask;
7719 audio_format_t format;
7720 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7721 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7722 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7723 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7724 status = NO_ERROR;
7725 }
Eric Laurent81784c32012-11-19 14:55:58 -08007726 }
Eric Laurent10351942014-05-08 18:49:52 -07007727 if (status == NO_ERROR) {
7728 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007729 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007730 }
7731 }
Eric Laurent81784c32012-11-19 14:55:58 -08007732 }
Eric Laurent10351942014-05-08 18:49:52 -07007733
Eric Laurent81784c32012-11-19 14:55:58 -08007734 return reconfig;
7735}
7736
7737String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7738{
Eric Laurent81784c32012-11-19 14:55:58 -08007739 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007740 if (initCheck() == NO_ERROR) {
7741 String8 out_s8;
7742 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7743 return out_s8;
7744 }
Eric Laurent81784c32012-11-19 14:55:58 -08007745 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007746 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007747}
7748
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007749void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007750 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7751
7752 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007753
7754 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007755 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007756 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007757 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007758 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007759 desc->mChannelMask = mChannelMask;
7760 desc->mSamplingRate = mSampleRate;
7761 desc->mFormat = mFormat;
7762 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007763 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007764 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007765 break;
7766
Eric Laurent73e26b62015-04-27 16:55:58 -07007767 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007768 default:
7769 break;
7770 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007771 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007772}
7773
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007774void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007775{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007776 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7777 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007778 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007779 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007780 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007781 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7782 result = mInput->stream->getFrameSize(&mFrameSize);
7783 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7784 result = mInput->stream->getBufferSize(&mBufferSize);
7785 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007786 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007787 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7788 "mBufferSize=%lld, mFrameCount=%lld",
7789 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7790 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007791 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007792 // 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 -07007793 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007794 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007795 // A larger value should allow more old data to be read after a track calls start(),
7796 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007797 //
7798 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007799 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007800 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007801 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007802 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007803
7804 // TODO optimize audio capture buffer sizes ...
7805 // Here we calculate the size of the sliding buffer used as a source
7806 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7807 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7808 // be better to have it derived from the pipe depth in the long term.
7809 // The current value is higher than necessary. However it should not add to latency.
7810
Glenn Kasten85948432013-08-19 12:09:05 -07007811 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007812 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7813 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007814 // if posix_memalign fails, will segv here.
7815 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007816
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007817 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7818 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007819}
7820
Glenn Kasten5f972c02014-01-13 09:59:31 -08007821uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007822{
7823 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007824 uint32_t result;
7825 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7826 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007827 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007828 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007829}
7830
Eric Laurent4c415062016-06-17 16:14:16 -07007831// hasAudioSession_l() must be called with ThreadBase::mLock held
7832uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007833{
Eric Laurent81784c32012-11-19 14:55:58 -08007834 uint32_t result = 0;
7835 if (getEffectChain_l(sessionId) != 0) {
7836 result = EFFECT_SESSION;
7837 }
7838
7839 for (size_t i = 0; i < mTracks.size(); ++i) {
7840 if (sessionId == mTracks[i]->sessionId()) {
7841 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007842 if (mTracks[i]->isFastTrack()) {
7843 result |= FAST_SESSION;
7844 }
Eric Laurent81784c32012-11-19 14:55:58 -08007845 break;
7846 }
7847 }
7848
7849 return result;
7850}
7851
Glenn Kastend848eb42016-03-08 13:42:11 -08007852KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007853{
Glenn Kastend848eb42016-03-08 13:42:11 -08007854 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007855 Mutex::Autolock _l(mLock);
7856 for (size_t j = 0; j < mTracks.size(); ++j) {
7857 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007858 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007859 if (ids.indexOfKey(sessionId) < 0) {
7860 ids.add(sessionId, true);
7861 }
7862 }
7863 return ids;
7864}
7865
7866AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7867{
7868 Mutex::Autolock _l(mLock);
7869 AudioStreamIn *input = mInput;
7870 mInput = NULL;
7871 return input;
7872}
7873
7874// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007875sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007876{
7877 if (mInput == NULL) {
7878 return NULL;
7879 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007880 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007881}
7882
7883status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7884{
7885 // only one chain per input thread
7886 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007887 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007888 return INVALID_OPERATION;
7889 }
7890 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007891 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007892 chain->setInBuffer(NULL);
7893 chain->setOutBuffer(NULL);
7894
7895 checkSuspendOnAddEffectChain_l(chain);
7896
Eric Laurent1b928682014-10-02 19:41:47 -07007897 // make sure enabled pre processing effects state is communicated to the HAL as we
7898 // just moved them to a new input stream.
7899 chain->syncHalEffectsState();
7900
Eric Laurent81784c32012-11-19 14:55:58 -08007901 mEffectChains.add(chain);
7902
7903 return NO_ERROR;
7904}
7905
7906size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7907{
7908 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7909 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007910 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007911 chain.get(), mEffectChains.size(), this);
7912 if (mEffectChains.size() == 1) {
7913 mEffectChains.removeAt(0);
7914 }
7915 return 0;
7916}
7917
Eric Laurent1c333e22014-05-20 10:48:17 -07007918status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7919 audio_patch_handle_t *handle)
7920{
7921 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007922
7923 // store new device and send to effects
7924 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007925 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007926 for (size_t i = 0; i < mEffectChains.size(); i++) {
7927 mEffectChains[i]->setDevice_l(mInDevice);
7928 }
7929
Eric Laurentd8365c52017-07-16 15:27:05 -07007930 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007931
7932 // store new source and send to effects
7933 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7934 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007935 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007936 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007937 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007938 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007939
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007940 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007941 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7942 status = hwDevice->createAudioPatch(patch->num_sources,
7943 patch->sources,
7944 patch->num_sinks,
7945 patch->sinks,
7946 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007947 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007948 char *address;
7949 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7950 address = audio_device_address_to_parameter(
7951 patch->sources[0].ext.device.type,
7952 patch->sources[0].ext.device.address);
7953 } else {
7954 address = (char *)calloc(1, 1);
7955 }
7956 AudioParameter param = AudioParameter(String8(address));
7957 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007958 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007959 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007960 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007961 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007962 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007963 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007964 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007965
Eric Laurente8726fe2015-06-26 09:39:24 -07007966 if (mInDevice != mPrevInDevice) {
7967 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7968 mPrevInDevice = mInDevice;
7969 }
Eric Laurent296fb132015-05-01 11:38:42 -07007970
Eric Laurent1c333e22014-05-20 10:48:17 -07007971 return status;
7972}
7973
7974status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7975{
7976 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007977
7978 mInDevice = AUDIO_DEVICE_NONE;
7979
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007980 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007981 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7982 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007983 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007984 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007985 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007986 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007987 }
7988 return status;
7989}
7990
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007991void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007992{
7993 Mutex::Autolock _l(mLock);
7994 mTracks.add(record);
7995}
7996
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007997void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007998{
7999 Mutex::Autolock _l(mLock);
8000 destroyTrack_l(record);
8001}
8002
Mikhail Naganovdc769682018-05-04 15:34:08 -07008003void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008004{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008005 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008006 config->role = AUDIO_PORT_ROLE_SINK;
8007 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8008 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008009 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8010 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8011 config->flags.input = mInput->flags;
8012 }
Eric Laurent83b88082014-06-20 18:31:16 -07008013}
Eric Laurent1c333e22014-05-20 10:48:17 -07008014
Eric Laurent6acd1d42017-01-04 14:23:29 -08008015// ----------------------------------------------------------------------------
8016// Mmap
8017// ----------------------------------------------------------------------------
8018
8019AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8020 : mThread(thread)
8021{
Phil Burk9fabbf82017-08-03 12:02:00 -07008022 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008023}
8024
8025AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8026{
Phil Burk9fabbf82017-08-03 12:02:00 -07008027 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008028}
8029
8030status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8031 struct audio_mmap_buffer_info *info)
8032{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008033 return mThread->createMmapBuffer(minSizeFrames, info);
8034}
8035
8036status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8037{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008038 return mThread->getMmapPosition(position);
8039}
8040
Eric Laurenta54f1282017-07-01 19:39:32 -07008041status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008042 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008043
8044{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008045 return mThread->start(client, handle);
8046}
8047
8048status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8049{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008050 return mThread->stop(handle);
8051}
8052
Eric Laurent18b57012017-02-13 16:23:52 -08008053status_t AudioFlinger::MmapThreadHandle::standby()
8054{
Eric Laurent18b57012017-02-13 16:23:52 -08008055 return mThread->standby();
8056}
8057
Eric Laurent6acd1d42017-01-04 14:23:29 -08008058
8059AudioFlinger::MmapThread::MmapThread(
8060 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8061 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8062 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8063 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008064 mSessionId(AUDIO_SESSION_NONE),
8065 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008066 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008067 mActiveTracks(&this->mLocalLog),
8068 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8069 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008070{
Eric Laurent18b57012017-02-13 16:23:52 -08008071 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008072 readHalParameters_l();
8073}
8074
8075AudioFlinger::MmapThread::~MmapThread()
8076{
Eric Laurent18b57012017-02-13 16:23:52 -08008077 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008078}
8079
8080void AudioFlinger::MmapThread::onFirstRef()
8081{
8082 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8083}
8084
8085void AudioFlinger::MmapThread::disconnect()
8086{
Eric Laurent331679c2018-04-16 17:03:16 -07008087 ActiveTracks<MmapTrack> activeTracks;
8088 {
8089 Mutex::Autolock _l(mLock);
8090 for (const sp<MmapTrack> &t : mActiveTracks) {
8091 activeTracks.add(t);
8092 }
8093 }
8094 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008095 stop(t->portId());
8096 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008097 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008098 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008099 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008100 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008101 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008102 }
8103}
8104
8105
8106void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8107 audio_stream_type_t streamType __unused,
8108 audio_session_t sessionId,
8109 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008110 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008111 audio_port_handle_t portId)
8112{
8113 mAttr = *attr;
8114 mSessionId = sessionId;
8115 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008116 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008117 mPortId = portId;
8118}
8119
8120status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8121 struct audio_mmap_buffer_info *info)
8122{
8123 if (mHalStream == 0) {
8124 return NO_INIT;
8125 }
Eric Laurent18b57012017-02-13 16:23:52 -08008126 mStandby = true;
8127 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008128 return mHalStream->createMmapBuffer(minSizeFrames, info);
8129}
8130
8131status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8132{
8133 if (mHalStream == 0) {
8134 return NO_INIT;
8135 }
8136 return mHalStream->getMmapPosition(position);
8137}
8138
Eric Laurent331679c2018-04-16 17:03:16 -07008139status_t AudioFlinger::MmapThread::exitStandby()
8140{
8141 status_t ret = mHalStream->start();
8142 if (ret != NO_ERROR) {
8143 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8144 return ret;
8145 }
8146 mStandby = false;
8147 return NO_ERROR;
8148}
8149
Eric Laurenta54f1282017-07-01 19:39:32 -07008150status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008151 audio_port_handle_t *handle)
8152{
Eric Laurenta54f1282017-07-01 19:39:32 -07008153 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8154 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008155 if (mHalStream == 0) {
8156 return NO_INIT;
8157 }
8158
8159 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008160
Eric Laurenta54f1282017-07-01 19:39:32 -07008161 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008162 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008163 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008164 }
8165
8166 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8167
8168 audio_io_handle_t io = mId;
8169 if (isOutput()) {
8170 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8171 config.sample_rate = mSampleRate;
8172 config.channel_mask = mChannelMask;
8173 config.format = mFormat;
8174 audio_stream_type_t stream = streamType();
8175 audio_output_flags_t flags =
8176 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008177 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008178 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8179 mSessionId,
8180 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008181 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008182 client.clientUid,
8183 &config,
8184 flags,
8185 &deviceId,
8186 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008187 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008188 audio_config_base_t config;
8189 config.sample_rate = mSampleRate;
8190 config.channel_mask = mChannelMask;
8191 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008192 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008193 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8194 mSessionId,
8195 client.clientPid,
8196 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008197 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008198 &config,
8199 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8200 &deviceId,
8201 &portId);
8202 }
8203 // APM should not chose a different input or output stream for the same set of attributes
8204 // and audo configuration
8205 if (ret != NO_ERROR || io != mId) {
8206 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8207 __FUNCTION__, ret, io, mId);
8208 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008209 }
8210
Eric Laurent331679c2018-04-16 17:03:16 -07008211 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008212 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008213 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008214 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008215 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008216 }
8217
Eric Laurent331679c2018-04-16 17:03:16 -07008218 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008219 // abort if start is rejected by audio policy manager
8220 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008221 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008222 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008223 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008224 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008225 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008226 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008227 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008228 }
Eric Laurent331679c2018-04-16 17:03:16 -07008229 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008230 } else {
8231 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008232 }
8233 return PERMISSION_DENIED;
8234 }
8235
Eric Laurent67f97292018-04-20 18:05:41 -07008236 if (isOutput()) {
8237 // force volume update when a new track is added
8238 mHalVolFloat = -1.0f;
8239 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008240 for (const sp<MmapTrack> &track : mActiveTracks) {
8241 if (track->isSilenced_l() && track->uid() != client.clientUid)
8242 track->invalidate();
8243 }
8244 }
8245
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008246 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8247 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008248 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008249
Eric Laurent331679c2018-04-16 17:03:16 -07008250 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008251 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008252 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008253 if (chain != 0) {
8254 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8255 chain->incTrackCnt();
8256 chain->incActiveTrackCnt();
8257 }
8258
8259 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008260 broadcast_l();
8261
Eric Laurenta54f1282017-07-01 19:39:32 -07008262 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008263
8264 return NO_ERROR;
8265}
8266
8267status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8268{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008269 ALOGV("%s handle %d", __FUNCTION__, handle);
8270
8271 if (mHalStream == 0) {
8272 return NO_INIT;
8273 }
8274
Eric Laurenta54f1282017-07-01 19:39:32 -07008275 if (handle == mPortId) {
8276 mHalStream->stop();
8277 return NO_ERROR;
8278 }
8279
Eric Laurent331679c2018-04-16 17:03:16 -07008280 Mutex::Autolock _l(mLock);
8281
Eric Laurent6acd1d42017-01-04 14:23:29 -08008282 sp<MmapTrack> track;
8283 for (const sp<MmapTrack> &t : mActiveTracks) {
8284 if (handle == t->portId()) {
8285 track = t;
8286 break;
8287 }
8288 }
8289 if (track == 0) {
8290 return BAD_VALUE;
8291 }
8292
8293 mActiveTracks.remove(track);
8294
Eric Laurent331679c2018-04-16 17:03:16 -07008295 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008296 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008297 AudioSystem::stopOutput(track->portId());
8298 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008299 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008300 AudioSystem::stopInput(track->portId());
8301 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008302 }
Eric Laurent331679c2018-04-16 17:03:16 -07008303 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008304
8305 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8306 if (chain != 0) {
8307 chain->decActiveTrackCnt();
8308 chain->decTrackCnt();
8309 }
8310
8311 broadcast_l();
8312
Eric Laurent6acd1d42017-01-04 14:23:29 -08008313 return NO_ERROR;
8314}
8315
Eric Laurent18b57012017-02-13 16:23:52 -08008316status_t AudioFlinger::MmapThread::standby()
8317{
8318 ALOGV("%s", __FUNCTION__);
8319
8320 if (mHalStream == 0) {
8321 return NO_INIT;
8322 }
8323 if (mActiveTracks.size() != 0) {
8324 return INVALID_OPERATION;
8325 }
8326 mHalStream->standby();
8327 mStandby = true;
8328 releaseWakeLock();
8329 return NO_ERROR;
8330}
8331
Eric Laurent6acd1d42017-01-04 14:23:29 -08008332
8333void AudioFlinger::MmapThread::readHalParameters_l()
8334{
8335 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8336 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8337 mFormat = mHALFormat;
8338 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8339 result = mHalStream->getFrameSize(&mFrameSize);
8340 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8341 result = mHalStream->getBufferSize(&mBufferSize);
8342 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8343 mFrameCount = mBufferSize / mFrameSize;
8344}
8345
8346bool AudioFlinger::MmapThread::threadLoop()
8347{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008348 checkSilentMode_l();
8349
8350 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8351
8352 while (!exitPending())
8353 {
8354 Mutex::Autolock _l(mLock);
8355 Vector< sp<EffectChain> > effectChains;
8356
8357 if (mSignalPending) {
8358 // A signal was raised while we were unlocked
8359 mSignalPending = false;
8360 } else {
8361 if (mConfigEvents.isEmpty()) {
8362 // we're about to wait, flush the binder command buffer
8363 IPCThreadState::self()->flushCommands();
8364
8365 if (exitPending()) {
8366 break;
8367 }
8368
Eric Laurent6acd1d42017-01-04 14:23:29 -08008369 // wait until we have something to do...
8370 ALOGV("%s going to sleep", myName.string());
8371 mWaitWorkCV.wait(mLock);
8372 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008373
8374 checkSilentMode_l();
8375
8376 continue;
8377 }
8378 }
8379
8380 processConfigEvents_l();
8381
8382 processVolume_l();
8383
8384 checkInvalidTracks_l();
8385
8386 mActiveTracks.updatePowerState(this);
8387
Kevin Rocard069c2712018-03-29 19:09:14 -07008388 updateMetadata_l();
8389
Eric Laurent6acd1d42017-01-04 14:23:29 -08008390 lockEffectChains_l(effectChains);
8391 for (size_t i = 0; i < effectChains.size(); i ++) {
8392 effectChains[i]->process_l();
8393 }
8394 // enable changes in effect chain
8395 unlockEffectChains(effectChains);
8396 // Effect chains will be actually deleted here if they were removed from
8397 // mEffectChains list during mixing or effects processing
8398 }
8399
8400 threadLoop_exit();
8401
8402 if (!mStandby) {
8403 threadLoop_standby();
8404 mStandby = true;
8405 }
8406
Eric Laurent6acd1d42017-01-04 14:23:29 -08008407 ALOGV("Thread %p type %d exiting", this, mType);
8408 return false;
8409}
8410
8411// checkForNewParameter_l() must be called with ThreadBase::mLock held
8412bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8413 status_t& status)
8414{
8415 AudioParameter param = AudioParameter(keyValuePair);
8416 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008417 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008418 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008419 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008420 // forward device change to effects that have requested to be
8421 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008422 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008423 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008424 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008425 }
8426 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008427 if (audio_is_output_devices(device)) {
8428 mOutDevice = device;
8429 if (!isOutput()) {
8430 sendToHal = false;
8431 }
8432 } else {
8433 mInDevice = device;
8434 if (device != AUDIO_DEVICE_NONE) {
8435 mPrevInDevice = value;
8436 }
8437 // TODO: implement and call checkBtNrec_l();
8438 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008439 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008440 if (sendToHal) {
8441 status = mHalStream->setParameters(keyValuePair);
8442 } else {
8443 status = NO_ERROR;
8444 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008445
8446 return false;
8447}
8448
8449String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8450{
8451 Mutex::Autolock _l(mLock);
8452 String8 out_s8;
8453 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8454 return out_s8;
8455 }
8456 return String8();
8457}
8458
8459void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8460 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8461
8462 desc->mIoHandle = mId;
8463
8464 switch (event) {
8465 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008466 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008467 case AUDIO_INPUT_CONFIG_CHANGED:
8468 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008469 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008470 case AUDIO_OUTPUT_CONFIG_CHANGED:
8471 desc->mPatch = mPatch;
8472 desc->mChannelMask = mChannelMask;
8473 desc->mSamplingRate = mSampleRate;
8474 desc->mFormat = mFormat;
8475 desc->mFrameCount = mFrameCount;
8476 desc->mFrameCountHAL = mFrameCount;
8477 desc->mLatency = 0;
8478 break;
8479
8480 case AUDIO_INPUT_CLOSED:
8481 case AUDIO_OUTPUT_CLOSED:
8482 default:
8483 break;
8484 }
8485 mAudioFlinger->ioConfigChanged(event, desc, pid);
8486}
8487
8488status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8489 audio_patch_handle_t *handle)
8490{
8491 status_t status = NO_ERROR;
8492
8493 // store new device and send to effects
8494 audio_devices_t type = AUDIO_DEVICE_NONE;
8495 audio_port_handle_t deviceId;
8496 if (isOutput()) {
8497 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8498 type |= patch->sinks[i].ext.device.type;
8499 }
8500 deviceId = patch->sinks[0].id;
8501 } else {
8502 type = patch->sources[0].ext.device.type;
8503 deviceId = patch->sources[0].id;
8504 }
8505
8506 for (size_t i = 0; i < mEffectChains.size(); i++) {
8507 mEffectChains[i]->setDevice_l(type);
8508 }
8509
8510 if (isOutput()) {
8511 mOutDevice = type;
8512 } else {
8513 mInDevice = type;
8514 // store new source and send to effects
8515 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8516 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8517 for (size_t i = 0; i < mEffectChains.size(); i++) {
8518 mEffectChains[i]->setAudioSource_l(mAudioSource);
8519 }
8520 }
8521 }
8522
8523 if (mAudioHwDev->supportsAudioPatches()) {
8524 status = mHalDevice->createAudioPatch(patch->num_sources,
8525 patch->sources,
8526 patch->num_sinks,
8527 patch->sinks,
8528 handle);
8529 } else {
8530 char *address;
8531 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8532 //FIXME: we only support address on first sink with HAL version < 3.0
8533 address = audio_device_address_to_parameter(
8534 patch->sinks[0].ext.device.type,
8535 patch->sinks[0].ext.device.address);
8536 } else {
8537 address = (char *)calloc(1, 1);
8538 }
8539 AudioParameter param = AudioParameter(String8(address));
8540 free(address);
8541 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8542 if (!isOutput()) {
8543 param.addInt(String8(AudioParameter::keyInputSource),
8544 (int)patch->sinks[0].ext.mix.usecase.source);
8545 }
8546 status = mHalStream->setParameters(param.toString());
8547 *handle = AUDIO_PATCH_HANDLE_NONE;
8548 }
8549
8550 if (isOutput() && mPrevOutDevice != mOutDevice) {
8551 mPrevOutDevice = type;
8552 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008553 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008554 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008555 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008556 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008557 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008558 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008559 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008560 }
8561 if (!isOutput() && mPrevInDevice != mInDevice) {
8562 mPrevInDevice = type;
8563 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008564 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008565 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008566 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008567 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008568 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008569 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008570 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008571 }
8572 return status;
8573}
8574
8575status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8576{
8577 status_t status = NO_ERROR;
8578
8579 mInDevice = AUDIO_DEVICE_NONE;
8580
8581 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8582 supportsAudioPatches : false;
8583
8584 if (supportsAudioPatches) {
8585 status = mHalDevice->releaseAudioPatch(handle);
8586 } else {
8587 AudioParameter param;
8588 param.addInt(String8(AudioParameter::keyRouting), 0);
8589 status = mHalStream->setParameters(param.toString());
8590 }
8591 return status;
8592}
8593
Mikhail Naganovdc769682018-05-04 15:34:08 -07008594void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008595{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008596 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008597 if (isOutput()) {
8598 config->role = AUDIO_PORT_ROLE_SOURCE;
8599 config->ext.mix.hw_module = mAudioHwDev->handle();
8600 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8601 } else {
8602 config->role = AUDIO_PORT_ROLE_SINK;
8603 config->ext.mix.hw_module = mAudioHwDev->handle();
8604 config->ext.mix.usecase.source = mAudioSource;
8605 }
8606}
8607
8608status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8609{
8610 audio_session_t session = chain->sessionId();
8611
8612 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8613 // Attach all tracks with same session ID to this chain.
8614 // indicate all active tracks in the chain
8615 for (const sp<MmapTrack> &track : mActiveTracks) {
8616 if (session == track->sessionId()) {
8617 chain->incTrackCnt();
8618 chain->incActiveTrackCnt();
8619 }
8620 }
8621
8622 chain->setThread(this);
8623 chain->setInBuffer(nullptr);
8624 chain->setOutBuffer(nullptr);
8625 chain->syncHalEffectsState();
8626
8627 mEffectChains.add(chain);
8628 checkSuspendOnAddEffectChain_l(chain);
8629 return NO_ERROR;
8630}
8631
8632size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8633{
8634 audio_session_t session = chain->sessionId();
8635
8636 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8637
8638 for (size_t i = 0; i < mEffectChains.size(); i++) {
8639 if (chain == mEffectChains[i]) {
8640 mEffectChains.removeAt(i);
8641 // detach all active tracks from the chain
8642 // detach all tracks with same session ID from this chain
8643 for (const sp<MmapTrack> &track : mActiveTracks) {
8644 if (session == track->sessionId()) {
8645 chain->decActiveTrackCnt();
8646 chain->decTrackCnt();
8647 }
8648 }
8649 break;
8650 }
8651 }
8652 return mEffectChains.size();
8653}
8654
8655// hasAudioSession_l() must be called with ThreadBase::mLock held
8656uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8657{
8658 uint32_t result = 0;
8659 if (getEffectChain_l(sessionId) != 0) {
8660 result = EFFECT_SESSION;
8661 }
8662
8663 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8664 sp<MmapTrack> track = mActiveTracks[i];
8665 if (sessionId == track->sessionId()) {
8666 result |= TRACK_SESSION;
8667 if (track->isFastTrack()) {
8668 result |= FAST_SESSION;
8669 }
8670 break;
8671 }
8672 }
8673
8674 return result;
8675}
8676
8677void AudioFlinger::MmapThread::threadLoop_standby()
8678{
8679 mHalStream->standby();
8680}
8681
8682void AudioFlinger::MmapThread::threadLoop_exit()
8683{
Phil Burk7dce7282017-09-27 13:51:41 -07008684 // Do not call callback->onTearDown() because it is redundant for thread exit
8685 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008686}
8687
8688status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8689{
8690 return BAD_VALUE;
8691}
8692
8693bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8694{
8695 return false;
8696}
8697
8698status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8699 const effect_descriptor_t *desc, audio_session_t sessionId)
8700{
8701 // No global effect sessions on mmap threads
8702 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8703 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8704 desc->name, mThreadName);
8705 return BAD_VALUE;
8706 }
8707
8708 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8709 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8710 desc->name);
8711 return BAD_VALUE;
8712 }
8713 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008714 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8715 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008716 return BAD_VALUE;
8717 }
8718
8719 // Only allow effects without processing load or latency
8720 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8721 return BAD_VALUE;
8722 }
8723
8724 return NO_ERROR;
8725
8726}
8727
8728void AudioFlinger::MmapThread::checkInvalidTracks_l()
8729{
8730 for (const sp<MmapTrack> &track : mActiveTracks) {
8731 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008732 sp<MmapStreamCallback> callback = mCallback.promote();
8733 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008734 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008735 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008736 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008737 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8738 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8739 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008740 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008741 }
8742 }
8743}
8744
8745void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8746{
8747 dumpInternals(fd, args);
8748 dumpTracks(fd, args);
8749 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008750 dprintf(fd, " Local log:\n");
8751 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008752}
8753
8754void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8755{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756 dumpBase(fd, args);
8757
8758 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8759 mAttr.content_type, mAttr.usage, mAttr.source);
8760 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8761 if (mActiveTracks.size() == 0) {
8762 dprintf(fd, " No active clients\n");
8763 }
8764}
8765
8766void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8767{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008768 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008769 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008770 dprintf(fd, " %zu Tracks\n", numtracks);
8771 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008772 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008773 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008774 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008775 for (size_t i = 0; i < numtracks ; ++i) {
8776 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008777 result.append(prefix);
8778 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008779 }
8780 } else {
8781 dprintf(fd, "\n");
8782 }
8783 write(fd, result.string(), result.size());
8784}
8785
8786AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8787 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8788 AudioHwDevice *hwDev, AudioStreamOut *output,
8789 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8790 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8791 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008792 mStreamVolume(1.0),
8793 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008794 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008795{
8796 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8797 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8798 mMasterVolume = audioFlinger->masterVolume_l();
8799 mMasterMute = audioFlinger->masterMute_l();
8800 if (mAudioHwDev) {
8801 if (mAudioHwDev->canSetMasterVolume()) {
8802 mMasterVolume = 1.0;
8803 }
8804
8805 if (mAudioHwDev->canSetMasterMute()) {
8806 mMasterMute = false;
8807 }
8808 }
8809}
8810
8811void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8812 audio_stream_type_t streamType,
8813 audio_session_t sessionId,
8814 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008815 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008816 audio_port_handle_t portId)
8817{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008818 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008819 mStreamType = streamType;
8820}
8821
8822AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8823{
8824 Mutex::Autolock _l(mLock);
8825 AudioStreamOut *output = mOutput;
8826 mOutput = NULL;
8827 return output;
8828}
8829
8830void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8831{
8832 Mutex::Autolock _l(mLock);
8833 // Don't apply master volume in SW if our HAL can do it for us.
8834 if (mAudioHwDev &&
8835 mAudioHwDev->canSetMasterVolume()) {
8836 mMasterVolume = 1.0;
8837 } else {
8838 mMasterVolume = value;
8839 }
8840}
8841
8842void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8843{
8844 Mutex::Autolock _l(mLock);
8845 // Don't apply master mute in SW if our HAL can do it for us.
8846 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8847 mMasterMute = false;
8848 } else {
8849 mMasterMute = muted;
8850 }
8851}
8852
8853void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8854{
8855 Mutex::Autolock _l(mLock);
8856 if (stream == mStreamType) {
8857 mStreamVolume = value;
8858 broadcast_l();
8859 }
8860}
8861
8862float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8863{
8864 Mutex::Autolock _l(mLock);
8865 if (stream == mStreamType) {
8866 return mStreamVolume;
8867 }
8868 return 0.0f;
8869}
8870
8871void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8872{
8873 Mutex::Autolock _l(mLock);
8874 if (stream == mStreamType) {
8875 mStreamMute= muted;
8876 broadcast_l();
8877 }
8878}
8879
8880void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8881{
8882 Mutex::Autolock _l(mLock);
8883 if (streamType == mStreamType) {
8884 for (const sp<MmapTrack> &track : mActiveTracks) {
8885 track->invalidate();
8886 }
8887 broadcast_l();
8888 }
8889}
8890
8891void AudioFlinger::MmapPlaybackThread::processVolume_l()
8892{
8893 float volume;
8894
8895 if (mMasterMute || mStreamMute) {
8896 volume = 0;
8897 } else {
8898 volume = mMasterVolume * mStreamVolume;
8899 }
8900
8901 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008902
8903 // Convert volumes from float to 8.24
8904 uint32_t vol = (uint32_t)(volume * (1 << 24));
8905
8906 // Delegate volume control to effect in track effect chain if needed
8907 // only one effect chain can be present on DirectOutputThread, so if
8908 // there is one, the track is connected to it
8909 if (!mEffectChains.isEmpty()) {
8910 mEffectChains[0]->setVolume_l(&vol, &vol);
8911 volume = (float)vol / (1 << 24);
8912 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008913 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008914 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8915 mHalVolFloat = volume; // HW volume control worked, so update value.
8916 mNoCallbackWarningCount = 0;
8917 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008918 sp<MmapStreamCallback> callback = mCallback.promote();
8919 if (callback != 0) {
8920 int channelCount;
8921 if (isOutput()) {
8922 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8923 } else {
8924 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8925 }
8926 Vector<float> values;
8927 for (int i = 0; i < channelCount; i++) {
8928 values.add(volume);
8929 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008930 mHalVolFloat = volume; // SW volume control worked, so update value.
8931 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008932 mLock.unlock();
8933 callback->onVolumeChanged(mChannelMask, values);
8934 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008935 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008936 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8937 ALOGW("Could not set MMAP stream volume: no volume callback!");
8938 mNoCallbackWarningCount++;
8939 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008940 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008941 }
8942 }
8943}
8944
Kevin Rocard069c2712018-03-29 19:09:14 -07008945void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8946{
8947 if (mOutput == nullptr || mOutput->stream == nullptr ||
8948 !mActiveTracks.readAndClearHasChanged()) {
8949 return;
8950 }
8951 StreamOutHalInterface::SourceMetadata metadata;
8952 for (const sp<MmapTrack> &track : mActiveTracks) {
8953 // No track is invalid as this is called after prepareTrack_l in the same critical section
8954 metadata.tracks.push_back({
8955 .usage = track->attributes().usage,
8956 .content_type = track->attributes().content_type,
8957 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8958 });
8959 }
8960 mOutput->stream->updateSourceMetadata(metadata);
8961}
8962
Eric Laurent6acd1d42017-01-04 14:23:29 -08008963void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8964{
8965 if (!mMasterMute) {
8966 char value[PROPERTY_VALUE_MAX];
8967 if (property_get("ro.audio.silent", value, "0") > 0) {
8968 char *endptr;
8969 unsigned long ul = strtoul(value, &endptr, 0);
8970 if (*endptr == '\0' && ul != 0) {
8971 ALOGD("Silence is golden");
8972 // The setprop command will not allow a property to be changed after
8973 // the first time it is set, so we don't have to worry about un-muting.
8974 setMasterMute_l(true);
8975 }
8976 }
8977 }
8978}
8979
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008980void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
8981{
8982 MmapThread::toAudioPortConfig(config);
8983 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
8984 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8985 config->flags.output = mOutput->flags;
8986 }
8987}
8988
Eric Laurent6acd1d42017-01-04 14:23:29 -08008989void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8990{
8991 MmapThread::dumpInternals(fd, args);
8992
Glenn Kastend3bb6452016-12-05 18:14:37 -08008993 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8994 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008995 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8996}
8997
8998AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8999 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9000 AudioHwDevice *hwDev, AudioStreamIn *input,
9001 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9002 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9003 mInput(input)
9004{
9005 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9006 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9007}
9008
Eric Laurent331679c2018-04-16 17:03:16 -07009009status_t AudioFlinger::MmapCaptureThread::exitStandby()
9010{
9011 mInput->stream->setGain(1.0f);
9012 return MmapThread::exitStandby();
9013}
9014
Eric Laurent6acd1d42017-01-04 14:23:29 -08009015AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9016{
9017 Mutex::Autolock _l(mLock);
9018 AudioStreamIn *input = mInput;
9019 mInput = NULL;
9020 return input;
9021}
Kevin Rocard069c2712018-03-29 19:09:14 -07009022
Eric Laurent331679c2018-04-16 17:03:16 -07009023
9024void AudioFlinger::MmapCaptureThread::processVolume_l()
9025{
9026 bool changed = false;
9027 bool silenced = false;
9028
9029 sp<MmapStreamCallback> callback = mCallback.promote();
9030 if (callback == 0) {
9031 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9032 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9033 mNoCallbackWarningCount++;
9034 }
9035 }
9036
9037 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9038 // track is silenced and unmute otherwise
9039 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9040 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9041 changed = true;
9042 silenced = mActiveTracks[i]->isSilenced_l();
9043 }
9044 }
9045
9046 if (changed) {
9047 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9048 }
9049}
9050
Kevin Rocard069c2712018-03-29 19:09:14 -07009051void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9052{
9053 if (mInput == nullptr || mInput->stream == nullptr ||
9054 !mActiveTracks.readAndClearHasChanged()) {
9055 return;
9056 }
9057 StreamInHalInterface::SinkMetadata metadata;
9058 for (const sp<MmapTrack> &track : mActiveTracks) {
9059 // No track is invalid as this is called after prepareTrack_l in the same critical section
9060 metadata.tracks.push_back({
9061 .source = track->attributes().source,
9062 .gain = 1, // capture tracks do not have volumes
9063 });
9064 }
9065 mInput->stream->updateSinkMetadata(metadata);
9066}
9067
Eric Laurent331679c2018-04-16 17:03:16 -07009068void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9069{
9070 Mutex::Autolock _l(mLock);
9071 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9072 if (mActiveTracks[i]->uid() == uid) {
9073 mActiveTracks[i]->setSilenced_l(silenced);
9074 broadcast_l();
9075 }
9076 }
9077}
9078
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009079void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9080{
9081 MmapThread::toAudioPortConfig(config);
9082 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9083 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9084 config->flags.input = mInput->flags;
9085 }
9086}
9087
Glenn Kasten63238ef2015-03-02 15:50:29 -08009088} // namespace android