blob: 8bf5337a30d9ebf532de6a2dfd02cf7ad7a63485 [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.
Glenn Kasten691b02a2017-10-03 10:12:20 -0700203static const size_t kRecordThreadReadOnlyHeapSize = 0x4000;
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
856 if (locked) {
857 mLock.unlock();
858 }
859}
860
861void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
862{
863 const size_t SIZE = 256;
864 char buffer[SIZE];
865 String8 result;
866
Marco Nelissenb2208842014-02-07 14:00:50 -0800867 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000868 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800869 write(fd, buffer, strlen(buffer));
870
Marco Nelissenb2208842014-02-07 14:00:50 -0800871 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800872 sp<EffectChain> chain = mEffectChains[i];
873 if (chain != 0) {
874 chain->dump(fd, args);
875 }
876 }
877}
878
Andy Hungdae27702016-10-31 14:01:16 -0700879void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800880{
881 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700882 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800883}
884
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100885String16 AudioFlinger::ThreadBase::getWakeLockTag()
886{
887 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800888 case MIXER:
889 return String16("AudioMix");
890 case DIRECT:
891 return String16("AudioDirectOut");
892 case DUPLICATING:
893 return String16("AudioDup");
894 case RECORD:
895 return String16("AudioIn");
896 case OFFLOAD:
897 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800898 case MMAP:
899 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800900 default:
901 ALOG_ASSERT(false);
902 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100903 }
904}
905
Andy Hungdae27702016-10-31 14:01:16 -0700906void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800907{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800908 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800909 if (mPowerManager != 0) {
910 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700911 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
912 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700913 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100914 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700915 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700916 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800917 if (status == NO_ERROR) {
918 mWakeLockToken = binder;
919 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800920 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800921 }
Wei Jia3f273d12015-11-24 09:06:49 -0800922
Andy Hung3f0c9022016-01-15 17:49:46 -0800923 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800924 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
925 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800926}
927
928void AudioFlinger::ThreadBase::releaseWakeLock()
929{
930 Mutex::Autolock _l(mLock);
931 releaseWakeLock_l();
932}
933
934void AudioFlinger::ThreadBase::releaseWakeLock_l()
935{
Andy Hung3f0c9022016-01-15 17:49:46 -0800936 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800937 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800938 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800939 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700940 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
941 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800942 }
943 mWakeLockToken.clear();
944 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800945}
946
947void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700948 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800949 // use checkService() to avoid blocking if power service is not up yet
950 sp<IBinder> binder =
951 defaultServiceManager()->checkService(String16("power"));
952 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800953 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800954 } else {
955 mPowerManager = interface_cast<IPowerManager>(binder);
956 binder->linkToDeath(mDeathRecipient);
957 }
958 }
959}
960
Andy Hungd01b0f12016-11-07 16:10:30 -0800961void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700963
964#if !LOG_NDEBUG
965 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800966 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700967 s << uid << " ";
968 }
969 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
970#endif
971
Andy Hung438e7572015-12-14 15:51:17 -0800972 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
973 if (mSystemReady) {
974 ALOGE("no wake lock to update, but system ready!");
975 } else {
976 ALOGW("no wake lock to update, system not ready yet");
977 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800978 return;
979 }
980 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800981 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
982 status_t status = mPowerManager->updateWakeLockUids(
983 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
984 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800985 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800986 }
987}
988
Eric Laurent81784c32012-11-19 14:55:58 -0800989void AudioFlinger::ThreadBase::clearPowerManager()
990{
991 Mutex::Autolock _l(mLock);
992 releaseWakeLock_l();
993 mPowerManager.clear();
994}
995
Glenn Kasten0f11b512014-01-31 16:18:54 -0800996void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800997{
998 sp<ThreadBase> thread = mThread.promote();
999 if (thread != 0) {
1000 thread->clearPowerManager();
1001 }
1002 ALOGW("power manager service died !!!");
1003}
1004
Eric Laurent81784c32012-11-19 14:55:58 -08001005void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001006 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001007{
1008 sp<EffectChain> chain = getEffectChain_l(sessionId);
1009 if (chain != 0) {
1010 if (type != NULL) {
1011 chain->setEffectSuspended_l(type, suspend);
1012 } else {
1013 chain->setEffectSuspendedAll_l(suspend);
1014 }
1015 }
1016
1017 updateSuspendedSessions_l(type, suspend, sessionId);
1018}
1019
1020void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1021{
1022 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1023 if (index < 0) {
1024 return;
1025 }
1026
1027 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1028 mSuspendedSessions.valueAt(index);
1029
1030 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001031 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001032 for (int j = 0; j < desc->mRefCount; j++) {
1033 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1034 chain->setEffectSuspendedAll_l(true);
1035 } else {
1036 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1037 desc->mType.timeLow);
1038 chain->setEffectSuspended_l(&desc->mType, true);
1039 }
1040 }
1041 }
1042}
1043
1044void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1045 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001046 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001047{
1048 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1049
1050 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1051
1052 if (suspend) {
1053 if (index >= 0) {
1054 sessionEffects = mSuspendedSessions.valueAt(index);
1055 } else {
1056 mSuspendedSessions.add(sessionId, sessionEffects);
1057 }
1058 } else {
1059 if (index < 0) {
1060 return;
1061 }
1062 sessionEffects = mSuspendedSessions.valueAt(index);
1063 }
1064
1065
1066 int key = EffectChain::kKeyForSuspendAll;
1067 if (type != NULL) {
1068 key = type->timeLow;
1069 }
1070 index = sessionEffects.indexOfKey(key);
1071
1072 sp<SuspendedSessionDesc> desc;
1073 if (suspend) {
1074 if (index >= 0) {
1075 desc = sessionEffects.valueAt(index);
1076 } else {
1077 desc = new SuspendedSessionDesc();
1078 if (type != NULL) {
1079 desc->mType = *type;
1080 }
1081 sessionEffects.add(key, desc);
1082 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1083 }
1084 desc->mRefCount++;
1085 } else {
1086 if (index < 0) {
1087 return;
1088 }
1089 desc = sessionEffects.valueAt(index);
1090 if (--desc->mRefCount == 0) {
1091 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1092 sessionEffects.removeItemsAt(index);
1093 if (sessionEffects.isEmpty()) {
1094 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1095 sessionId);
1096 mSuspendedSessions.removeItem(sessionId);
1097 }
1098 }
1099 }
1100 if (!sessionEffects.isEmpty()) {
1101 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1102 }
1103}
1104
1105void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1106 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001107 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001108{
1109 Mutex::Autolock _l(mLock);
1110 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1111}
1112
1113void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1114 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001115 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001116{
1117 if (mType != RECORD) {
1118 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1119 // another session. This gives the priority to well behaved effect control panels
1120 // and applications not using global effects.
1121 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1122 // global effects
1123 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1124 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1125 }
1126 }
1127
1128 sp<EffectChain> chain = getEffectChain_l(sessionId);
1129 if (chain != 0) {
1130 chain->checkSuspendOnEffectEnabled(effect, enabled);
1131 }
1132}
1133
Eric Laurent4c415062016-06-17 16:14:16 -07001134// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1135status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1136 const effect_descriptor_t *desc, audio_session_t sessionId)
1137{
1138 // No global effect sessions on record threads
1139 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1140 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1141 desc->name, mThreadName);
1142 return BAD_VALUE;
1143 }
1144 // only pre processing effects on record thread
1145 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1146 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1147 desc->name, mThreadName);
1148 return BAD_VALUE;
1149 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001150
1151 // always allow effects without processing load or latency
1152 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1153 return NO_ERROR;
1154 }
1155
Eric Laurent4c415062016-06-17 16:14:16 -07001156 audio_input_flags_t flags = mInput->flags;
1157 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1158 if (flags & AUDIO_INPUT_FLAG_RAW) {
1159 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1164 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1165 desc->name, mThreadName);
1166 return BAD_VALUE;
1167 }
1168 }
1169 return NO_ERROR;
1170}
1171
1172// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1173status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1174 const effect_descriptor_t *desc, audio_session_t sessionId)
1175{
1176 // no preprocessing on playback threads
1177 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1178 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1179 " thread %s", desc->name, mThreadName);
1180 return BAD_VALUE;
1181 }
1182
Eric Laurent3e4de772017-07-16 16:55:08 -07001183 // always allow effects without processing load or latency
1184 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1185 return NO_ERROR;
1186 }
1187
Eric Laurent4c415062016-06-17 16:14:16 -07001188 switch (mType) {
1189 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001190#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001191 // Reject any effect on mixer multichannel sinks.
1192 // TODO: fix both format and multichannel issues with effects.
1193 if (mChannelCount != FCC_2) {
1194 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1195 " thread %s", desc->name, mChannelCount, mThreadName);
1196 return BAD_VALUE;
1197 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001198#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001199 audio_output_flags_t flags = mOutput->flags;
1200 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1201 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1202 // global effects are applied only to non fast tracks if they are SW
1203 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1204 break;
1205 }
1206 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1207 // only post processing on output stage session
1208 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1209 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1210 " on output stage session", desc->name);
1211 return BAD_VALUE;
1212 }
1213 } else {
1214 // no restriction on effects applied on non fast tracks
1215 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1216 break;
1217 }
1218 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001219
Eric Laurent4c415062016-06-17 16:14:16 -07001220 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1221 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1222 desc->name);
1223 return BAD_VALUE;
1224 }
1225 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1226 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1227 " in fast mode", desc->name);
1228 return BAD_VALUE;
1229 }
1230 }
1231 } break;
1232 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001233 // nothing actionable on offload threads, if the effect:
1234 // - is offloadable: the effect can be created
1235 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1236 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001237 break;
1238 case DIRECT:
1239 // Reject any effect on Direct output threads for now, since the format of
1240 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1241 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1242 desc->name, mThreadName);
1243 return BAD_VALUE;
1244 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001245#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001246 // Reject any effect on mixer multichannel sinks.
1247 // TODO: fix both format and multichannel issues with effects.
1248 if (mChannelCount != FCC_2) {
1249 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1250 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1251 return BAD_VALUE;
1252 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001253#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001254 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1255 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1256 " thread %s", desc->name, mThreadName);
1257 return BAD_VALUE;
1258 }
1259 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1260 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1261 " DUPLICATING thread %s", desc->name, mThreadName);
1262 return BAD_VALUE;
1263 }
1264 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1265 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1266 " DUPLICATING thread %s", desc->name, mThreadName);
1267 return BAD_VALUE;
1268 }
1269 break;
1270 default:
1271 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1272 }
1273
1274 return NO_ERROR;
1275}
1276
Eric Laurent81784c32012-11-19 14:55:58 -08001277// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1278sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1279 const sp<AudioFlinger::Client>& client,
1280 const sp<IEffectClient>& effectClient,
1281 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001282 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001283 effect_descriptor_t *desc,
1284 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001285 status_t *status,
1286 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001287{
1288 sp<EffectModule> effect;
1289 sp<EffectHandle> handle;
1290 status_t lStatus;
1291 sp<EffectChain> chain;
1292 bool chainCreated = false;
1293 bool effectCreated = false;
1294 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001295 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001296
1297 lStatus = initCheck();
1298 if (lStatus != NO_ERROR) {
1299 ALOGW("createEffect_l() Audio driver not initialized.");
1300 goto Exit;
1301 }
1302
Eric Laurent81784c32012-11-19 14:55:58 -08001303 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1304
1305 { // scope for mLock
1306 Mutex::Autolock _l(mLock);
1307
Eric Laurent4c415062016-06-17 16:14:16 -07001308 lStatus = checkEffectCompatibility_l(desc, sessionId);
1309 if (lStatus != NO_ERROR) {
1310 goto Exit;
1311 }
1312
Eric Laurent81784c32012-11-19 14:55:58 -08001313 // check for existing effect chain with the requested audio session
1314 chain = getEffectChain_l(sessionId);
1315 if (chain == 0) {
1316 // create a new chain for this session
1317 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1318 chain = new EffectChain(this, sessionId);
1319 addEffectChain_l(chain);
1320 chain->setStrategy(getStrategyForSession_l(sessionId));
1321 chainCreated = true;
1322 } else {
1323 effect = chain->getEffectFromDesc_l(desc);
1324 }
1325
1326 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1327
1328 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001329 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001330 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001331 lStatus = AudioSystem::registerEffect(
1332 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001333 if (lStatus != NO_ERROR) {
1334 goto Exit;
1335 }
1336 effectRegistered = true;
1337 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001338 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001339 if (lStatus != NO_ERROR) {
1340 goto Exit;
1341 }
1342 effectCreated = true;
1343
1344 effect->setDevice(mOutDevice);
1345 effect->setDevice(mInDevice);
1346 effect->setMode(mAudioFlinger->getMode());
1347 effect->setAudioSource(mAudioSource);
1348 }
1349 // create effect handle and connect it to effect module
1350 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001351 lStatus = handle->initCheck();
1352 if (lStatus == OK) {
1353 lStatus = effect->addHandle(handle.get());
1354 }
Eric Laurent81784c32012-11-19 14:55:58 -08001355 if (enabled != NULL) {
1356 *enabled = (int)effect->isEnabled();
1357 }
1358 }
1359
1360Exit:
1361 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1362 Mutex::Autolock _l(mLock);
1363 if (effectCreated) {
1364 chain->removeEffect_l(effect);
1365 }
1366 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001367 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001368 }
1369 if (chainCreated) {
1370 removeEffectChain_l(chain);
1371 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001372 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001373 }
1374
Glenn Kasten9156ef32013-08-06 15:39:08 -07001375 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001376 return handle;
1377}
1378
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001379void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1380 bool unpinIfLast)
1381{
1382 bool remove = false;
1383 sp<EffectModule> effect;
1384 {
1385 Mutex::Autolock _l(mLock);
1386
1387 effect = handle->effect().promote();
1388 if (effect == 0) {
1389 return;
1390 }
1391 // restore suspended effects if the disconnected handle was enabled and the last one.
1392 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1393 if (remove) {
1394 removeEffect_l(effect, true);
1395 }
1396 }
1397 if (remove) {
1398 mAudioFlinger->updateOrphanEffectChains(effect);
1399 AudioSystem::unregisterEffect(effect->id());
1400 if (handle->enabled()) {
1401 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1402 }
1403 }
1404}
1405
Glenn Kastend848eb42016-03-08 13:42:11 -08001406sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1407 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001408{
1409 Mutex::Autolock _l(mLock);
1410 return getEffect_l(sessionId, effectId);
1411}
1412
Glenn Kastend848eb42016-03-08 13:42:11 -08001413sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1414 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001415{
1416 sp<EffectChain> chain = getEffectChain_l(sessionId);
1417 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1418}
1419
1420// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1421// PlaybackThread::mLock held
1422status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1423{
1424 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001425 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001426 sp<EffectChain> chain = getEffectChain_l(sessionId);
1427 bool chainCreated = false;
1428
Eric Laurent5baf2af2013-09-12 17:37:00 -07001429 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001430 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001431 this, effect->desc().name, effect->desc().flags);
1432
Eric Laurent81784c32012-11-19 14:55:58 -08001433 if (chain == 0) {
1434 // create a new chain for this session
1435 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1436 chain = new EffectChain(this, sessionId);
1437 addEffectChain_l(chain);
1438 chain->setStrategy(getStrategyForSession_l(sessionId));
1439 chainCreated = true;
1440 }
1441 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1442
1443 if (chain->getEffectFromId_l(effect->id()) != 0) {
1444 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1445 this, effect->desc().name, chain.get());
1446 return BAD_VALUE;
1447 }
1448
Eric Laurent5baf2af2013-09-12 17:37:00 -07001449 effect->setOffloaded(mType == OFFLOAD, mId);
1450
Eric Laurent81784c32012-11-19 14:55:58 -08001451 status_t status = chain->addEffect_l(effect);
1452 if (status != NO_ERROR) {
1453 if (chainCreated) {
1454 removeEffectChain_l(chain);
1455 }
1456 return status;
1457 }
1458
1459 effect->setDevice(mOutDevice);
1460 effect->setDevice(mInDevice);
1461 effect->setMode(mAudioFlinger->getMode());
1462 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001463
Eric Laurent81784c32012-11-19 14:55:58 -08001464 return NO_ERROR;
1465}
1466
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001467void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001468
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001469 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001470 effect_descriptor_t desc = effect->desc();
1471 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1472 detachAuxEffect_l(effect->id());
1473 }
1474
1475 sp<EffectChain> chain = effect->chain().promote();
1476 if (chain != 0) {
1477 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001478 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001479 removeEffectChain_l(chain);
1480 }
1481 } else {
1482 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1483 }
1484}
1485
1486void AudioFlinger::ThreadBase::lockEffectChains_l(
1487 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1488{
1489 effectChains = mEffectChains;
1490 for (size_t i = 0; i < mEffectChains.size(); i++) {
1491 mEffectChains[i]->lock();
1492 }
1493}
1494
1495void AudioFlinger::ThreadBase::unlockEffectChains(
1496 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1497{
1498 for (size_t i = 0; i < effectChains.size(); i++) {
1499 effectChains[i]->unlock();
1500 }
1501}
1502
Glenn Kastend848eb42016-03-08 13:42:11 -08001503sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001504{
1505 Mutex::Autolock _l(mLock);
1506 return getEffectChain_l(sessionId);
1507}
1508
Glenn Kastend848eb42016-03-08 13:42:11 -08001509sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1510 const
Eric Laurent81784c32012-11-19 14:55:58 -08001511{
1512 size_t size = mEffectChains.size();
1513 for (size_t i = 0; i < size; i++) {
1514 if (mEffectChains[i]->sessionId() == sessionId) {
1515 return mEffectChains[i];
1516 }
1517 }
1518 return 0;
1519}
1520
1521void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1522{
1523 Mutex::Autolock _l(mLock);
1524 size_t size = mEffectChains.size();
1525 for (size_t i = 0; i < size; i++) {
1526 mEffectChains[i]->setMode_l(mode);
1527 }
1528}
1529
Mikhail Naganovdc769682018-05-04 15:34:08 -07001530void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001531{
1532 config->type = AUDIO_PORT_TYPE_MIX;
1533 config->ext.mix.handle = mId;
1534 config->sample_rate = mSampleRate;
1535 config->format = mFormat;
1536 config->channel_mask = mChannelMask;
1537 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1538 AUDIO_PORT_CONFIG_FORMAT;
1539}
1540
Eric Laurent72e3f392015-05-20 14:43:50 -07001541void AudioFlinger::ThreadBase::systemReady()
1542{
1543 Mutex::Autolock _l(mLock);
1544 if (mSystemReady) {
1545 return;
1546 }
1547 mSystemReady = true;
1548
1549 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1550 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1551 }
1552 mPendingConfigEvents.clear();
1553}
1554
Andy Hungdae27702016-10-31 14:01:16 -07001555template <typename T>
1556ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1557 ssize_t index = mActiveTracks.indexOf(track);
1558 if (index >= 0) {
1559 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1560 return index;
1561 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001562 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001563 mActiveTracksGeneration++;
1564 mLatestActiveTrack = track;
1565 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001566 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001567 return mActiveTracks.add(track);
1568}
1569
1570template <typename T>
1571ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1572 ssize_t index = mActiveTracks.remove(track);
1573 if (index < 0) {
1574 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1575 return index;
1576 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001577 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001578 mActiveTracksGeneration++;
1579 --mBatteryCounter[track->uid()].second;
1580 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001581 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001582 return index;
1583}
1584
1585template <typename T>
1586void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1587 for (const sp<T> &track : mActiveTracks) {
1588 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001589 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001590 }
1591 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001592 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001593 mActiveTracks.clear();
1594 mLatestActiveTrack.clear();
1595 mBatteryCounter.clear();
1596}
1597
1598template <typename T>
1599void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1600 sp<ThreadBase> thread, bool force) {
1601 // Updates ActiveTracks client uids to the thread wakelock.
1602 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1603 thread->updateWakeLockUids_l(getWakeLockUids());
1604 mLastActiveTracksGeneration = mActiveTracksGeneration;
1605 }
1606
1607 // Updates BatteryNotifier uids
1608 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1609 const uid_t uid = it->first;
1610 ssize_t &previous = it->second.first;
1611 ssize_t &current = it->second.second;
1612 if (current > 0) {
1613 if (previous == 0) {
1614 BatteryNotifier::getInstance().noteStartAudio(uid);
1615 }
1616 previous = current;
1617 ++it;
1618 } else if (current == 0) {
1619 if (previous > 0) {
1620 BatteryNotifier::getInstance().noteStopAudio(uid);
1621 }
1622 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1623 } else /* (current < 0) */ {
1624 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1625 }
1626 }
1627}
Eric Laurent83b88082014-06-20 18:31:16 -07001628
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001629template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001630bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1631 const bool hasChanged = mHasChanged;
1632 mHasChanged = false;
1633 return hasChanged;
1634}
1635
1636template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001637void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1638 const char *funcName, const sp<T> &track) const {
1639 if (mLocalLog != nullptr) {
1640 String8 result;
1641 track->appendDump(result, false /* active */);
1642 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1643 }
1644}
1645
Eric Laurent6acd1d42017-01-04 14:23:29 -08001646void AudioFlinger::ThreadBase::broadcast_l()
1647{
1648 // Thread could be blocked waiting for async
1649 // so signal it to handle state changes immediately
1650 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1651 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1652 mSignalPending = true;
1653 mWaitWorkCV.broadcast();
1654}
1655
Eric Laurent81784c32012-11-19 14:55:58 -08001656// ----------------------------------------------------------------------------
1657// Playback
1658// ----------------------------------------------------------------------------
1659
1660AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1661 AudioStreamOut* output,
1662 audio_io_handle_t id,
1663 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001664 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001665 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001666 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001667 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001668 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001669 mMixerBuffer(NULL),
1670 mMixerBufferSize(0),
1671 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1672 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001673 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001674 mEffectBuffer(NULL),
1675 mEffectBufferSize(0),
1676 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1677 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001678 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001679 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001680 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001681 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001682 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001683 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001684 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001685 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001686 mMixerStatus(MIXER_IDLE),
1687 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001688 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001689 mBytesRemaining(0),
1690 mCurrentWriteLength(0),
1691 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001692 mWriteAckSequence(0),
1693 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001694 mScreenState(AudioFlinger::mScreenState),
1695 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001696 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001697 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1698 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001699{
Glenn Kastend7dca052015-03-05 16:05:54 -08001700 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1701 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001702
1703 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1704 // it would be safer to explicitly pass initial masterVolume/masterMute as
1705 // parameter.
1706 //
1707 // If the HAL we are using has support for master volume or master mute,
1708 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1709 // and the mute set to false).
1710 mMasterVolume = audioFlinger->masterVolume_l();
1711 mMasterMute = audioFlinger->masterMute_l();
1712 if (mOutput && mOutput->audioHwDev) {
1713 if (mOutput->audioHwDev->canSetMasterVolume()) {
1714 mMasterVolume = 1.0;
1715 }
1716
1717 if (mOutput->audioHwDev->canSetMasterMute()) {
1718 mMasterMute = false;
1719 }
1720 }
1721
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001722 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001723
Eric Laurent223fd5c2014-11-11 13:43:36 -08001724 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001725 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001726 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001727 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001728 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1729 }
Eric Laurent98e38192018-02-15 18:31:53 -08001730 // Audio patch volume is always max
1731 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1732 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001733}
1734
1735AudioFlinger::PlaybackThread::~PlaybackThread()
1736{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001737 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001738 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001739 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001740 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001741}
1742
1743void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1744{
1745 dumpInternals(fd, args);
1746 dumpTracks(fd, args);
1747 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001748 dprintf(fd, " Local log:\n");
1749 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001750}
1751
Glenn Kasten0f11b512014-01-31 16:18:54 -08001752void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001753{
Eric Laurent81784c32012-11-19 14:55:58 -08001754 String8 result;
1755
Marco Nelissenb2208842014-02-07 14:00:50 -08001756 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001757 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1758 const stream_type_t *st = &mStreamTypes[i];
1759 if (i > 0) {
1760 result.appendFormat(", ");
1761 }
1762 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1763 if (st->mute) {
1764 result.append("M");
1765 }
1766 }
1767 result.append("\n");
1768 write(fd, result.string(), result.length());
1769 result.clear();
1770
Eric Laurent81784c32012-11-19 14:55:58 -08001771 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1772 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001773 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001774 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001775
1776 size_t numtracks = mTracks.size();
1777 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001778 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001779 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001780 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001781 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001782 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001783 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001784 Track::appendDumpHeader(result);
1785 for (size_t i = 0; i < numtracks; ++i) {
1786 sp<Track> track = mTracks[i];
1787 if (track != 0) {
1788 bool active = mActiveTracks.indexOf(track) >= 0;
1789 if (active) {
1790 numactiveseen++;
1791 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001792 result.append(prefix);
1793 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001794 }
1795 }
1796 } else {
1797 result.append("\n");
1798 }
1799 if (numactiveseen != numactive) {
1800 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001801 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001802 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001803 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001804 Track::appendDumpHeader(result);
1805 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001806 sp<Track> track = mActiveTracks[i];
1807 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001808 result.append(prefix);
1809 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001810 }
1811 }
1812 }
1813
1814 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001815}
1816
1817void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1818{
Glenn Kasten44182c22015-03-05 17:12:23 -08001819 dumpBase(fd, args);
1820
Elliott Hughes87cebad2014-05-22 10:14:43 -07001821 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001822 dprintf(fd, " Last write occurred (msecs): %llu\n",
1823 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001824 dprintf(fd, " Total writes: %d\n", mNumWrites);
1825 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1826 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1827 dprintf(fd, " Suspend count: %d\n", mSuspended);
1828 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1829 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1830 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1831 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001832 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001833 AudioStreamOut *output = mOutput;
1834 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001835 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1836 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001837 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1838 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1839 if (mPipeSink.get() != nullptr) {
1840 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1841 }
1842 if (output != nullptr) {
1843 dprintf(fd, " Hal stream dump:\n");
1844 (void)output->stream->dump(fd);
1845 }
Eric Laurent81784c32012-11-19 14:55:58 -08001846}
1847
1848// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001849
1850void AudioFlinger::PlaybackThread::onFirstRef()
1851{
Glenn Kastend7dca052015-03-05 16:05:54 -08001852 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
1855// ThreadBase virtuals
1856void AudioFlinger::PlaybackThread::preExit()
1857{
1858 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001859 // FIXME this is using hard-coded strings but in the future, this functionality will be
1860 // converted to use audio HAL extensions required to support tunneling
1861 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1862 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001863}
1864
1865// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1866sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1867 const sp<AudioFlinger::Client>& client,
1868 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001869 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001870 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001871 audio_format_t format,
1872 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001873 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001874 size_t *pNotificationFrameCount,
1875 uint32_t notificationsPerBuffer,
1876 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001877 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001878 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001879 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001880 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001881 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001882 status_t *status,
1883 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001884{
Glenn Kasten74935e42013-12-19 08:56:45 -08001885 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001886 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001887 sp<Track> track;
1888 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001889 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001890 audio_output_flags_t requestedFlags = *flags;
1891
1892 if (*pSampleRate == 0) {
1893 *pSampleRate = mSampleRate;
1894 }
1895 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001896
1897 // special case for FAST flag considered OK if fast mixer is present
1898 if (hasFastMixer()) {
1899 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1900 }
1901
1902 // Check if requested flags are compatible with output stream flags
1903 if ((*flags & outputFlags) != *flags) {
1904 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1905 *flags, outputFlags);
1906 *flags = (audio_output_flags_t)(*flags & outputFlags);
1907 }
Eric Laurent81784c32012-11-19 14:55:58 -08001908
Eric Laurent81784c32012-11-19 14:55:58 -08001909 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001910 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001911 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001912 // PCM data
1913 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001914 // TODO: extract as a data library function that checks that a computationally
1915 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001916 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001917 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1918 (channelMask == AUDIO_CHANNEL_OUT_MONO
1919 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001920 // hardware sample rate
1921 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001922 // normal mixer has an associated fast mixer
1923 hasFastMixer() &&
1924 // there are sufficient fast track slots available
1925 (mFastTrackAvailMask != 0)
1926 // FIXME test that MixerThread for this fast track has a capable output HAL
1927 // FIXME add a permission test also?
1928 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001929 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1930 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001931 // read the fast track multiplier property the first time it is needed
1932 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1933 if (ok != 0) {
1934 ALOGE("%s pthread_once failed: %d", __func__, ok);
1935 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001936 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001937 }
Eric Laurent4c415062016-06-17 16:14:16 -07001938
1939 // check compatibility with audio effects.
1940 { // scope for mLock
1941 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001942 for (audio_session_t session : {
1943 AUDIO_SESSION_OUTPUT_STAGE,
1944 AUDIO_SESSION_OUTPUT_MIX,
1945 sessionId,
1946 }) {
1947 sp<EffectChain> chain = getEffectChain_l(session);
1948 if (chain.get() != nullptr) {
1949 audio_output_flags_t old = *flags;
1950 chain->checkOutputFlagCompatibility(flags);
1951 if (old != *flags) {
1952 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1953 (int)session, (int)old, (int)*flags);
1954 }
Eric Laurent4c415062016-06-17 16:14:16 -07001955 }
1956 }
1957 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001958 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001959 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1960 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001961 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001962 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1963 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001964 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001965 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001966 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001967 audio_is_linear_pcm(format),
1968 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001969 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001970 }
1971 }
Eric Laurent21da6472017-11-09 16:29:26 -08001972
1973 if (!audio_has_proportional_frames(format)) {
1974 if (sharedBuffer != 0) {
1975 // Same comment as below about ignoring frameCount parameter for set()
1976 frameCount = sharedBuffer->size();
1977 } else if (frameCount == 0) {
1978 frameCount = mNormalFrameCount;
1979 }
1980 if (notificationFrameCount != frameCount) {
1981 notificationFrameCount = frameCount;
1982 }
1983 } else if (sharedBuffer != 0) {
1984 // FIXME: Ensure client side memory buffers need
1985 // not have additional alignment beyond sample
1986 // (e.g. 16 bit stereo accessed as 32 bit frame).
1987 size_t alignment = audio_bytes_per_sample(format);
1988 if (alignment & 1) {
1989 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1990 alignment = 1;
1991 }
1992 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1993 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1994 if (channelCount > 1) {
1995 // More than 2 channels does not require stronger alignment than stereo
1996 alignment <<= 1;
1997 }
1998 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
1999 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2000 sharedBuffer->pointer(), channelCount);
2001 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002002 goto Exit;
2003 }
Eric Laurent21da6472017-11-09 16:29:26 -08002004
2005 // When initializing a shared buffer AudioTrack via constructors,
2006 // there's no frameCount parameter.
2007 // But when initializing a shared buffer AudioTrack via set(),
2008 // there _is_ a frameCount parameter. We silently ignore it.
2009 frameCount = sharedBuffer->size() / frameSize;
2010 } else {
2011 size_t minFrameCount = 0;
2012 // For fast tracks we try to respect the application's request for notifications per buffer.
2013 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2014 if (notificationsPerBuffer > 0) {
2015 // Avoid possible arithmetic overflow during multiplication.
2016 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2017 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2018 notificationsPerBuffer, mFrameCount);
2019 } else {
2020 minFrameCount = mFrameCount * notificationsPerBuffer;
2021 }
2022 }
2023 } else {
2024 // For normal PCM streaming tracks, update minimum frame count.
2025 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2026 // cover audio hardware latency.
2027 // This is probably too conservative, but legacy application code may depend on it.
2028 // If you change this calculation, also review the start threshold which is related.
2029 uint32_t latencyMs = latency_l();
2030 if (latencyMs == 0) {
2031 ALOGE("Error when retrieving output stream latency");
2032 lStatus = UNKNOWN_ERROR;
2033 goto Exit;
2034 }
2035
2036 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2037 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2038
Eric Laurent81784c32012-11-19 14:55:58 -08002039 }
Eric Laurent21da6472017-11-09 16:29:26 -08002040 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002041 frameCount = minFrameCount;
2042 }
Eric Laurent81784c32012-11-19 14:55:58 -08002043 }
Eric Laurent21da6472017-11-09 16:29:26 -08002044
2045 // Make sure that application is notified with sufficient margin before underrun.
2046 // The client can divide the AudioTrack buffer into sub-buffers,
2047 // and expresses its desire to server as the notification frame count.
2048 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2049 size_t maxNotificationFrames;
2050 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2051 // notify every HAL buffer, regardless of the size of the track buffer
2052 maxNotificationFrames = mFrameCount;
2053 } else {
2054 // For normal tracks, use at least double-buffering if no sample rate conversion,
2055 // or at least triple-buffering if there is sample rate conversion
2056 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2057 maxNotificationFrames = frameCount / nBuffering;
2058 // If client requested a fast track but this was denied, then use the smaller maximum.
2059 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2060 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2061 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2062 maxNotificationFrames = maxNotificationFramesFastDenied;
2063 }
2064 }
2065 }
2066 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2067 if (notificationFrameCount == 0) {
2068 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2069 maxNotificationFrames, frameCount);
2070 } else {
2071 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2072 notificationFrameCount, maxNotificationFrames, frameCount);
2073 }
2074 notificationFrameCount = maxNotificationFrames;
2075 }
2076 }
2077
Glenn Kasten74935e42013-12-19 08:56:45 -08002078 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002079 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002080
Glenn Kastenc3df8382014-03-13 15:05:25 -07002081 switch (mType) {
2082
2083 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002084 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002085 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002086 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2087 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002088 sampleRate, format, channelMask, mOutput, mFormat);
2089 lStatus = BAD_VALUE;
2090 goto Exit;
2091 }
2092 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002093 break;
2094
2095 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002096 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002097 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2098 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099 sampleRate, format, channelMask, mOutput, mFormat);
2100 lStatus = BAD_VALUE;
2101 goto Exit;
2102 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002103 break;
2104
2105 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002106 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002107 ALOGE("createTrack_l() Bad parameter: format %#x \""
2108 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002109 format, mOutput, mFormat);
2110 lStatus = BAD_VALUE;
2111 goto Exit;
2112 }
Andy Hungcd044842014-08-07 11:04:34 -07002113 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002114 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2115 lStatus = BAD_VALUE;
2116 goto Exit;
2117 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002118 break;
2119
Eric Laurent81784c32012-11-19 14:55:58 -08002120 }
2121
2122 lStatus = initCheck();
2123 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002124 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002125 goto Exit;
2126 }
2127
2128 { // scope for mLock
2129 Mutex::Autolock _l(mLock);
2130
2131 // all tracks in same audio session must share the same routing strategy otherwise
2132 // conflicts will happen when tracks are moved from one output to another by audio policy
2133 // manager
2134 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2135 for (size_t i = 0; i < mTracks.size(); ++i) {
2136 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002137 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002138 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2139 if (sessionId == t->sessionId() && strategy != actual) {
2140 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2141 strategy, actual);
2142 lStatus = BAD_VALUE;
2143 goto Exit;
2144 }
2145 }
2146 }
2147
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002148 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002149 channelMask, frameCount,
2150 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002151 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002152
Glenn Kasten03003332013-08-06 15:40:54 -07002153 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2154 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002155 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002156 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002157 goto Exit;
2158 }
2159 mTracks.add(track);
2160
2161 sp<EffectChain> chain = getEffectChain_l(sessionId);
2162 if (chain != 0) {
2163 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2164 track->setMainBuffer(chain->inBuffer());
2165 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2166 chain->incTrackCnt();
2167 }
2168
Eric Laurent05067782016-06-01 18:27:28 -07002169 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002170 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2171 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2172 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002173 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002174 }
2175 }
2176
2177 lStatus = NO_ERROR;
2178
2179Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002180 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002181 return track;
2182}
2183
Andy Hung1bc088a2018-02-09 15:57:31 -08002184template<typename T>
2185ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2186{
2187 const ssize_t index = mTracks.add(track);
2188 if (index >= 0) {
2189 // set name for track when adding.
2190 int name;
2191 if (mUnusedTrackNames.empty()) {
2192 name = mTracks.size() - 1; // new name {0 ... size-1}.
2193 } else {
2194 // reuse smallest name for deleted track.
2195 auto it = mUnusedTrackNames.begin();
2196 name = *it;
2197 (void)mUnusedTrackNames.erase(it);
2198 }
2199 track->setName(name);
2200 } else {
2201 LOG_ALWAYS_FATAL("cannot add track");
2202 }
2203 return index;
2204}
2205
2206template<typename T>
2207ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2208{
2209 const int name = track->name();
2210 const ssize_t index = mTracks.remove(track);
2211 if (index >= 0) {
2212 // invalidate name when removing from mTracks.
2213 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2214
2215 if (mSaveDeletedTrackNames) {
2216 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2217 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2218 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2219 mDeletedTrackNames.emplace(name);
2220 }
2221
2222 mUnusedTrackNames.emplace(name);
2223 track->setName(T::TRACK_NAME_PENDING);
2224 } else {
2225 LOG_ALWAYS_FATAL_IF(name >= 0,
2226 "valid name %d for track not in mTracks (returned %zd)", name, index);
2227 }
2228 return index;
2229}
2230
Eric Laurent81784c32012-11-19 14:55:58 -08002231uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2232{
2233 return latency;
2234}
2235
2236uint32_t AudioFlinger::PlaybackThread::latency() const
2237{
2238 Mutex::Autolock _l(mLock);
2239 return latency_l();
2240}
2241uint32_t AudioFlinger::PlaybackThread::latency_l() const
2242{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002243 uint32_t latency;
2244 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2245 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002246 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002247 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002248}
2249
2250void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2251{
2252 Mutex::Autolock _l(mLock);
2253 // Don't apply master volume in SW if our HAL can do it for us.
2254 if (mOutput && mOutput->audioHwDev &&
2255 mOutput->audioHwDev->canSetMasterVolume()) {
2256 mMasterVolume = 1.0;
2257 } else {
2258 mMasterVolume = value;
2259 }
2260}
2261
2262void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2263{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002264 if (isDuplicating()) {
2265 return;
2266 }
Eric Laurent81784c32012-11-19 14:55:58 -08002267 Mutex::Autolock _l(mLock);
2268 // Don't apply master mute in SW if our HAL can do it for us.
2269 if (mOutput && mOutput->audioHwDev &&
2270 mOutput->audioHwDev->canSetMasterMute()) {
2271 mMasterMute = false;
2272 } else {
2273 mMasterMute = muted;
2274 }
2275}
2276
2277void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2278{
2279 Mutex::Autolock _l(mLock);
2280 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002281 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002282}
2283
2284void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2285{
2286 Mutex::Autolock _l(mLock);
2287 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002288 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002289}
2290
2291float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2292{
2293 Mutex::Autolock _l(mLock);
2294 return mStreamTypes[stream].volume;
2295}
2296
2297// addTrack_l() must be called with ThreadBase::mLock held
2298status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2299{
2300 status_t status = ALREADY_EXISTS;
2301
Eric Laurent81784c32012-11-19 14:55:58 -08002302 if (mActiveTracks.indexOf(track) < 0) {
2303 // the track is newly added, make sure it fills up all its
2304 // buffers before playing. This is to ensure the client will
2305 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002306 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002307 TrackBase::track_state state = track->mState;
2308 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002309 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002310 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002311 mLock.lock();
2312 // abort track was stopped/paused while we released the lock
2313 if (state != track->mState) {
2314 if (status == NO_ERROR) {
2315 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002316 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002317 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002318 mLock.lock();
2319 }
2320 return INVALID_OPERATION;
2321 }
2322 // abort if start is rejected by audio policy manager
2323 if (status != NO_ERROR) {
2324 return PERMISSION_DENIED;
2325 }
2326#ifdef ADD_BATTERY_DATA
2327 // to track the speaker usage
2328 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2329#endif
2330 }
2331
Eric Laurent51716182016-02-29 18:00:56 -08002332 // set retry count for buffer fill
2333 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002334 if (track->isStopping_1()) {
2335 track->mRetryCount = kMaxTrackStopRetriesOffload;
2336 } else {
2337 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2338 }
2339 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002340 } else {
2341 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002342 track->mFillingUpStatus =
2343 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002344 }
2345
Eric Laurent81784c32012-11-19 14:55:58 -08002346 track->mResetDone = false;
2347 track->mPresentationCompleteFrames = 0;
2348 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002349 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2350 if (chain != 0) {
2351 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2352 track->sessionId());
2353 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002354 }
2355
2356 status = NO_ERROR;
2357 }
2358
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002359 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002360 return status;
2361}
2362
Eric Laurentbfb1b832013-01-07 09:53:42 -08002363bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002364{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002365 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002366 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002367 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2368 track->mState = TrackBase::STOPPED;
2369 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002370 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002371 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002372 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002373 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002374
2375 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002376}
2377
2378void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2379{
2380 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002381
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002382 String8 result;
2383 track->appendDump(result, false /* active */);
2384 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002385
Eric Laurent81784c32012-11-19 14:55:58 -08002386 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002387 if (track->isFastTrack()) {
2388 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002389 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002390 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2391 mFastTrackAvailMask |= 1 << index;
2392 // redundant as track is about to be destroyed, for dumpsys only
2393 track->mFastIndex = -1;
2394 }
2395 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2396 if (chain != 0) {
2397 chain->decTrackCnt();
2398 }
2399}
2400
2401String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2402{
Eric Laurent81784c32012-11-19 14:55:58 -08002403 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002404 String8 out_s8;
2405 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2406 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002407 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002408 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002409}
2410
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002411void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002412 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2413 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002414
Eric Laurent73e26b62015-04-27 16:55:58 -07002415 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002416
2417 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002418 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002419 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002420 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002421 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002422 desc->mChannelMask = mChannelMask;
2423 desc->mSamplingRate = mSampleRate;
2424 desc->mFormat = mFormat;
2425 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002426 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002427 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002428 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002429 break;
2430
Eric Laurent73e26b62015-04-27 16:55:58 -07002431 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002432 default:
2433 break;
2434 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002435 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002436}
2437
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002438void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002439{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002440 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002441}
2442
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002443void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002444{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002445 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446}
2447
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002448void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002449{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002450 mCallbackThread->setAsyncError();
2451}
2452
Eric Laurent3b4529e2013-09-05 18:09:19 -07002453void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002454{
2455 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002456 // reject out of sequence requests
2457 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2458 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002459 mWaitWorkCV.signal();
2460 }
2461}
2462
Eric Laurent3b4529e2013-09-05 18:09:19 -07002463void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002464{
2465 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002466 // reject out of sequence requests
2467 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2468 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002469 mWaitWorkCV.signal();
2470 }
2471}
2472
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002473void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002474{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002475 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002476 mSampleRate = mOutput->getSampleRate();
2477 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002478 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002479 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002480 }
Andy Hung9a592762014-07-21 21:56:01 -07002481 if ((mType == MIXER || mType == DUPLICATING)
2482 && !isValidPcmSinkChannelMask(mChannelMask)) {
2483 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2484 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002485 }
Andy Hunge5412692014-05-16 11:25:07 -07002486 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002487
2488 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002489 status_t result = mOutput->stream->getFormat(&mHALFormat);
2490 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002491 // Get format from the shim, which will be different than the HAL format
2492 // if playing compressed audio over HDMI passthrough.
2493 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002494 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002495 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002496 }
Andy Hung6146c082014-03-18 11:56:15 -07002497 if ((mType == MIXER || mType == DUPLICATING)
2498 && !isValidPcmSinkFormat(mFormat)) {
2499 LOG_FATAL("HAL format %#x not supported for mixed output",
2500 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002501 }
Phil Burk062e67a2015-02-11 13:40:50 -08002502 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002503 result = mOutput->stream->getBufferSize(&mBufferSize);
2504 LOG_ALWAYS_FATAL_IF(result != OK,
2505 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002506 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002507 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002508 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002509 mFrameCount);
2510 }
2511
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002512 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2513 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002514 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002515 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002516 }
2517 }
2518
Eric Laurentd1f69b02014-12-15 14:33:13 -08002519 mHwSupportsPause = false;
2520 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002521 bool supportsPause = false, supportsResume = false;
2522 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2523 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002524 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002525 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002526 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002527 } else if (supportsResume) {
2528 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002529 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002530 }
2531 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002532 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2533 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2534 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002535
Andy Hungfbfc3952015-01-15 13:33:51 -08002536 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2537 // For best precision, we use float instead of the associated output
2538 // device format (typically PCM 16 bit).
2539
2540 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2541 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2542 mBufferSize = mFrameSize * mFrameCount;
2543
2544 // TODO: We currently use the associated output device channel mask and sample rate.
2545 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2546 // (if a valid mask) to avoid premature downmix.
2547 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2548 // instead of the output device sample rate to avoid loss of high frequency information.
2549 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2550 }
2551
Andy Hung09a50072014-02-27 14:30:47 -08002552 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002553 double multiplier = 1.0;
2554 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2555 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002556 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2557 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002558
Eric Laurent81784c32012-11-19 14:55:58 -08002559 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2560 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2561 maxNormalFrameCount = maxNormalFrameCount & ~15;
2562 if (maxNormalFrameCount < minNormalFrameCount) {
2563 maxNormalFrameCount = minNormalFrameCount;
2564 }
2565 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2566 if (multiplier <= 1.0) {
2567 multiplier = 1.0;
2568 } else if (multiplier <= 2.0) {
2569 if (2 * mFrameCount <= maxNormalFrameCount) {
2570 multiplier = 2.0;
2571 } else {
2572 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2573 }
2574 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002575 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002576 }
2577 }
2578 mNormalFrameCount = multiplier * mFrameCount;
2579 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002580 if (mType == MIXER || mType == DUPLICATING) {
2581 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2582 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002583 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002584 mNormalFrameCount);
2585
Andy Hung08fb1742015-05-31 23:22:10 -07002586 // Check if we want to throttle the processing to no more than 2x normal rate
2587 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002588 mThreadThrottleTimeMs = 0;
2589 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002590 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2591
Andy Hung010a1a12014-03-13 13:57:33 -07002592 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2593 // Originally this was int16_t[] array, need to remove legacy implications.
2594 free(mSinkBuffer);
2595 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002596 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2597 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2598 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002599 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002600
Andy Hung69aed5f2014-02-25 17:24:40 -08002601 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2602 // drives the output.
2603 free(mMixerBuffer);
2604 mMixerBuffer = NULL;
2605 if (mMixerBufferEnabled) {
2606 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2607 mMixerBufferSize = mNormalFrameCount * mChannelCount
2608 * audio_bytes_per_sample(mMixerBufferFormat);
2609 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2610 }
Andy Hung98ef9782014-03-04 14:46:50 -08002611 free(mEffectBuffer);
2612 mEffectBuffer = NULL;
2613 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002614 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002615 mEffectBufferSize = mNormalFrameCount * mChannelCount
2616 * audio_bytes_per_sample(mEffectBufferFormat);
2617 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2618 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002619
Eric Laurent81784c32012-11-19 14:55:58 -08002620 // force reconfiguration of effect chains and engines to take new buffer size and audio
2621 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002622 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002623 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2624 // matter.
2625 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2626 Vector< sp<EffectChain> > effectChains = mEffectChains;
2627 for (size_t i = 0; i < effectChains.size(); i ++) {
2628 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2629 }
2630}
2631
Kevin Rocard069c2712018-03-29 19:09:14 -07002632void AudioFlinger::PlaybackThread::updateMetadata_l()
2633{
Kevin Rocard12381092018-04-11 09:19:59 -07002634 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2635 return; // That should not happen
2636 }
2637 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2638 for (const sp<Track> &track : mActiveTracks) {
2639 // Do not short-circuit as all hasChanged states must be reset
2640 // as all the metadata are going to be sent
2641 hasChanged |= track->readAndClearHasChanged();
2642 }
2643 if (!hasChanged) {
2644 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002645 }
2646 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002647 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002648 for (const sp<Track> &track : mActiveTracks) {
2649 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002650 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002651 }
Kevin Rocard12381092018-04-11 09:19:59 -07002652 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002653}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002654
Kevin Rocard12381092018-04-11 09:19:59 -07002655void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2656 const StreamOutHalInterface::SourceMetadata& metadata)
2657{
2658 mOutput->stream->updateSourceMetadata(metadata);
2659};
2660
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002661status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002662{
2663 if (halFrames == NULL || dspFrames == NULL) {
2664 return BAD_VALUE;
2665 }
2666 Mutex::Autolock _l(mLock);
2667 if (initCheck() != NO_ERROR) {
2668 return INVALID_OPERATION;
2669 }
Andy Hung818e7a32016-02-16 18:08:07 -08002670 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002671 *halFrames = framesWritten;
2672
2673 if (isSuspended()) {
2674 // return an estimation of rendered frames when the output is suspended
2675 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002676 *dspFrames = (uint32_t)
2677 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002678 return NO_ERROR;
2679 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002680 status_t status;
2681 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002682 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002683 *dspFrames = (size_t)frames;
2684 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002685 }
2686}
2687
Eric Laurent4c415062016-06-17 16:14:16 -07002688// hasAudioSession_l() must be called with ThreadBase::mLock held
2689uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002690{
Eric Laurent81784c32012-11-19 14:55:58 -08002691 uint32_t result = 0;
2692 if (getEffectChain_l(sessionId) != 0) {
2693 result = EFFECT_SESSION;
2694 }
2695
2696 for (size_t i = 0; i < mTracks.size(); ++i) {
2697 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002698 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002699 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002700 if (track->isFastTrack()) {
2701 result |= FAST_SESSION;
2702 }
Eric Laurent81784c32012-11-19 14:55:58 -08002703 break;
2704 }
2705 }
2706
2707 return result;
2708}
2709
Glenn Kastend848eb42016-03-08 13:42:11 -08002710uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002711{
2712 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2713 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2714 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2715 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
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 return AudioSystem::getStrategyForStream(track->streamType());
2721 }
2722 }
2723 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2724}
2725
2726
Phil Burk062e67a2015-02-11 13:40:50 -08002727AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002728{
2729 Mutex::Autolock _l(mLock);
2730 return mOutput;
2731}
2732
Phil Burk062e67a2015-02-11 13:40:50 -08002733AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002734{
2735 Mutex::Autolock _l(mLock);
2736 AudioStreamOut *output = mOutput;
2737 mOutput = NULL;
2738 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2739 // must push a NULL and wait for ack
2740 mOutputSink.clear();
2741 mPipeSink.clear();
2742 mNormalSink.clear();
2743 return output;
2744}
2745
2746// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002747sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002748{
2749 if (mOutput == NULL) {
2750 return NULL;
2751 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002752 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002753}
2754
2755uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2756{
2757 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2758}
2759
2760status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2761{
2762 if (!isValidSyncEvent(event)) {
2763 return BAD_VALUE;
2764 }
2765
2766 Mutex::Autolock _l(mLock);
2767
2768 for (size_t i = 0; i < mTracks.size(); ++i) {
2769 sp<Track> track = mTracks[i];
2770 if (event->triggerSession() == track->sessionId()) {
2771 (void) track->setSyncEvent(event);
2772 return NO_ERROR;
2773 }
2774 }
2775
2776 return NAME_NOT_FOUND;
2777}
2778
2779bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2780{
2781 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2782}
2783
2784void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2785 const Vector< sp<Track> >& tracksToRemove)
2786{
2787 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002788 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002789 for (size_t i = 0 ; i < count ; i++) {
2790 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002791 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002792 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002793 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002794#ifdef ADD_BATTERY_DATA
2795 // to track the speaker usage
2796 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2797#endif
2798 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002799 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002800 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002801 }
Eric Laurent81784c32012-11-19 14:55:58 -08002802 }
2803 }
2804 }
Eric Laurent81784c32012-11-19 14:55:58 -08002805}
2806
2807void AudioFlinger::PlaybackThread::checkSilentMode_l()
2808{
2809 if (!mMasterMute) {
2810 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002811 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2812 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2813 return;
2814 }
Eric Laurent81784c32012-11-19 14:55:58 -08002815 if (property_get("ro.audio.silent", value, "0") > 0) {
2816 char *endptr;
2817 unsigned long ul = strtoul(value, &endptr, 0);
2818 if (*endptr == '\0' && ul != 0) {
2819 ALOGD("Silence is golden");
2820 // The setprop command will not allow a property to be changed after
2821 // the first time it is set, so we don't have to worry about un-muting.
2822 setMasterMute_l(true);
2823 }
2824 }
2825 }
2826}
2827
2828// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002829ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002830{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002831 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002832 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002833 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002834 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002835
2836 // If an NBAIO sink is present, use it to write the normal mixer's submix
2837 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002838
Andy Hung010a1a12014-03-13 13:57:33 -07002839 const size_t count = mBytesRemaining / mFrameSize;
2840
Simon Wilson2d590962012-11-29 15:18:50 -08002841 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002842 // update the setpoint when AudioFlinger::mScreenState changes
2843 uint32_t screenState = AudioFlinger::mScreenState;
2844 if (screenState != mScreenState) {
2845 mScreenState = screenState;
2846 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2847 if (pipe != NULL) {
2848 pipe->setAvgFrames((mScreenState & 1) ?
2849 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2850 }
2851 }
Andy Hung010a1a12014-03-13 13:57:33 -07002852 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002853 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002854 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002855 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002856 } else {
2857 bytesWritten = framesWritten;
2858 }
2859 // otherwise use the HAL / AudioStreamOut directly
2860 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002862
Eric Laurentbfb1b832013-01-07 09:53:42 -08002863 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002864 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2865 mWriteAckSequence += 2;
2866 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002868 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002870 // FIXME We should have an implementation of timestamps for direct output threads.
2871 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002872 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002873
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 if (mUseAsyncWrite &&
2875 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2876 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002877 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002879 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 }
Eric Laurent81784c32012-11-19 14:55:58 -08002881 }
2882
Eric Laurent81784c32012-11-19 14:55:58 -08002883 mNumWrites++;
2884 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002885 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 return bytesWritten;
2887}
2888
2889void AudioFlinger::PlaybackThread::threadLoop_drain()
2890{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002891 bool supportsDrain = false;
2892 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2894 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002895 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2896 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002898 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002900 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002901 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902 }
2903}
2904
2905void AudioFlinger::PlaybackThread::threadLoop_exit()
2906{
Eric Laurent275e8e92014-11-30 15:14:47 -08002907 {
2908 Mutex::Autolock _l(mLock);
2909 for (size_t i = 0; i < mTracks.size(); i++) {
2910 sp<Track> track = mTracks[i];
2911 track->invalidate();
2912 }
Andy Hungdae27702016-10-31 14:01:16 -07002913 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2914 // After we exit there are no more track changes sent to BatteryNotifier
2915 // because that requires an active threadLoop.
2916 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2917 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002918 }
Eric Laurent81784c32012-11-19 14:55:58 -08002919}
2920
2921/*
2922The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002923 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002924 - mActiveSleepTimeUs from activeSleepTimeUs()
2925 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002926 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2927 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002928 - maxPeriod from frame count and sample rate (MIXER only)
2929
2930The parameters that affect these derived values are:
2931 - frame count
2932 - frame size
2933 - sample rate
2934 - device type: A2DP or not
2935 - device latency
2936 - format: PCM or not
2937 - active sleep time
2938 - idle sleep time
2939*/
2940
2941void AudioFlinger::PlaybackThread::cacheParameters_l()
2942{
Andy Hung25c2dac2014-02-27 14:56:00 -08002943 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002944 mActiveSleepTimeUs = activeSleepTimeUs();
2945 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002946
2947 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2948 // truncating audio when going to standby.
2949 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2950 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2951 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2952 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2953 }
2954 }
Eric Laurent81784c32012-11-19 14:55:58 -08002955}
2956
Eric Laurent13084622016-05-17 10:51:49 -07002957bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002958{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002959 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002960 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002961 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002962 size_t size = mTracks.size();
2963 for (size_t i = 0; i < size; i++) {
2964 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002965 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002966 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002967 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002968 }
2969 }
Eric Laurent13084622016-05-17 10:51:49 -07002970 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002971}
2972
Haynes Mathew George05317d22016-05-03 16:34:26 -07002973void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2974{
2975 Mutex::Autolock _l(mLock);
2976 invalidateTracks_l(streamType);
2977}
2978
Eric Laurent81784c32012-11-19 14:55:58 -08002979status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2980{
Glenn Kastend848eb42016-03-08 13:42:11 -08002981 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002982 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002983 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002984 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2985 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2986 &halInBuffer);
2987 if (result != OK) return result;
2988 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002989 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002990 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002991 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002992 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002993 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002994 if (mType != DIRECT) {
2995 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002996 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07002997 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002998 &halInBuffer);
2999 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003000#ifdef FLOAT_EFFECT_CHAIN
3001 buffer = halInBuffer->audioBuffer()->f32;
3002#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003003 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003004#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003005 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3006 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003007 }
3008
3009 // Attach all tracks with same session ID to this chain.
3010 for (size_t i = 0; i < mTracks.size(); ++i) {
3011 sp<Track> track = mTracks[i];
3012 if (session == track->sessionId()) {
3013 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3014 buffer);
3015 track->setMainBuffer(buffer);
3016 chain->incTrackCnt();
3017 }
3018 }
3019
3020 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003021 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003022 if (session == track->sessionId()) {
3023 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3024 chain->incActiveTrackCnt();
3025 }
3026 }
3027 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003028 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003029 chain->setInBuffer(halInBuffer);
3030 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003031 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003032 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003033 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3034 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003035 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003036 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003037 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003038 // Effect chain for other sessions are inserted at beginning of effect
3039 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003040 // sessions is not important.
3041 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3042 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3043 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003044 size_t size = mEffectChains.size();
3045 size_t i = 0;
3046 for (i = 0; i < size; i++) {
3047 if (mEffectChains[i]->sessionId() < session) {
3048 break;
3049 }
3050 }
3051 mEffectChains.insertAt(chain, i);
3052 checkSuspendOnAddEffectChain_l(chain);
3053
3054 return NO_ERROR;
3055}
3056
3057size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3058{
Glenn Kastend848eb42016-03-08 13:42:11 -08003059 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003060
3061 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3062
3063 for (size_t i = 0; i < mEffectChains.size(); i++) {
3064 if (chain == mEffectChains[i]) {
3065 mEffectChains.removeAt(i);
3066 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003067 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003068 if (session == track->sessionId()) {
3069 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3070 chain.get(), session);
3071 chain->decActiveTrackCnt();
3072 }
3073 }
3074
3075 // detach all tracks with same session ID from this chain
3076 for (size_t i = 0; i < mTracks.size(); ++i) {
3077 sp<Track> track = mTracks[i];
3078 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003079 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003080 chain->decTrackCnt();
3081 }
3082 }
3083 break;
3084 }
3085 }
3086 return mEffectChains.size();
3087}
3088
3089status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003090 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003091{
3092 Mutex::Autolock _l(mLock);
3093 return attachAuxEffect_l(track, EffectId);
3094}
3095
3096status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003097 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003098{
3099 status_t status = NO_ERROR;
3100
3101 if (EffectId == 0) {
3102 track->setAuxBuffer(0, NULL);
3103 } else {
3104 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3105 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3106 if (effect != 0) {
3107 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3108 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3109 } else {
3110 status = INVALID_OPERATION;
3111 }
3112 } else {
3113 status = BAD_VALUE;
3114 }
3115 }
3116 return status;
3117}
3118
3119void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3120{
3121 for (size_t i = 0; i < mTracks.size(); ++i) {
3122 sp<Track> track = mTracks[i];
3123 if (track->auxEffectId() == effectId) {
3124 attachAuxEffect_l(track, 0);
3125 }
3126 }
3127}
3128
3129bool AudioFlinger::PlaybackThread::threadLoop()
3130{
Glenn Kasten388d5712017-04-07 14:38:41 -07003131 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003132
Eric Laurent81784c32012-11-19 14:55:58 -08003133 Vector< sp<Track> > tracksToRemove;
3134
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003135 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003136 nsecs_t lastWriteFinished = -1; // time last server write completed
3137 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003138
3139 // MIXER
3140 nsecs_t lastWarning = 0;
3141
3142 // DUPLICATING
3143 // FIXME could this be made local to while loop?
3144 writeFrames = 0;
3145
3146 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003147 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003148
3149 if (mType == MIXER) {
3150 sleepTimeShift = 0;
3151 }
3152
3153 CpuStats cpuStats;
3154 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3155
3156 acquireWakeLock();
3157
Glenn Kasteneef598c2017-04-03 14:41:13 -07003158 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3159 // thread associated with this PlaybackThread.
3160 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3161 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003162 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3163 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003164 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003165 const char *logString = NULL;
3166
rago1bb90822017-05-02 18:31:48 -07003167 // Estimated time for next buffer to be written to hal. This is used only on
3168 // suspended mode (for now) to help schedule the wait time until next iteration.
3169 nsecs_t timeLoopNextNs = 0;
3170
Eric Laurent664539d2013-09-23 18:24:31 -07003171 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003172
Eric Laurent81784c32012-11-19 14:55:58 -08003173 while (!exitPending())
3174 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003175 // Log merge requests are performed during AudioFlinger binder transactions, but
3176 // that does not cover audio playback. It's requested here for that reason.
3177 mAudioFlinger->requestLogMerge();
3178
Eric Laurent81784c32012-11-19 14:55:58 -08003179 cpuStats.sample(myName);
3180
3181 Vector< sp<EffectChain> > effectChains;
3182
Eric Laurent81784c32012-11-19 14:55:58 -08003183 { // scope for mLock
3184
3185 Mutex::Autolock _l(mLock);
3186
Eric Laurent021cf962014-05-13 10:18:14 -07003187 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003188
Glenn Kasteneef598c2017-04-03 14:41:13 -07003189 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003190 if (logString != NULL) {
3191 mNBLogWriter->logTimestamp();
3192 mNBLogWriter->log(logString);
3193 logString = NULL;
3194 }
3195
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003196 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003197 // and associate with the sink frames written out. We need
3198 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003199 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003200 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003201 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003202 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003203 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003204 ExtendedTimestamp timestamp; // use private copy to fetch
3205 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003206
3207 // We keep track of the last valid kernel position in case we are in underrun
3208 // and the normal mixer period is the same as the fast mixer period, or there
3209 // is some error from the HAL.
3210 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3211 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3212 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3213 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3214 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3215
3216 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3217 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3218 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3219 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003220 }
3221
3222 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3223 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003224 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003225 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003226 }
3227
Andy Hung818e7a32016-02-16 18:08:07 -08003228 // copy over kernel info
3229 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003230 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3231 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003232 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3233 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003234 }
3235 // mFramesWritten for non-offloaded tracks are contiguous
3236 // even after standby() is called. This is useful for the track frame
3237 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003238 bool serverLocationUpdate = false;
3239 if (mFramesWritten != lastFramesWritten) {
3240 serverLocationUpdate = true;
3241 lastFramesWritten = mFramesWritten;
3242 }
3243 // Only update timestamps if there is a meaningful change.
3244 // Either the kernel timestamp must be valid or we have written something.
3245 if (kernelLocationUpdate || serverLocationUpdate) {
3246 if (serverLocationUpdate) {
3247 // use the time before we called the HAL write - it is a bit more accurate
3248 // to when the server last read data than the current time here.
3249 //
3250 // If we haven't written anything, mLastWriteTime will be -1
3251 // and we use systemTime().
3252 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3253 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3254 ? systemTime() : mLastWriteTime;
3255 }
Andy Hungdae27702016-10-31 14:01:16 -07003256
3257 for (const sp<Track> &t : mActiveTracks) {
3258 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003259 t->updateTrackFrameInfo(
3260 t->mAudioTrackServerProxy->framesReleased(),
3261 mFramesWritten,
3262 mTimestamp);
3263 }
Andy Hunge10393e2015-06-12 13:59:33 -07003264 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003265 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003266#if 0
3267 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003268 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003269 timespec ts;
3270 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003271 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003272 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003273 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003274 }
3275 ++z;
3276#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003277 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003278 if (mSignalPending) {
3279 // A signal was raised while we were unlocked
3280 mSignalPending = false;
3281 } else if (waitingAsyncCallback_l()) {
3282 if (exitPending()) {
3283 break;
3284 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003285 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003286 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003287 releaseWakeLock_l();
3288 released = true;
3289 }
Andy Hung10cbff12017-02-21 17:30:14 -08003290
3291 const int64_t waitNs = computeWaitTimeNs_l();
3292 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3293 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3294 if (status == TIMED_OUT) {
3295 mSignalPending = true; // if timeout recheck everything
3296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003298 if (released) {
3299 acquireWakeLock_l();
3300 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003301 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3302 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003303
3304 continue;
3305 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003306 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003307 isSuspended()) {
3308 // put audio hardware into standby after short delay
3309 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003310
3311 threadLoop_standby();
3312
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003313 // This is where we go into standby
3314 if (!mStandby) {
3315 LOG_AUDIO_STATE();
3316 }
Eric Laurent81784c32012-11-19 14:55:58 -08003317 mStandby = true;
3318 }
3319
3320 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3321 // we're about to wait, flush the binder command buffer
3322 IPCThreadState::self()->flushCommands();
3323
3324 clearOutputTracks();
3325
3326 if (exitPending()) {
3327 break;
3328 }
3329
3330 releaseWakeLock_l();
3331 // wait until we have something to do...
3332 ALOGV("%s going to sleep", myName.string());
3333 mWaitWorkCV.wait(mLock);
3334 ALOGV("%s waking up", myName.string());
3335 acquireWakeLock_l();
3336
3337 mMixerStatus = MIXER_IDLE;
3338 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3339 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003340 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003341 checkSilentMode_l();
3342
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003343 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3344 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003345 if (mType == MIXER) {
3346 sleepTimeShift = 0;
3347 }
3348
3349 continue;
3350 }
3351 }
Eric Laurent81784c32012-11-19 14:55:58 -08003352 // mMixerStatusIgnoringFastTracks is also updated internally
3353 mMixerStatus = prepareTracks_l(&tracksToRemove);
3354
Andy Hungdae27702016-10-31 14:01:16 -07003355 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003356
Kevin Rocard069c2712018-03-29 19:09:14 -07003357 updateMetadata_l();
3358
Eric Laurent81784c32012-11-19 14:55:58 -08003359 // prevent any changes in effect chain list and in each effect chain
3360 // during mixing and effect process as the audio buffers could be deleted
3361 // or modified if an effect is created or deleted
3362 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003363 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003364
Eric Laurentbfb1b832013-01-07 09:53:42 -08003365 if (mBytesRemaining == 0) {
3366 mCurrentWriteLength = 0;
3367 if (mMixerStatus == MIXER_TRACKS_READY) {
3368 // threadLoop_mix() sets mCurrentWriteLength
3369 threadLoop_mix();
3370 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3371 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003372 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003373 // must be written to HAL
3374 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003375 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003376 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003377 }
3378 }
Andy Hung98ef9782014-03-04 14:46:50 -08003379 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003380 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003381 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3382 // or mSinkBuffer (if there are no effects).
3383 //
3384 // This is done pre-effects computation; if effects change to
3385 // support higher precision, this needs to move.
3386 //
3387 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003388 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003389 if (mMixerBufferValid) {
3390 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3391 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3392
Andy Hung2ddee192015-12-18 17:34:44 -08003393 // mono blend occurs for mixer threads only (not direct or offloaded)
3394 // and is handled here if we're going directly to the sink.
3395 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003396 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3397 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003398 }
3399
Andy Hung98ef9782014-03-04 14:46:50 -08003400 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3401 mNormalFrameCount * mChannelCount);
3402 }
3403
Eric Laurentbfb1b832013-01-07 09:53:42 -08003404 mBytesRemaining = mCurrentWriteLength;
3405 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003406 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3407 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3408 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3409 mBytesWritten += mBytesRemaining;
3410 mFramesWritten += framesRemaining;
3411 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003412 mBytesRemaining = 0;
3413 }
Eric Laurent81784c32012-11-19 14:55:58 -08003414
Eric Laurentbfb1b832013-01-07 09:53:42 -08003415 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003416 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003417 for (size_t i = 0; i < effectChains.size(); i ++) {
3418 effectChains[i]->process_l();
3419 }
Eric Laurent81784c32012-11-19 14:55:58 -08003420 }
3421 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003422 // Process effect chains for offloaded thread even if no audio
3423 // was read from audio track: process only updates effect state
3424 // and thus does have to be synchronized with audio writes but may have
3425 // to be called while waiting for async write callback
3426 if (mType == OFFLOAD) {
3427 for (size_t i = 0; i < effectChains.size(); i ++) {
3428 effectChains[i]->process_l();
3429 }
3430 }
Eric Laurent81784c32012-11-19 14:55:58 -08003431
Andy Hung98ef9782014-03-04 14:46:50 -08003432 // Only if the Effects buffer is enabled and there is data in the
3433 // Effects buffer (buffer valid), we need to
3434 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003435 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003436 if (mEffectBufferValid) {
3437 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003438
3439 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003440 mono_blend(mEffectBuffer, mEffectBufferFormat, 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(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3445 mNormalFrameCount * mChannelCount);
3446 }
3447
Eric Laurent81784c32012-11-19 14:55:58 -08003448 // enable changes in effect chain
3449 unlockEffectChains(effectChains);
3450
Eric Laurentbfb1b832013-01-07 09:53:42 -08003451 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003452 // mSleepTimeUs == 0 means we must write to audio hardware
3453 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003454 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003455 // We save lastWriteFinished here, as previousLastWriteFinished,
3456 // for throttling. On thread start, previousLastWriteFinished will be
3457 // set to -1, which properly results in no throttling after the first write.
3458 nsecs_t previousLastWriteFinished = lastWriteFinished;
3459 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003460 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003461 // FIXME rewrite to reduce number of system calls
3462 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003463 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003464 lastWriteFinished = systemTime();
3465 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 if (ret < 0) {
3467 mBytesRemaining = 0;
3468 } else {
3469 mBytesWritten += ret;
3470 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003471 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472 }
3473 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3474 (mMixerStatus == MIXER_DRAIN_ALL)) {
3475 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003476 }
Andy Hung08fb1742015-05-31 23:22:10 -07003477 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003478 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003479 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003480 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003481 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003482 ATRACE_NAME("underrun");
3483 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003484 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003485 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003486 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003487 }
Andy Hung08fb1742015-05-31 23:22:10 -07003488
3489 if (mThreadThrottle
3490 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3491 && ret > 0) { // we wrote something
3492 // Limit MixerThread data processing to no more than twice the
3493 // expected processing rate.
3494 //
3495 // This helps prevent underruns with NuPlayer and other applications
3496 // which may set up buffers that are close to the minimum size, or use
3497 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3498 //
3499 // The throttle smooths out sudden large data drains from the device,
3500 // e.g. when it comes out of standby, which often causes problems with
3501 // (1) mixer threads without a fast mixer (which has its own warm-up)
3502 // (2) minimum buffer sized tracks (even if the track is full,
3503 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003504 //
3505 // Total time spent in last processing cycle equals time spent in
3506 // 1. threadLoop_write, as well as time spent in
3507 // 2. threadLoop_mix (significant for heavy mixing, especially
3508 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003509
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003510 // it's OK if deltaMs (and deltaNs) is an overestimate.
3511 nsecs_t deltaNs;
3512 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3513 __builtin_sub_overflow(
3514 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3515 const int32_t deltaMs = deltaNs / 1000000;
3516
Ivan Lozanoea04d392017-11-07 14:37:07 -08003517 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003518 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3519 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003520 // notify of throttle start on verbose log
3521 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3522 "mixer(%p) throttle begin:"
3523 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003524 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003525 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003526 // Throttle must be attributed to the previous mixer loop's write time
3527 // to allow back-to-back throttling.
3528 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003529 } else {
3530 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3531 if (diff > 0) {
3532 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003533 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003534 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3535 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003536 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003537 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3538 }
Andy Hung08fb1742015-05-31 23:22:10 -07003539 }
3540 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003541 }
Eric Laurent81784c32012-11-19 14:55:58 -08003542
Eric Laurentbfb1b832013-01-07 09:53:42 -08003543 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003544 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003545 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003546 // suspended requires accurate metering of sleep time.
3547 if (isSuspended()) {
3548 // advance by expected sleepTime
3549 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3550 const nsecs_t nowNs = systemTime();
3551
3552 // compute expected next time vs current time.
3553 // (negative deltas are treated as delays).
3554 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3555 if (deltaNs < -kMaxNextBufferDelayNs) {
3556 // Delays longer than the max allowed trigger a reset.
3557 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3558 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3559 timeLoopNextNs = nowNs + deltaNs;
3560 } else if (deltaNs < 0) {
3561 // Delays within the max delay allowed: zero the delta/sleepTime
3562 // to help the system catch up in the next iteration(s)
3563 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3564 deltaNs = 0;
3565 }
3566 // update sleep time (which is >= 0)
3567 mSleepTimeUs = deltaNs / 1000;
3568 }
Eric Laurente93cc032016-05-05 10:15:10 -07003569 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3570 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003571 }
Glenn Kastene7754022014-10-31 12:11:26 -07003572 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 }
Eric Laurent81784c32012-11-19 14:55:58 -08003574 }
3575
3576 // Finally let go of removed track(s), without the lock held
3577 // since we can't guarantee the destructors won't acquire that
3578 // same lock. This will also mutate and push a new fast mixer state.
3579 threadLoop_removeTracks(tracksToRemove);
3580 tracksToRemove.clear();
3581
3582 // FIXME I don't understand the need for this here;
3583 // it was in the original code but maybe the
3584 // assignment in saveOutputTracks() makes this unnecessary?
3585 clearOutputTracks();
3586
3587 // Effect chains will be actually deleted here if they were removed from
3588 // mEffectChains list during mixing or effects processing
3589 effectChains.clear();
3590
3591 // FIXME Note that the above .clear() is no longer necessary since effectChains
3592 // is now local to this block, but will keep it for now (at least until merge done).
3593 }
3594
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 threadLoop_exit();
3596
Eric Laurentcf817a22014-08-04 20:36:31 -07003597 if (!mStandby) {
3598 threadLoop_standby();
3599 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003600 }
3601
3602 releaseWakeLock();
3603
3604 ALOGV("Thread %p type %d exiting", this, mType);
3605 return false;
3606}
3607
Eric Laurentbfb1b832013-01-07 09:53:42 -08003608// removeTracks_l() must be called with ThreadBase::mLock held
3609void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3610{
3611 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003612 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613 for (size_t i=0 ; i<count ; i++) {
3614 const sp<Track>& track = tracksToRemove.itemAt(i);
3615 mActiveTracks.remove(track);
3616 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3617 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3618 if (chain != 0) {
3619 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3620 track->sessionId());
3621 chain->decActiveTrackCnt();
3622 }
3623 if (track->isTerminated()) {
3624 removeTrack_l(track);
3625 }
3626 }
3627 }
3628
3629}
Eric Laurent81784c32012-11-19 14:55:58 -08003630
Eric Laurentaccc1472013-09-20 09:36:34 -07003631status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3632{
3633 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003634 ExtendedTimestamp ets;
3635 status_t status = mNormalSink->getTimestamp(ets);
3636 if (status == NO_ERROR) {
3637 status = ets.getBestTimestamp(&timestamp);
3638 }
3639 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003640 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003641 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003642 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003643 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003644 timestamp.mPosition = (uint32_t)position64;
3645 return NO_ERROR;
3646 }
3647 }
3648 return INVALID_OPERATION;
3649}
Eric Laurent1c333e22014-05-20 10:48:17 -07003650
Eric Laurent054d9d32015-04-24 08:48:48 -07003651status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3652 audio_patch_handle_t *handle)
3653{
Andy Hungf60abce2016-08-26 11:37:54 -07003654 status_t status;
3655 if (property_get_bool("af.patch_park", false /* default_value */)) {
3656 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3657 // or if HAL does not properly lock against access.
3658 AutoPark<FastMixer> park(mFastMixer);
3659 status = PlaybackThread::createAudioPatch_l(patch, handle);
3660 } else {
3661 status = PlaybackThread::createAudioPatch_l(patch, handle);
3662 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003663 return status;
3664}
3665
Eric Laurent1c333e22014-05-20 10:48:17 -07003666status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3667 audio_patch_handle_t *handle)
3668{
3669 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003670
3671 // store new device and send to effects
3672 audio_devices_t type = AUDIO_DEVICE_NONE;
3673 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3674 type |= patch->sinks[i].ext.device.type;
3675 }
3676
3677#ifdef ADD_BATTERY_DATA
3678 // when changing the audio output device, call addBatteryData to notify
3679 // the change
3680 if (mOutDevice != type) {
3681 uint32_t params = 0;
3682 // check whether speaker is on
3683 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3684 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003685 }
3686
Eric Laurent054d9d32015-04-24 08:48:48 -07003687 audio_devices_t deviceWithoutSpeaker
3688 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3689 // check if any other device (except speaker) is on
3690 if (type & deviceWithoutSpeaker) {
3691 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3692 }
3693
3694 if (params != 0) {
3695 addBatteryData(params);
3696 }
3697 }
3698#endif
3699
3700 for (size_t i = 0; i < mEffectChains.size(); i++) {
3701 mEffectChains[i]->setDevice_l(type);
3702 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003703
3704 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3705 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3706 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003707 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003708 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003709
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003710 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003711 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3712 status = hwDevice->createAudioPatch(patch->num_sources,
3713 patch->sources,
3714 patch->num_sinks,
3715 patch->sinks,
3716 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003717 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003718 char *address;
3719 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3720 //FIXME: we only support address on first sink with HAL version < 3.0
3721 address = audio_device_address_to_parameter(
3722 patch->sinks[0].ext.device.type,
3723 patch->sinks[0].ext.device.address);
3724 } else {
3725 address = (char *)calloc(1, 1);
3726 }
3727 AudioParameter param = AudioParameter(String8(address));
3728 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003729 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003730 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003731 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003732 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003733 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003734 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003735 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3736 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003737 return status;
3738}
3739
Eric Laurent054d9d32015-04-24 08:48:48 -07003740status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3741{
Andy Hungf60abce2016-08-26 11:37:54 -07003742 status_t status;
3743 if (property_get_bool("af.patch_park", false /* default_value */)) {
3744 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3745 // or if HAL does not properly lock against access.
3746 AutoPark<FastMixer> park(mFastMixer);
3747 status = PlaybackThread::releaseAudioPatch_l(handle);
3748 } else {
3749 status = PlaybackThread::releaseAudioPatch_l(handle);
3750 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003751 return status;
3752}
3753
Eric Laurent1c333e22014-05-20 10:48:17 -07003754status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3755{
3756 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003757
3758 mOutDevice = AUDIO_DEVICE_NONE;
3759
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003760 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003761 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3762 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003763 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003764 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003765 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003766 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003767 }
3768 return status;
3769}
3770
Eric Laurent83b88082014-06-20 18:31:16 -07003771void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3772{
3773 Mutex::Autolock _l(mLock);
3774 mTracks.add(track);
3775}
3776
3777void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3778{
3779 Mutex::Autolock _l(mLock);
3780 destroyTrack_l(track);
3781}
3782
Mikhail Naganovdc769682018-05-04 15:34:08 -07003783void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003784{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003785 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003786 config->role = AUDIO_PORT_ROLE_SOURCE;
3787 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3788 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3789}
3790
Eric Laurent81784c32012-11-19 14:55:58 -08003791// ----------------------------------------------------------------------------
3792
3793AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003794 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3795 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003796 // mAudioMixer below
3797 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003798 mFastMixerFutex(0),
3799 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003800 // mOutputSink below
3801 // mPipeSink below
3802 // mNormalSink below
3803{
3804 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003805 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003806 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003807 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3808 mNormalFrameCount);
3809 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3810
Andy Hungfbfc3952015-01-15 13:33:51 -08003811 if (type == DUPLICATING) {
3812 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3813 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3814 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3815 return;
3816 }
Eric Laurent81784c32012-11-19 14:55:58 -08003817 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003818 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003819 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003820 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003821#if !LOG_NDEBUG
3822 ssize_t index =
3823#else
3824 (void)
3825#endif
3826 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003827 ALOG_ASSERT(index == 0);
3828
3829 // initialize fast mixer depending on configuration
3830 bool initFastMixer;
3831 switch (kUseFastMixer) {
3832 case FastMixer_Never:
3833 initFastMixer = false;
3834 break;
3835 case FastMixer_Always:
3836 initFastMixer = true;
3837 break;
3838 case FastMixer_Static:
3839 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003840 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3841 // where the period is less than an experimentally determined threshold that can be
3842 // scheduled reliably with CFS. However, the BT A2DP HAL is
3843 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3844 initFastMixer = mFrameCount < mNormalFrameCount
3845 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003846 break;
3847 }
Andy Hungfda69402017-02-15 14:33:12 -08003848 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3849 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3850 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003851 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003852 audio_format_t fastMixerFormat;
3853 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3854 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3855 } else {
3856 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3857 }
3858 if (mFormat != fastMixerFormat) {
3859 // change our Sink format to accept our intermediate precision
3860 mFormat = fastMixerFormat;
3861 free(mSinkBuffer);
3862 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3863 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3864 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3865 }
Eric Laurent81784c32012-11-19 14:55:58 -08003866
3867 // create a MonoPipe to connect our submix to FastMixer
3868 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003869#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003870 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003871#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003872 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003873 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003874 format.mFormat = fastMixerFormat;
3875 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3876
Eric Laurent81784c32012-11-19 14:55:58 -08003877 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3878 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3879 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3880 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3881 const NBAIO_Format offers[1] = {format};
3882 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003883#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003884 ssize_t index =
3885#else
3886 (void)
3887#endif
3888 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003889 ALOG_ASSERT(index == 0);
3890 monoPipe->setAvgFrames((mScreenState & 1) ?
3891 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3892 mPipeSink = monoPipe;
3893
Glenn Kasten46909e72013-02-26 09:20:22 -08003894#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003895 if (mTeeSinkOutputEnabled) {
3896 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003897 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3898 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003899 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003900 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003901 ALOG_ASSERT(index == 0);
3902 mTeeSink = teeSink;
3903 PipeReader *teeSource = new PipeReader(*teeSink);
3904 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003905 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003906 ALOG_ASSERT(index == 0);
3907 mTeeSource = teeSource;
3908 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003909#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003910
3911 // create fast mixer and configure it initially with just one fast track for our submix
3912 mFastMixer = new FastMixer();
3913 FastMixerStateQueue *sq = mFastMixer->sq();
3914#ifdef STATE_QUEUE_DUMP
3915 sq->setObserverDump(&mStateQueueObserverDump);
3916 sq->setMutatorDump(&mStateQueueMutatorDump);
3917#endif
3918 FastMixerState *state = sq->begin();
3919 FastTrack *fastTrack = &state->mFastTracks[0];
3920 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3921 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3922 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003923 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3924 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003925 fastTrack->mGeneration++;
3926 state->mFastTracksGen++;
3927 state->mTrackMask = 1;
3928 // fast mixer will use the HAL output sink
3929 state->mOutputSink = mOutputSink.get();
3930 state->mOutputSinkGen++;
3931 state->mFrameCount = mFrameCount;
3932 state->mCommand = FastMixerState::COLD_IDLE;
3933 // already done in constructor initialization list
3934 //mFastMixerFutex = 0;
3935 state->mColdFutexAddr = &mFastMixerFutex;
3936 state->mColdGen++;
3937 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003938#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003939 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003940#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003941 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3942 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003943 sq->end();
3944 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3945
3946 // start the fast mixer
3947 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3948 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003949 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003950 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003951
3952#ifdef AUDIO_WATCHDOG
3953 // create and start the watchdog
3954 mAudioWatchdog = new AudioWatchdog();
3955 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3956 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3957 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003958 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003959#endif
3960
Eric Laurent81784c32012-11-19 14:55:58 -08003961 }
3962
3963 switch (kUseFastMixer) {
3964 case FastMixer_Never:
3965 case FastMixer_Dynamic:
3966 mNormalSink = mOutputSink;
3967 break;
3968 case FastMixer_Always:
3969 mNormalSink = mPipeSink;
3970 break;
3971 case FastMixer_Static:
3972 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3973 break;
3974 }
3975}
3976
3977AudioFlinger::MixerThread::~MixerThread()
3978{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003979 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003980 FastMixerStateQueue *sq = mFastMixer->sq();
3981 FastMixerState *state = sq->begin();
3982 if (state->mCommand == FastMixerState::COLD_IDLE) {
3983 int32_t old = android_atomic_inc(&mFastMixerFutex);
3984 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003985 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003986 }
3987 }
3988 state->mCommand = FastMixerState::EXIT;
3989 sq->end();
3990 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3991 mFastMixer->join();
3992 // Though the fast mixer thread has exited, it's state queue is still valid.
3993 // We'll use that extract the final state which contains one remaining fast track
3994 // corresponding to our sub-mix.
3995 state = sq->begin();
3996 ALOG_ASSERT(state->mTrackMask == 1);
3997 FastTrack *fastTrack = &state->mFastTracks[0];
3998 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3999 delete fastTrack->mBufferProvider;
4000 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004001 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004002#ifdef AUDIO_WATCHDOG
4003 if (mAudioWatchdog != 0) {
4004 mAudioWatchdog->requestExit();
4005 mAudioWatchdog->requestExitAndWait();
4006 mAudioWatchdog.clear();
4007 }
4008#endif
4009 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004010 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004011 delete mAudioMixer;
4012}
4013
4014
4015uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4016{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004017 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004018 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4019 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4020 }
4021 return latency;
4022}
4023
4024
4025void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4026{
4027 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4028}
4029
Eric Laurentbfb1b832013-01-07 09:53:42 -08004030ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004031{
4032 // FIXME we should only do one push per cycle; confirm this is true
4033 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004034 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004035 FastMixerStateQueue *sq = mFastMixer->sq();
4036 FastMixerState *state = sq->begin();
4037 if (state->mCommand != FastMixerState::MIX_WRITE &&
4038 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4039 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004040
4041 // FIXME workaround for first HAL write being CPU bound on some devices
4042 ATRACE_BEGIN("write");
4043 mOutput->write((char *)mSinkBuffer, 0);
4044 ATRACE_END();
4045
Eric Laurent81784c32012-11-19 14:55:58 -08004046 int32_t old = android_atomic_inc(&mFastMixerFutex);
4047 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004048 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004049 }
4050#ifdef AUDIO_WATCHDOG
4051 if (mAudioWatchdog != 0) {
4052 mAudioWatchdog->resume();
4053 }
4054#endif
4055 }
4056 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004057#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004058 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004059 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004060#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004061 sq->end();
4062 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4063 if (kUseFastMixer == FastMixer_Dynamic) {
4064 mNormalSink = mPipeSink;
4065 }
4066 } else {
4067 sq->end(false /*didModify*/);
4068 }
4069 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004070 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004071}
4072
4073void AudioFlinger::MixerThread::threadLoop_standby()
4074{
4075 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004076 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004077 FastMixerStateQueue *sq = mFastMixer->sq();
4078 FastMixerState *state = sq->begin();
4079 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004080 // Report any frames trapped in the Monopipe
4081 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4082 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4083 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4084 "monoPipeWritten:%lld monoPipeLeft:%lld",
4085 (long long)mFramesWritten, (long long)mSuspendedFrames,
4086 (long long)mPipeSink->framesWritten(), pipeFrames);
4087 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4088
Eric Laurent81784c32012-11-19 14:55:58 -08004089 state->mCommand = FastMixerState::COLD_IDLE;
4090 state->mColdFutexAddr = &mFastMixerFutex;
4091 state->mColdGen++;
4092 mFastMixerFutex = 0;
4093 sq->end();
4094 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4095 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4096 if (kUseFastMixer == FastMixer_Dynamic) {
4097 mNormalSink = mOutputSink;
4098 }
4099#ifdef AUDIO_WATCHDOG
4100 if (mAudioWatchdog != 0) {
4101 mAudioWatchdog->pause();
4102 }
4103#endif
4104 } else {
4105 sq->end(false /*didModify*/);
4106 }
4107 }
4108 PlaybackThread::threadLoop_standby();
4109}
4110
Eric Laurentbfb1b832013-01-07 09:53:42 -08004111bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4112{
4113 return false;
4114}
4115
4116bool AudioFlinger::PlaybackThread::shouldStandby_l()
4117{
4118 return !mStandby;
4119}
4120
4121bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4122{
4123 Mutex::Autolock _l(mLock);
4124 return waitingAsyncCallback_l();
4125}
4126
Eric Laurent81784c32012-11-19 14:55:58 -08004127// shared by MIXER and DIRECT, overridden by DUPLICATING
4128void AudioFlinger::PlaybackThread::threadLoop_standby()
4129{
4130 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004131 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004132 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004133 // discard any pending drain or write ack by incrementing sequence
4134 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4135 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004136 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004137 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4138 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004139 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004140 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004141}
4142
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004143void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4144{
4145 ALOGV("signal playback thread");
4146 broadcast_l();
4147}
4148
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004149void AudioFlinger::PlaybackThread::onAsyncError()
4150{
4151 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4152 invalidateTracks((audio_stream_type_t)i);
4153 }
4154}
4155
Eric Laurent81784c32012-11-19 14:55:58 -08004156void AudioFlinger::MixerThread::threadLoop_mix()
4157{
Eric Laurent81784c32012-11-19 14:55:58 -08004158 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004159 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004160 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004161 // increase sleep time progressively when application underrun condition clears.
4162 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4163 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4164 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004165 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004166 sleepTimeShift--;
4167 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004168 mSleepTimeUs = 0;
4169 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004170 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004171
Eric Laurent81784c32012-11-19 14:55:58 -08004172}
4173
4174void AudioFlinger::MixerThread::threadLoop_sleepTime()
4175{
4176 // If no tracks are ready, sleep once for the duration of an output
4177 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004178 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004179 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004180 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4181 // Using the Monopipe availableToWrite, we estimate the
4182 // sleep time to retry for more data (before we underrun).
4183 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4184 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4185 const size_t pipeFrames = monoPipe->maxFrames();
4186 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4187 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4188 const size_t framesDelay = std::min(
4189 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4190 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4191 pipeFrames, framesLeft, framesDelay);
4192 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4193 } else {
4194 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4195 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4196 mSleepTimeUs = kMinThreadSleepTimeUs;
4197 }
4198 // reduce sleep time in case of consecutive application underruns to avoid
4199 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4200 // duration we would end up writing less data than needed by the audio HAL if
4201 // the condition persists.
4202 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4203 sleepTimeShift++;
4204 }
Eric Laurent81784c32012-11-19 14:55:58 -08004205 }
4206 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004207 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004208 }
4209 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004210 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4211 // before effects processing or output.
4212 if (mMixerBufferValid) {
4213 memset(mMixerBuffer, 0, mMixerBufferSize);
4214 } else {
4215 memset(mSinkBuffer, 0, mSinkBufferSize);
4216 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004217 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004218 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4219 "anticipated start");
4220 }
4221 // TODO add standby time extension fct of effect tail
4222}
4223
4224// prepareTracks_l() must be called with ThreadBase::mLock held
4225AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4226 Vector< sp<Track> > *tracksToRemove)
4227{
Andy Hung1bc088a2018-02-09 15:57:31 -08004228 // clean up deleted track names in AudioMixer before allocating new tracks
4229 (void)mTracks.processDeletedTrackNames([this](int name) {
4230 // for each name, destroy it in the AudioMixer
4231 if (mAudioMixer->exists(name)) {
4232 mAudioMixer->destroy(name);
4233 }
4234 });
4235 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004236
4237 mixer_state mixerStatus = MIXER_IDLE;
4238 // find out which tracks need to be processed
4239 size_t count = mActiveTracks.size();
4240 size_t mixedTracks = 0;
4241 size_t tracksWithEffect = 0;
4242 // counts only _active_ fast tracks
4243 size_t fastTracks = 0;
4244 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4245
4246 float masterVolume = mMasterVolume;
4247 bool masterMute = mMasterMute;
4248
4249 if (masterMute) {
4250 masterVolume = 0;
4251 }
4252 // Delegate master volume control to effect in output mix effect chain if needed
4253 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4254 if (chain != 0) {
4255 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4256 chain->setVolume_l(&v, &v);
4257 masterVolume = (float)((v + (1 << 23)) >> 24);
4258 chain.clear();
4259 }
4260
4261 // prepare a new state to push
4262 FastMixerStateQueue *sq = NULL;
4263 FastMixerState *state = NULL;
4264 bool didModify = false;
4265 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004266 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004267 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004268 sq = mFastMixer->sq();
4269 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004270 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004271 }
4272
Andy Hung69aed5f2014-02-25 17:24:40 -08004273 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004274 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004275
Andy Hungbd3b2b02018-05-21 10:53:11 -07004276 // DeferredOperations handles statistics after setting mixerStatus.
4277 class DeferredOperations {
4278 public:
4279 DeferredOperations(mixer_state *mixerStatus)
4280 : mMixerStatus(mixerStatus) { }
4281
4282 // when leaving scope, tally frames properly.
4283 ~DeferredOperations() {
4284 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4285 // because that is when the underrun occurs.
4286 // We do not distinguish between FastTracks and NormalTracks here.
4287 if (*mMixerStatus == MIXER_TRACKS_READY) {
4288 for (const auto &underrun : mUnderrunFrames) {
4289 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4290 underrun.second);
4291 }
4292 }
4293 }
4294
4295 // tallyUnderrunFrames() is called to update the track counters
4296 // with the number of underrun frames for a particular mixer period.
4297 // We defer tallying until we know the final mixer status.
4298 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4299 mUnderrunFrames.emplace_back(track, underrunFrames);
4300 }
4301
4302 private:
4303 const mixer_state * const mMixerStatus;
4304 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4305 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4306
Eric Laurent81784c32012-11-19 14:55:58 -08004307 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004308 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004309
4310 // this const just means the local variable doesn't change
4311 Track* const track = t.get();
4312
4313 // process fast tracks
4314 if (track->isFastTrack()) {
4315
4316 // It's theoretically possible (though unlikely) for a fast track to be created
4317 // and then removed within the same normal mix cycle. This is not a problem, as
4318 // the track never becomes active so it's fast mixer slot is never touched.
4319 // The converse, of removing an (active) track and then creating a new track
4320 // at the identical fast mixer slot within the same normal mix cycle,
4321 // is impossible because the slot isn't marked available until the end of each cycle.
4322 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004323 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004324 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4325 FastTrack *fastTrack = &state->mFastTracks[j];
4326
4327 // Determine whether the track is currently in underrun condition,
4328 // and whether it had a recent underrun.
4329 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4330 FastTrackUnderruns underruns = ftDump->mUnderruns;
4331 uint32_t recentFull = (underruns.mBitFields.mFull -
4332 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4333 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4334 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4335 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4336 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4337 uint32_t recentUnderruns = recentPartial + recentEmpty;
4338 track->mObservedUnderruns = underruns;
4339 // don't count underruns that occur while stopping or pausing
4340 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004341 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004342 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4343 recentUnderruns > 0) {
4344 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004345 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004346 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004347 // Immediately account for FastTrack underruns.
4348 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004349
4350 // This is similar to the state machine for normal tracks,
4351 // with a few modifications for fast tracks.
4352 bool isActive = true;
4353 switch (track->mState) {
4354 case TrackBase::STOPPING_1:
4355 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004356 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004357 track->mState = TrackBase::STOPPING_2;
4358 }
4359 break;
4360 case TrackBase::PAUSING:
4361 // ramp down is not yet implemented
4362 track->setPaused();
4363 break;
4364 case TrackBase::RESUMING:
4365 // ramp up is not yet implemented
4366 track->mState = TrackBase::ACTIVE;
4367 break;
4368 case TrackBase::ACTIVE:
4369 if (recentFull > 0 || recentPartial > 0) {
4370 // track has provided at least some frames recently: reset retry count
4371 track->mRetryCount = kMaxTrackRetries;
4372 }
4373 if (recentUnderruns == 0) {
4374 // no recent underruns: stay active
4375 break;
4376 }
4377 // there has recently been an underrun of some kind
4378 if (track->sharedBuffer() == 0) {
4379 // were any of the recent underruns "empty" (no frames available)?
4380 if (recentEmpty == 0) {
4381 // no, then ignore the partial underruns as they are allowed indefinitely
4382 break;
4383 }
4384 // there has recently been an "empty" underrun: decrement the retry counter
4385 if (--(track->mRetryCount) > 0) {
4386 break;
4387 }
4388 // indicate to client process that the track was disabled because of underrun;
4389 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004390 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004391 // remove from active list, but state remains ACTIVE [confusing but true]
4392 isActive = false;
4393 break;
4394 }
4395 // fall through
4396 case TrackBase::STOPPING_2:
4397 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004398 case TrackBase::STOPPED:
4399 case TrackBase::FLUSHED: // flush() while active
4400 // Check for presentation complete if track is inactive
4401 // We have consumed all the buffers of this track.
4402 // This would be incomplete if we auto-paused on underrun
4403 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004404 uint32_t latency = 0;
4405 status_t result = mOutput->stream->getLatency(&latency);
4406 ALOGE_IF(result != OK,
4407 "Error when retrieving output stream latency: %d", result);
4408 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004409 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004410 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4411 // track stays in active list until presentation is complete
4412 break;
4413 }
4414 }
4415 if (track->isStopping_2()) {
4416 track->mState = TrackBase::STOPPED;
4417 }
4418 if (track->isStopped()) {
4419 // Can't reset directly, as fast mixer is still polling this track
4420 // track->reset();
4421 // So instead mark this track as needing to be reset after push with ack
4422 resetMask |= 1 << i;
4423 }
4424 isActive = false;
4425 break;
4426 case TrackBase::IDLE:
4427 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004428 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004429 }
4430
4431 if (isActive) {
4432 // was it previously inactive?
4433 if (!(state->mTrackMask & (1 << j))) {
4434 ExtendedAudioBufferProvider *eabp = track;
4435 VolumeProvider *vp = track;
4436 fastTrack->mBufferProvider = eabp;
4437 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004438 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004439 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004440 fastTrack->mGeneration++;
4441 state->mTrackMask |= 1 << j;
4442 didModify = true;
4443 // no acknowledgement required for newly active tracks
4444 }
Kevin Rocard12381092018-04-11 09:19:59 -07004445 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004446 // cache the combined master volume and stream type volume for fast mixer; this
4447 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004448 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004449 proxy->framesReleased()).first;
4450 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004451 * mStreamTypes[track->streamType()].volume
4452 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004453 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004454 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4455 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4456 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4457 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004458 ++fastTracks;
4459 } else {
4460 // was it previously active?
4461 if (state->mTrackMask & (1 << j)) {
4462 fastTrack->mBufferProvider = NULL;
4463 fastTrack->mGeneration++;
4464 state->mTrackMask &= ~(1 << j);
4465 didModify = true;
4466 // If any fast tracks were removed, we must wait for acknowledgement
4467 // because we're about to decrement the last sp<> on those tracks.
4468 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4469 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004470 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4471 // AudioTrack may start (which may not be with a start() but with a write()
4472 // after underrun) and immediately paused or released. In that case the
4473 // FastTrack state hasn't had time to update.
4474 // TODO Remove the ALOGW when this theory is confirmed.
4475 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004476 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4477 j, track->mState, state->mTrackMask, recentUnderruns,
4478 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004479 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004480 }
4481 tracksToRemove->add(track);
4482 // Avoids a misleading display in dumpsys
4483 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4484 }
4485 continue;
4486 }
4487
4488 { // local variable scope to avoid goto warning
4489
4490 audio_track_cblk_t* cblk = track->cblk();
4491
4492 // The first time a track is added we wait
4493 // for all its buffers to be filled before processing it
4494 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004495
4496 // if an active track doesn't exist in the AudioMixer, create it.
4497 if (!mAudioMixer->exists(name)) {
4498 status_t status = mAudioMixer->create(
4499 name,
4500 track->mChannelMask,
4501 track->mFormat,
4502 track->mSessionId);
4503 if (status != OK) {
4504 ALOGW("%s: cannot create track name"
4505 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4506 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4507 tracksToRemove->add(track);
4508 track->invalidate(); // consider it dead.
4509 continue;
4510 }
4511 }
4512
Eric Laurent81784c32012-11-19 14:55:58 -08004513 // make sure that we have enough frames to mix one full buffer.
4514 // enforce this condition only once to enable draining the buffer in case the client
4515 // app does not call stop() and relies on underrun to stop:
4516 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4517 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004518 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004519 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004520 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004521
4522 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004523 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004524 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4525 // add frames already consumed but not yet released by the resampler
4526 // because mAudioTrackServerProxy->framesReady() will include these frames
4527 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4528
Eric Laurent81784c32012-11-19 14:55:58 -08004529 uint32_t minFrames = 1;
4530 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4531 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004532 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004533 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004534
4535 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004536 if (ATRACE_ENABLED()) {
4537 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004538 std::string traceName("nRdy");
4539 traceName += std::to_string(track->name());
4540 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004541 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004542 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004543 !track->isPaused() && !track->isTerminated())
4544 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004545 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004546
4547 mixedTracks++;
4548
Andy Hung69aed5f2014-02-25 17:24:40 -08004549 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4550 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004551 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004552 if (track->mainBuffer() != mSinkBuffer &&
4553 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004554 if (mEffectBufferEnabled) {
4555 mEffectBufferValid = true; // Later can set directly.
4556 }
Eric Laurent81784c32012-11-19 14:55:58 -08004557 chain = getEffectChain_l(track->sessionId());
4558 // Delegate volume control to effect in track effect chain if needed
4559 if (chain != 0) {
4560 tracksWithEffect++;
4561 } else {
4562 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4563 "session %d",
4564 name, track->sessionId());
4565 }
4566 }
4567
4568
4569 int param = AudioMixer::VOLUME;
4570 if (track->mFillingUpStatus == Track::FS_FILLED) {
4571 // no ramp for the first volume setting
4572 track->mFillingUpStatus = Track::FS_ACTIVE;
4573 if (track->mState == TrackBase::RESUMING) {
4574 track->mState = TrackBase::ACTIVE;
4575 param = AudioMixer::RAMP_VOLUME;
4576 }
4577 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004578 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004579 // FIXME should not make a decision based on mServer
4580 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004581 // If the track is stopped before the first frame was mixed,
4582 // do not apply ramp
4583 param = AudioMixer::RAMP_VOLUME;
4584 }
4585
4586 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004587 uint32_t vl, vr; // in U8.24 integer format
4588 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004589 // read original volumes with volume control
4590 float typeVolume = mStreamTypes[track->streamType()].volume;
4591 float v = masterVolume * typeVolume;
4592
Glenn Kastene4756fe2012-11-29 13:38:14 -08004593 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004594 vl = vr = 0;
4595 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004596 if (track->isPausing()) {
4597 track->setPaused();
4598 }
4599 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004600 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004601 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004602 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4603 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004604 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004605 if (vlf > GAIN_FLOAT_UNITY) {
4606 ALOGV("Track left volume out of range: %.3g", vlf);
4607 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004608 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004609 if (vrf > GAIN_FLOAT_UNITY) {
4610 ALOGV("Track right volume out of range: %.3g", vrf);
4611 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004612 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004613 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004614 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004615 // now apply the master volume and stream type volume and shaper volume
4616 vlf *= v * vh;
4617 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004618 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004619 // then derive vl and vr as U8.24 versions for the effect chain
4620 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4621 vl = (uint32_t) (scaleto8_24 * vlf);
4622 vr = (uint32_t) (scaleto8_24 * vrf);
4623 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004624 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004625 // send level comes from shared memory and so may be corrupt
4626 if (sendLevel > MAX_GAIN_INT) {
4627 ALOGV("Track send level out of range: %04X", sendLevel);
4628 sendLevel = MAX_GAIN_INT;
4629 }
Andy Hung6be49402014-05-30 10:42:03 -07004630 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4631 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004632 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004633
Kevin Rocard12381092018-04-11 09:19:59 -07004634 track->setFinalVolume((vrf + vlf) / 2.f);
4635
Eric Laurent81784c32012-11-19 14:55:58 -08004636 // Delegate volume control to effect in track effect chain if needed
4637 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4638 // Do not ramp volume if volume is controlled by effect
4639 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004640 // Update remaining floating point volume levels
4641 vlf = (float)vl / (1 << 24);
4642 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004643 track->mHasVolumeController = true;
4644 } else {
4645 // force no volume ramp when volume controller was just disabled or removed
4646 // from effect chain to avoid volume spike
4647 if (track->mHasVolumeController) {
4648 param = AudioMixer::VOLUME;
4649 }
4650 track->mHasVolumeController = false;
4651 }
4652
Eric Laurent7c29ec92017-09-20 17:54:22 -07004653 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4654 // still applied by the mixer.
4655 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4656 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4657 if (v != mLeftVolFloat) {
4658 status_t result = mOutput->stream->setVolume(v, v);
4659 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4660 if (result == OK) {
4661 mLeftVolFloat = v;
4662 }
4663 }
4664 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4665 // remove stream volume contribution from software volume.
4666 if (v != 0.0f && mLeftVolFloat == v) {
4667 vlf = min(1.0f, vlf / v);
4668 vrf = min(1.0f, vrf / v);
4669 vaf = min(1.0f, vaf / v);
4670 }
4671 }
Eric Laurent81784c32012-11-19 14:55:58 -08004672 // XXX: these things DON'T need to be done each time
4673 mAudioMixer->setBufferProvider(name, track);
4674 mAudioMixer->enable(name);
4675
Andy Hung6be49402014-05-30 10:42:03 -07004676 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4677 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4678 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004679 mAudioMixer->setParameter(
4680 name,
4681 AudioMixer::TRACK,
4682 AudioMixer::FORMAT, (void *)track->format());
4683 mAudioMixer->setParameter(
4684 name,
4685 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004686 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004687 mAudioMixer->setParameter(
4688 name,
4689 AudioMixer::TRACK,
4690 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004691 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004692 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004693 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004694 if (reqSampleRate == 0) {
4695 reqSampleRate = mSampleRate;
4696 } else if (reqSampleRate > maxSampleRate) {
4697 reqSampleRate = maxSampleRate;
4698 }
Eric Laurent81784c32012-11-19 14:55:58 -08004699 mAudioMixer->setParameter(
4700 name,
4701 AudioMixer::RESAMPLE,
4702 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004703 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004704
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004705 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004706 mAudioMixer->setParameter(
4707 name,
4708 AudioMixer::TIMESTRETCH,
4709 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004710 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004711
Andy Hung69aed5f2014-02-25 17:24:40 -08004712 /*
4713 * Select the appropriate output buffer for the track.
4714 *
Andy Hung98ef9782014-03-04 14:46:50 -08004715 * Tracks with effects go into their own effects chain buffer
4716 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004717 *
4718 * Other tracks can use mMixerBuffer for higher precision
4719 * channel accumulation. If this buffer is enabled
4720 * (mMixerBufferEnabled true), then selected tracks will accumulate
4721 * into it.
4722 *
4723 */
4724 if (mMixerBufferEnabled
4725 && (track->mainBuffer() == mSinkBuffer
4726 || track->mainBuffer() == mMixerBuffer)) {
4727 mAudioMixer->setParameter(
4728 name,
4729 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004730 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004731 mAudioMixer->setParameter(
4732 name,
4733 AudioMixer::TRACK,
4734 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4735 // TODO: override track->mainBuffer()?
4736 mMixerBufferValid = true;
4737 } else {
4738 mAudioMixer->setParameter(
4739 name,
4740 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004741 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004742 mAudioMixer->setParameter(
4743 name,
4744 AudioMixer::TRACK,
4745 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4746 }
Eric Laurent81784c32012-11-19 14:55:58 -08004747 mAudioMixer->setParameter(
4748 name,
4749 AudioMixer::TRACK,
4750 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4751
4752 // reset retry count
4753 track->mRetryCount = kMaxTrackRetries;
4754
4755 // If one track is ready, set the mixer ready if:
4756 // - the mixer was not ready during previous round OR
4757 // - no other track is not ready
4758 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4759 mixerStatus != MIXER_TRACKS_ENABLED) {
4760 mixerStatus = MIXER_TRACKS_READY;
4761 }
4762 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004763 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004764 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004765 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4766 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004767 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004768 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004769 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004770
Eric Laurent81784c32012-11-19 14:55:58 -08004771 // clear effect chain input buffer if an active track underruns to avoid sending
4772 // previous audio buffer again to effects
4773 chain = getEffectChain_l(track->sessionId());
4774 if (chain != 0) {
4775 chain->clearInputBuffer();
4776 }
4777
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004778 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004779 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4780 track->isStopped() || track->isPaused()) {
4781 // We have consumed all the buffers of this track.
4782 // Remove it from the list of active tracks.
4783 // TODO: use actual buffer filling status instead of latency when available from
4784 // audio HAL
4785 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004786 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004787 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4788 if (track->isStopped()) {
4789 track->reset();
4790 }
4791 tracksToRemove->add(track);
4792 }
4793 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004794 // No buffers for this track. Give it a few chances to
4795 // fill a buffer, then remove it from active list.
4796 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004797 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004798 tracksToRemove->add(track);
4799 // indicate to client process that the track was disabled because of underrun;
4800 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004801 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004802 // If one track is not ready, mark the mixer also not ready if:
4803 // - the mixer was ready during previous round OR
4804 // - no other track is ready
4805 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4806 mixerStatus != MIXER_TRACKS_READY) {
4807 mixerStatus = MIXER_TRACKS_ENABLED;
4808 }
4809 }
4810 mAudioMixer->disable(name);
4811 }
4812
4813 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004814
4815 }
4816
4817 // Push the new FastMixer state if necessary
4818 bool pauseAudioWatchdog = false;
4819 if (didModify) {
4820 state->mFastTracksGen++;
4821 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4822 if (kUseFastMixer == FastMixer_Dynamic &&
4823 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4824 state->mCommand = FastMixerState::COLD_IDLE;
4825 state->mColdFutexAddr = &mFastMixerFutex;
4826 state->mColdGen++;
4827 mFastMixerFutex = 0;
4828 if (kUseFastMixer == FastMixer_Dynamic) {
4829 mNormalSink = mOutputSink;
4830 }
4831 // If we go into cold idle, need to wait for acknowledgement
4832 // so that fast mixer stops doing I/O.
4833 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4834 pauseAudioWatchdog = true;
4835 }
Eric Laurent81784c32012-11-19 14:55:58 -08004836 }
4837 if (sq != NULL) {
4838 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004839 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4840 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4841 // when bringing the output sink into standby.)
4842 //
4843 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4844 //
4845 // This occurs with BT suspend when we idle the FastMixer with
4846 // active tracks, which may be added or removed.
4847 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004848 }
4849#ifdef AUDIO_WATCHDOG
4850 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4851 mAudioWatchdog->pause();
4852 }
4853#endif
4854
4855 // Now perform the deferred reset on fast tracks that have stopped
4856 while (resetMask != 0) {
4857 size_t i = __builtin_ctz(resetMask);
4858 ALOG_ASSERT(i < count);
4859 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004860 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004861 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4862 track->reset();
4863 }
4864
Andy Hung80d03d22018-04-10 10:32:11 -07004865 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4866 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4867 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4868 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4869 // See also the implementation of destroyTrack_l().
4870 for (const auto &track : *tracksToRemove) {
4871 const int name = track->name();
4872 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4873 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4874 }
4875 }
4876
Eric Laurent81784c32012-11-19 14:55:58 -08004877 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004879
Eric Laurent97d547d2014-09-02 14:45:53 -07004880 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4881 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004882 }
4883
4884 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004885 // as long as there are effects we should clear the effects buffer, to avoid
4886 // passing a non-clean buffer to the effect chain
4887 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004888 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004889 // sink or mix buffer must be cleared if all tracks are connected to an
4890 // effect chain as in this case the mixer will not write to the sink or mix buffer
4891 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004892 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4893 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004894 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004895 if (mMixerBufferValid) {
4896 memset(mMixerBuffer, 0, mMixerBufferSize);
4897 // TODO: In testing, mSinkBuffer below need not be cleared because
4898 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4899 // after mixing.
4900 //
4901 // To enforce this guarantee:
4902 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4903 // (mixedTracks == 0 && fastTracks > 0))
4904 // must imply MIXER_TRACKS_READY.
4905 // Later, we may clear buffers regardless, and skip much of this logic.
4906 }
Andy Hung98ef9782014-03-04 14:46:50 -08004907 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004908 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004909 }
4910
4911 // if any fast tracks, then status is ready
4912 mMixerStatusIgnoringFastTracks = mixerStatus;
4913 if (fastTracks > 0) {
4914 mixerStatus = MIXER_TRACKS_READY;
4915 }
4916 return mixerStatus;
4917}
4918
Eric Laurentad7dd962016-09-22 12:38:37 -07004919// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004920uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004921{
4922 uint32_t trackCount = 0;
4923 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004924 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004925 trackCount++;
4926 }
4927 }
4928 return trackCount;
4929}
4930
Andy Hung1bc088a2018-02-09 15:57:31 -08004931// isTrackAllowed_l() must be called with ThreadBase::mLock held
4932bool AudioFlinger::MixerThread::isTrackAllowed_l(
4933 audio_channel_mask_t channelMask, audio_format_t format,
4934 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004935{
Andy Hung1bc088a2018-02-09 15:57:31 -08004936 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4937 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004938 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004939 // Check validity as we don't call AudioMixer::create() here.
4940 if (!AudioMixer::isValidFormat(format)) {
4941 ALOGW("%s: invalid format: %#x", __func__, format);
4942 return false;
4943 }
4944 if (!AudioMixer::isValidChannelMask(channelMask)) {
4945 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4946 return false;
4947 }
4948 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004949}
4950
Eric Laurent10351942014-05-08 18:49:52 -07004951// checkForNewParameter_l() must be called with ThreadBase::mLock held
4952bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4953 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004954{
Eric Laurent81784c32012-11-19 14:55:58 -08004955 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004956 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004957
Eric Laurent10351942014-05-08 18:49:52 -07004958 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004959
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004960 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004961
Eric Laurent10351942014-05-08 18:49:52 -07004962 AudioParameter param = AudioParameter(keyValuePair);
4963 int value;
4964 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4965 reconfig = true;
4966 }
4967 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004968 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004969 status = BAD_VALUE;
4970 } else {
4971 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004972 reconfig = true;
4973 }
Eric Laurent10351942014-05-08 18:49:52 -07004974 }
4975 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004976 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004977 status = BAD_VALUE;
4978 } else {
4979 // no need to save value, since it's constant
4980 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004981 }
Eric Laurent10351942014-05-08 18:49:52 -07004982 }
4983 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4984 // do not accept frame count changes if tracks are open as the track buffer
4985 // size depends on frame count and correct behavior would not be guaranteed
4986 // if frame count is changed after track creation
4987 if (!mTracks.isEmpty()) {
4988 status = INVALID_OPERATION;
4989 } else {
4990 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004991 }
Eric Laurent10351942014-05-08 18:49:52 -07004992 }
4993 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004994#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004995 // when changing the audio output device, call addBatteryData to notify
4996 // the change
4997 if (mOutDevice != value) {
4998 uint32_t params = 0;
4999 // check whether speaker is on
5000 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5001 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005002 }
Eric Laurent10351942014-05-08 18:49:52 -07005003
5004 audio_devices_t deviceWithoutSpeaker
5005 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5006 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005007 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005008 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5009 }
5010
5011 if (params != 0) {
5012 addBatteryData(params);
5013 }
5014 }
Eric Laurent81784c32012-11-19 14:55:58 -08005015#endif
5016
Eric Laurent10351942014-05-08 18:49:52 -07005017 // forward device change to effects that have requested to be
5018 // aware of attached audio device.
5019 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005020 a2dpDeviceChanged =
5021 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005022 mOutDevice = value;
5023 for (size_t i = 0; i < mEffectChains.size(); i++) {
5024 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005025 }
5026 }
Eric Laurent10351942014-05-08 18:49:52 -07005027 }
Eric Laurent81784c32012-11-19 14:55:58 -08005028
Eric Laurent10351942014-05-08 18:49:52 -07005029 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005030 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005031 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005032 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005033 mStandby = true;
5034 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005035 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005036 }
Eric Laurent10351942014-05-08 18:49:52 -07005037 if (status == NO_ERROR && reconfig) {
5038 readOutputParameters_l();
5039 delete mAudioMixer;
5040 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005041 for (const auto &track : mTracks) {
5042 const int name = track->name();
5043 status_t status = mAudioMixer->create(
5044 name,
5045 track->mChannelMask,
5046 track->mFormat,
5047 track->mSessionId);
5048 ALOGW_IF(status != NO_ERROR,
5049 "%s: cannot create track name"
5050 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5051 __func__,
5052 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005053 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005054 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005055 }
Eric Laurent81784c32012-11-19 14:55:58 -08005056 }
5057
Eric Laurent42537be2016-01-08 17:16:42 -08005058 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005059}
5060
5061
5062void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5063{
Eric Laurent81784c32012-11-19 14:55:58 -08005064 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005065 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005066 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005067 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08005068
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005069 if (hasFastMixer()) {
5070 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5071
5072 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5073 // while we are dumping it. It may be inconsistent, but it won't mutate!
5074 // This is a large object so we place it on the heap.
5075 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5076 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
5077 copy->dump(fd);
5078 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08005079
5080#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005081 // Similar for state queue
5082 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5083 observerCopy.dump(fd);
5084 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5085 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005086#endif
5087
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005088#ifdef AUDIO_WATCHDOG
5089 if (mAudioWatchdog != 0) {
5090 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5091 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5092 wdCopy.dump(fd);
5093 }
5094#endif
5095
5096 } else {
5097 dprintf(fd, " No FastMixer\n");
5098 }
5099
Glenn Kasten46909e72013-02-26 09:20:22 -08005100#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08005101 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07005102 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08005103#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005104
Eric Laurent81784c32012-11-19 14:55:58 -08005105}
5106
5107uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5108{
5109 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5110}
5111
5112uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5113{
5114 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5115}
5116
5117void AudioFlinger::MixerThread::cacheParameters_l()
5118{
5119 PlaybackThread::cacheParameters_l();
5120
5121 // FIXME: Relaxed timing because of a certain device that can't meet latency
5122 // Should be reduced to 2x after the vendor fixes the driver issue
5123 // increase threshold again due to low power audio mode. The way this warning
5124 // threshold is calculated and its usefulness should be reconsidered anyway.
5125 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5126}
5127
5128// ----------------------------------------------------------------------------
5129
5130AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005131 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5132 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005133{
5134}
5135
Eric Laurentbfb1b832013-01-07 09:53:42 -08005136AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5137 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005138 ThreadBase::type_t type, bool systemReady)
5139 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005140 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005141{
5142}
5143
Eric Laurent81784c32012-11-19 14:55:58 -08005144AudioFlinger::DirectOutputThread::~DirectOutputThread()
5145{
5146}
5147
Eric Laurent5850c4c2016-11-10 13:04:31 -08005148void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005149{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005150 float left, right;
5151
5152 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5153 left = right = 0;
5154 } else {
5155 float typeVolume = mStreamTypes[track->streamType()].volume;
5156 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005157 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005158
Andy Hung10cbff12017-02-21 17:30:14 -08005159 // Get volumeshaper scaling
5160 std::pair<float /* volume */, bool /* active */>
5161 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005162 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005163 v *= vh.first;
5164 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005165
Glenn Kastenc56f3422014-03-21 17:53:17 -07005166 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5167 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5168 if (left > GAIN_FLOAT_UNITY) {
5169 left = GAIN_FLOAT_UNITY;
5170 }
5171 left *= v;
5172 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5173 if (right > GAIN_FLOAT_UNITY) {
5174 right = GAIN_FLOAT_UNITY;
5175 }
5176 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005177 }
5178
5179 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005180 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005181 if (left != mLeftVolFloat || right != mRightVolFloat) {
5182 mLeftVolFloat = left;
5183 mRightVolFloat = right;
5184
5185 // Convert volumes from float to 8.24
5186 uint32_t vl = (uint32_t)(left * (1 << 24));
5187 uint32_t vr = (uint32_t)(right * (1 << 24));
5188
5189 // Delegate volume control to effect in track effect chain if needed
5190 // only one effect chain can be present on DirectOutputThread, so if
5191 // there is one, the track is connected to it
5192 if (!mEffectChains.isEmpty()) {
5193 mEffectChains[0]->setVolume_l(&vl, &vr);
5194 left = (float)vl / (1 << 24);
5195 right = (float)vr / (1 << 24);
5196 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005197 status_t result = mOutput->stream->setVolume(left, right);
5198 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005199 }
5200 }
5201}
5202
Phil Burk43b4dcc2015-06-09 16:53:44 -07005203void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5204{
5205 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005206 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005207
Eric Laurent0f0631e2015-07-06 18:01:25 -07005208 if (previousTrack != 0 && latestTrack != 0) {
5209 if (mType == DIRECT) {
5210 if (previousTrack.get() != latestTrack.get()) {
5211 mFlushPending = true;
5212 }
5213 } else /* mType == OFFLOAD */ {
5214 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5215 mFlushPending = true;
5216 }
5217 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005218 }
5219 PlaybackThread::onAddNewTrack_l();
5220}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005221
Eric Laurent81784c32012-11-19 14:55:58 -08005222AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5223 Vector< sp<Track> > *tracksToRemove
5224)
5225{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005226 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005227 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005228 bool doHwPause = false;
5229 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005230
5231 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005232 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005233 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005234 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005235 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005236 continue;
5237 }
5238
Eric Laurent5850c4c2016-11-10 13:04:31 -08005239 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005240#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005241 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005242#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005243 // Only consider last track started for volume and mixer state control.
5244 // In theory an older track could underrun and restart after the new one starts
5245 // but as we only care about the transition phase between two tracks on a
5246 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005247 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005248 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005249
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005250 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005251 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005252 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005253 doHwPause = true;
5254 mHwPaused = true;
5255 }
5256 tracksToRemove->add(track);
5257 } else if (track->isFlushPending()) {
5258 track->flushAck();
5259 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005260 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005261 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005262 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005263 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005264 if (last) {
5265 mLeftVolFloat = mRightVolFloat = -1.0;
5266 if (mHwPaused) {
5267 doHwResume = true;
5268 mHwPaused = false;
5269 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005270 }
5271 }
5272
Eric Laurent81784c32012-11-19 14:55:58 -08005273 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005274 // for all its buffers to be filled before processing it.
5275 // Allow draining the buffer in case the client
5276 // app does not call stop() and relies on underrun to stop:
5277 // hence the test on (track->mRetryCount > 1).
5278 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005279 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005280 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005281 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005282 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005283 minFrames = mNormalFrameCount;
5284 } else {
5285 minFrames = 1;
5286 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005287
Eric Laurentab5cdba2014-06-09 17:22:27 -07005288 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5289 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005290 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005291 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005292
5293 if (track->mFillingUpStatus == Track::FS_FILLED) {
5294 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005295 if (last) {
5296 // make sure processVolume_l() will apply new volume even if 0
5297 mLeftVolFloat = mRightVolFloat = -1.0;
5298 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005299 if (!mHwSupportsPause) {
5300 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005301 }
5302 }
5303
5304 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005305 processVolume_l(track, last);
5306 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005307 sp<Track> previousTrack = mPreviousTrack.promote();
5308 if (previousTrack != 0) {
5309 if (track != previousTrack.get()) {
5310 // Flush any data still being written from last track
5311 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005312 // Invalidate previous track to force a seek when resuming.
5313 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005314 }
5315 }
5316 mPreviousTrack = track;
5317
Eric Laurentd595b7c2013-04-03 17:27:56 -07005318 // reset retry count
5319 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005320 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005321 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005322 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005323 doHwResume = true;
5324 mHwPaused = false;
5325 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005326 }
Eric Laurent81784c32012-11-19 14:55:58 -08005327 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005328 // clear effect chain input buffer if the last active track started underruns
5329 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005330 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005331 mEffectChains[0]->clearInputBuffer();
5332 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005333 if (track->isStopping_1()) {
5334 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005335 if (last && mHwPaused) {
5336 doHwResume = true;
5337 mHwPaused = false;
5338 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005339 }
5340 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5341 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005342 // We have consumed all the buffers of this track.
5343 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005344 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005345 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005346 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5347 } else {
5348 audioHALFrames = 0;
5349 }
5350
Andy Hung818e7a32016-02-16 18:08:07 -08005351 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005352 if (mStandby || !last ||
5353 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005354 if (track->isStopping_2()) {
5355 track->mState = TrackBase::STOPPED;
5356 }
Eric Laurent81784c32012-11-19 14:55:58 -08005357 if (track->isStopped()) {
5358 track->reset();
5359 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005360 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005361 }
5362 } else {
5363 // No buffers for this track. Give it a few chances to
5364 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005365 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005366 if (--(track->mRetryCount) <= 0) {
5367 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005368 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005369 // indicate to client process that the track was disabled because of underrun;
5370 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005371 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005373 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5374 "minFrames = %u, mFormat = %#x",
5375 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005376 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005377 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005378 doHwPause = true;
5379 mHwPaused = true;
5380 }
Eric Laurent81784c32012-11-19 14:55:58 -08005381 }
5382 }
5383 }
5384 }
5385
Eric Laurentd1f69b02014-12-15 14:33:13 -08005386 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005387 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005388 for (size_t i = 0; i < mTracks.size(); i++) {
5389 if (mTracks[i]->isFlushPending()) {
5390 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005391 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005392 }
5393 }
5394 }
5395
5396 // make sure the pause/flush/resume sequence is executed in the right order.
5397 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5398 // before flush and then resume HW. This can happen in case of pause/flush/resume
5399 // if resume is received before pause is executed.
5400 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005401 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005402 status_t result = mOutput->stream->pause();
5403 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005404 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005405 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005406 flushHw_l();
5407 }
5408 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005409 status_t result = mOutput->stream->resume();
5410 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005411 }
Eric Laurent81784c32012-11-19 14:55:58 -08005412 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005413 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005414
5415 return mixerStatus;
5416}
5417
5418void AudioFlinger::DirectOutputThread::threadLoop_mix()
5419{
Eric Laurent81784c32012-11-19 14:55:58 -08005420 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005421 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005422 // output audio to hardware
5423 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005424 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005425 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005426 status_t status = mActiveTrack->getNextBuffer(&buffer);
5427 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005428 // no need to pad with 0 for compressed audio
5429 if (audio_has_proportional_frames(mFormat)) {
5430 memset(curBuf, 0, frameCount * mFrameSize);
5431 }
Eric Laurent81784c32012-11-19 14:55:58 -08005432 break;
5433 }
5434 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5435 frameCount -= buffer.frameCount;
5436 curBuf += buffer.frameCount * mFrameSize;
5437 mActiveTrack->releaseBuffer(&buffer);
5438 }
Andy Hung2098f272014-02-27 14:00:06 -08005439 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005440 mSleepTimeUs = 0;
5441 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005442 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005443}
5444
5445void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5446{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005447 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005448 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005449 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005450 return;
5451 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005452 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005453 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005454 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005455 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005456 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005457 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005458 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005459 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005460 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005461 }
5462}
5463
Eric Laurentd1f69b02014-12-15 14:33:13 -08005464void AudioFlinger::DirectOutputThread::threadLoop_exit()
5465{
5466 {
5467 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005468 for (size_t i = 0; i < mTracks.size(); i++) {
5469 if (mTracks[i]->isFlushPending()) {
5470 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005471 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005472 }
5473 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005474 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005475 flushHw_l();
5476 }
5477 }
5478 PlaybackThread::threadLoop_exit();
5479}
5480
5481// must be called with thread mutex locked
5482bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5483{
5484 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005485 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005486
vivek mehta9cd7ad12016-03-17 00:18:29 -07005487 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5488 return !mStandby;
5489 }
5490
Eric Laurentd1f69b02014-12-15 14:33:13 -08005491 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5492 // after a timeout and we will enter standby then.
5493 if (mTracks.size() > 0) {
5494 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005495 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5496 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005497 }
5498
Eric Laurent5cff4032015-05-26 13:49:58 -07005499 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005500}
5501
Eric Laurent10351942014-05-08 18:49:52 -07005502// checkForNewParameter_l() must be called with ThreadBase::mLock held
5503bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5504 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005505{
5506 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005507 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005508
Eric Laurent10351942014-05-08 18:49:52 -07005509 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005510
Eric Laurent10351942014-05-08 18:49:52 -07005511 AudioParameter param = AudioParameter(keyValuePair);
5512 int value;
5513 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5514 // forward device change to effects that have requested to be
5515 // aware of attached audio device.
5516 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005517 a2dpDeviceChanged =
5518 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005519 mOutDevice = value;
5520 for (size_t i = 0; i < mEffectChains.size(); i++) {
5521 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005522 }
5523 }
Eric Laurent81784c32012-11-19 14:55:58 -08005524 }
Eric Laurent10351942014-05-08 18:49:52 -07005525 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5526 // do not accept frame count changes if tracks are open as the track buffer
5527 // size depends on frame count and correct behavior would not be garantied
5528 // if frame count is changed after track creation
5529 if (!mTracks.isEmpty()) {
5530 status = INVALID_OPERATION;
5531 } else {
5532 reconfig = true;
5533 }
5534 }
5535 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005536 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005537 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005538 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005539 mStandby = true;
5540 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005541 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005542 }
5543 if (status == NO_ERROR && reconfig) {
5544 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005545 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005546 }
5547 }
5548
Eric Laurent42537be2016-01-08 17:16:42 -08005549 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005550}
5551
5552uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5553{
5554 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005555 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005556 time = PlaybackThread::activeSleepTimeUs();
5557 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005558 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005559 }
5560 return time;
5561}
5562
5563uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5564{
5565 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005566 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005567 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5568 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005569 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005570 }
5571 return time;
5572}
5573
5574uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5575{
5576 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005577 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005578 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5579 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005580 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005581 }
5582 return time;
5583}
5584
5585void AudioFlinger::DirectOutputThread::cacheParameters_l()
5586{
5587 PlaybackThread::cacheParameters_l();
5588
5589 // use shorter standby delay as on normal output to release
5590 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005591 // no delay on outputs with HW A/V sync
5592 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005593 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005594 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005595 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005596 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005597 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005598 }
Eric Laurent81784c32012-11-19 14:55:58 -08005599}
5600
Eric Laurente659ef42014-09-29 13:06:46 -07005601void AudioFlinger::DirectOutputThread::flushHw_l()
5602{
Phil Burk062e67a2015-02-11 13:40:50 -08005603 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005604 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005605 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005606}
5607
Andy Hung10cbff12017-02-21 17:30:14 -08005608int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5609 // If a VolumeShaper is active, we must wake up periodically to update volume.
5610 const int64_t NS_PER_MS = 1000000;
5611 return mVolumeShaperActive ?
5612 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5613}
5614
Eric Laurent81784c32012-11-19 14:55:58 -08005615// ----------------------------------------------------------------------------
5616
Eric Laurentbfb1b832013-01-07 09:53:42 -08005617AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005618 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005620 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005621 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005622 mDrainSequence(0),
5623 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005624{
5625}
5626
5627AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5628{
5629}
5630
5631void AudioFlinger::AsyncCallbackThread::onFirstRef()
5632{
5633 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5634}
5635
5636bool AudioFlinger::AsyncCallbackThread::threadLoop()
5637{
5638 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005639 uint32_t writeAckSequence;
5640 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005641 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005642
5643 {
5644 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005645 while (!((mWriteAckSequence & 1) ||
5646 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005647 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005648 exitPending())) {
5649 mWaitWorkCV.wait(mLock);
5650 }
5651
Eric Laurentbfb1b832013-01-07 09:53:42 -08005652 if (exitPending()) {
5653 break;
5654 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005655 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5656 mWriteAckSequence, mDrainSequence);
5657 writeAckSequence = mWriteAckSequence;
5658 mWriteAckSequence &= ~1;
5659 drainSequence = mDrainSequence;
5660 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005661 asyncError = mAsyncError;
5662 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005663 }
5664 {
Eric Laurent4de95592013-09-26 15:28:21 -07005665 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5666 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005667 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005668 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005669 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005670 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005671 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005672 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005673 if (asyncError) {
5674 playbackThread->onAsyncError();
5675 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005676 }
5677 }
5678 }
5679 return false;
5680}
5681
5682void AudioFlinger::AsyncCallbackThread::exit()
5683{
5684 ALOGV("AsyncCallbackThread::exit");
5685 Mutex::Autolock _l(mLock);
5686 requestExit();
5687 mWaitWorkCV.broadcast();
5688}
5689
Eric Laurent3b4529e2013-09-05 18:09:19 -07005690void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691{
5692 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005693 // bit 0 is cleared
5694 mWriteAckSequence = sequence << 1;
5695}
5696
5697void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5698{
5699 Mutex::Autolock _l(mLock);
5700 // ignore unexpected callbacks
5701 if (mWriteAckSequence & 2) {
5702 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703 mWaitWorkCV.signal();
5704 }
5705}
5706
Eric Laurent3b4529e2013-09-05 18:09:19 -07005707void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005708{
5709 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005710 // bit 0 is cleared
5711 mDrainSequence = sequence << 1;
5712}
5713
5714void AudioFlinger::AsyncCallbackThread::resetDraining()
5715{
5716 Mutex::Autolock _l(mLock);
5717 // ignore unexpected callbacks
5718 if (mDrainSequence & 2) {
5719 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005720 mWaitWorkCV.signal();
5721 }
5722}
5723
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005724void AudioFlinger::AsyncCallbackThread::setAsyncError()
5725{
5726 Mutex::Autolock _l(mLock);
5727 mAsyncError = true;
5728 mWaitWorkCV.signal();
5729}
5730
Eric Laurentbfb1b832013-01-07 09:53:42 -08005731
5732// ----------------------------------------------------------------------------
5733AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005734 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5735 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005736 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5737 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005738{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005739 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005740 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005741 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005742}
5743
Eric Laurentbfb1b832013-01-07 09:53:42 -08005744void AudioFlinger::OffloadThread::threadLoop_exit()
5745{
5746 if (mFlushPending || mHwPaused) {
5747 // If a flush is pending or track was paused, just discard buffered data
5748 flushHw_l();
5749 } else {
5750 mMixerStatus = MIXER_DRAIN_ALL;
5751 threadLoop_drain();
5752 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005753 if (mUseAsyncWrite) {
5754 ALOG_ASSERT(mCallbackThread != 0);
5755 mCallbackThread->exit();
5756 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005757 PlaybackThread::threadLoop_exit();
5758}
5759
5760AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5761 Vector< sp<Track> > *tracksToRemove
5762)
5763{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005764 size_t count = mActiveTracks.size();
5765
5766 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005767 bool doHwPause = false;
5768 bool doHwResume = false;
5769
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005770 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005771
Eric Laurentbfb1b832013-01-07 09:53:42 -08005772 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005773 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005774 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005775#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005776 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005777#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005778 // Only consider last track started for volume and mixer state control.
5779 // In theory an older track could underrun and restart after the new one starts
5780 // but as we only care about the transition phase between two tracks on a
5781 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005782 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005783 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005784
Haynes Mathew George7844f672014-01-15 12:32:55 -08005785 if (track->isInvalid()) {
5786 ALOGW("An invalidated track shouldn't be in active list");
5787 tracksToRemove->add(track);
5788 continue;
5789 }
5790
5791 if (track->mState == TrackBase::IDLE) {
5792 ALOGW("An idle track shouldn't be in active list");
5793 continue;
5794 }
5795
Eric Laurentbfb1b832013-01-07 09:53:42 -08005796 if (track->isPausing()) {
5797 track->setPaused();
5798 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005799 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005800 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005801 mHwPaused = true;
5802 }
5803 // If we were part way through writing the mixbuffer to
5804 // the HAL we must save this until we resume
5805 // BUG - this will be wrong if a different track is made active,
5806 // in that case we want to discard the pending data in the
5807 // mixbuffer and tell the client to present it again when the
5808 // track is resumed
5809 mPausedWriteLength = mCurrentWriteLength;
5810 mPausedBytesRemaining = mBytesRemaining;
5811 mBytesRemaining = 0; // stop writing
5812 }
5813 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005814 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005815 if (track->isStopping_1()) {
5816 track->mRetryCount = kMaxTrackStopRetriesOffload;
5817 } else {
5818 track->mRetryCount = kMaxTrackRetriesOffload;
5819 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005820 track->flushAck();
5821 if (last) {
5822 mFlushPending = true;
5823 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005824 } else if (track->isResumePending()){
5825 track->resumeAck();
5826 if (last) {
5827 if (mPausedBytesRemaining) {
5828 // Need to continue write that was interrupted
5829 mCurrentWriteLength = mPausedWriteLength;
5830 mBytesRemaining = mPausedBytesRemaining;
5831 mPausedBytesRemaining = 0;
5832 }
5833 if (mHwPaused) {
5834 doHwResume = true;
5835 mHwPaused = false;
5836 // threadLoop_mix() will handle the case that we need to
5837 // resume an interrupted write
5838 }
5839 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005840 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005841
Eric Laurent3df841a2016-07-15 15:15:40 -07005842 mLeftVolFloat = mRightVolFloat = -1.0;
5843
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005844 // Do not handle new data in this iteration even if track->framesReady()
5845 mixerStatus = MIXER_TRACKS_ENABLED;
5846 }
5847 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005848 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005849 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005850 if (track->mFillingUpStatus == Track::FS_FILLED) {
5851 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005852 if (last) {
5853 // make sure processVolume_l() will apply new volume even if 0
5854 mLeftVolFloat = mRightVolFloat = -1.0;
5855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005856 }
5857
5858 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005859 sp<Track> previousTrack = mPreviousTrack.promote();
5860 if (previousTrack != 0) {
5861 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005862 // Flush any data still being written from last track
5863 mBytesRemaining = 0;
5864 if (mPausedBytesRemaining) {
5865 // Last track was paused so we also need to flush saved
5866 // mixbuffer state and invalidate track so that it will
5867 // re-submit that unwritten data when it is next resumed
5868 mPausedBytesRemaining = 0;
5869 // Invalidate is a bit drastic - would be more efficient
5870 // to have a flag to tell client that some of the
5871 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005872 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005873 }
5874 // flush data already sent to the DSP if changing audio session as audio
5875 // comes from a different source. Also invalidate previous track to force a
5876 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005877 if (previousTrack->sessionId() != track->sessionId()) {
5878 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005879 }
5880 }
5881 }
5882 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005883 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005884 if (track->isStopping_1()) {
5885 track->mRetryCount = kMaxTrackStopRetriesOffload;
5886 } else {
5887 track->mRetryCount = kMaxTrackRetriesOffload;
5888 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005889 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005890 mixerStatus = MIXER_TRACKS_READY;
5891 }
5892 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005893 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005894 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005895 if (--(track->mRetryCount) <= 0) {
5896 // Hardware buffer can hold a large amount of audio so we must
5897 // wait for all current track's data to drain before we say
5898 // that the track is stopped.
5899 if (mBytesRemaining == 0) {
5900 // Only start draining when all data in mixbuffer
5901 // has been written
5902 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5903 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5904 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5905 if (last && !mStandby) {
5906 // do not modify drain sequence if we are already draining. This happens
5907 // when resuming from pause after drain.
5908 if ((mDrainSequence & 1) == 0) {
5909 mSleepTimeUs = 0;
5910 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5911 mixerStatus = MIXER_DRAIN_TRACK;
5912 mDrainSequence += 2;
5913 }
5914 if (mHwPaused) {
5915 // It is possible to move from PAUSED to STOPPING_1 without
5916 // a resume so we must ensure hardware is running
5917 doHwResume = true;
5918 mHwPaused = false;
5919 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005920 }
5921 }
Eric Laurente93cc032016-05-05 10:15:10 -07005922 } else if (last) {
5923 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5924 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005925 }
5926 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005927 // Drain has completed or we are in standby, signal presentation complete
5928 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005929 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005930 uint32_t latency = 0;
5931 status_t result = mOutput->stream->getLatency(&latency);
5932 ALOGE_IF(result != OK,
5933 "Error when retrieving output stream latency: %d", result);
5934 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005935 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005936 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005937 track->presentationComplete(framesWritten, audioHALFrames);
5938 track->reset();
5939 tracksToRemove->add(track);
5940 }
5941 } else {
5942 // No buffers for this track. Give it a few chances to
5943 // fill a buffer, then remove it from active list.
5944 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005945 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005946 uint64_t position = 0;
5947 struct timespec unused;
5948 // The running check restarts the retry counter at least once.
5949 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5950 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5951 running = true;
5952 mOffloadUnderrunPosition = position;
5953 }
5954 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005955 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5956 (long long)position, (long long)mOffloadUnderrunPosition);
5957 }
5958 if (running) { // still running, give us more time.
5959 track->mRetryCount = kMaxTrackRetriesOffload;
5960 } else {
5961 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5962 track->name());
5963 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005964 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005965 // it will then automatically call start() when data is available
5966 track->disable();
5967 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005968 } else if (last){
5969 mixerStatus = MIXER_TRACKS_ENABLED;
5970 }
5971 }
5972 }
5973 // compute volume for this track
5974 processVolume_l(track, last);
5975 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005976
Eric Laurentea0fade2013-10-04 16:23:48 -07005977 // make sure the pause/flush/resume sequence is executed in the right order.
5978 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5979 // before flush and then resume HW. This can happen in case of pause/flush/resume
5980 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005981 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005982 status_t result = mOutput->stream->pause();
5983 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005984 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005985 if (mFlushPending) {
5986 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005987 }
Eric Laurentfd477972013-10-25 18:10:40 -07005988 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005989 status_t result = mOutput->stream->resume();
5990 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005991 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005992
Eric Laurentbfb1b832013-01-07 09:53:42 -08005993 // remove all the tracks that need to be...
5994 removeTracks_l(*tracksToRemove);
5995
5996 return mixerStatus;
5997}
5998
Eric Laurentbfb1b832013-01-07 09:53:42 -08005999// must be called with thread mutex locked
6000bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6001{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006002 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6003 mWriteAckSequence, mDrainSequence);
6004 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006005 return true;
6006 }
6007 return false;
6008}
6009
Eric Laurentbfb1b832013-01-07 09:53:42 -08006010bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6011{
6012 Mutex::Autolock _l(mLock);
6013 return waitingAsyncCallback_l();
6014}
6015
6016void AudioFlinger::OffloadThread::flushHw_l()
6017{
Eric Laurente659ef42014-09-29 13:06:46 -07006018 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006019 // Flush anything still waiting in the mixbuffer
6020 mCurrentWriteLength = 0;
6021 mBytesRemaining = 0;
6022 mPausedWriteLength = 0;
6023 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006024 // reset bytes written count to reflect that DSP buffers are empty after flush.
6025 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006026 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006027
Eric Laurentbfb1b832013-01-07 09:53:42 -08006028 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006029 // discard any pending drain or write ack by incrementing sequence
6030 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6031 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006032 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006033 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6034 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006035 }
6036}
6037
Haynes Mathew George05317d22016-05-03 16:34:26 -07006038void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6039{
6040 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006041 if (PlaybackThread::invalidateTracks_l(streamType)) {
6042 mFlushPending = true;
6043 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006044}
6045
Eric Laurentbfb1b832013-01-07 09:53:42 -08006046// ----------------------------------------------------------------------------
6047
Eric Laurent81784c32012-11-19 14:55:58 -08006048AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006049 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006050 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006051 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006052 mWaitTimeMs(UINT_MAX)
6053{
6054 addOutputTrack(mainThread);
6055}
6056
6057AudioFlinger::DuplicatingThread::~DuplicatingThread()
6058{
6059 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6060 mOutputTracks[i]->destroy();
6061 }
6062}
6063
6064void AudioFlinger::DuplicatingThread::threadLoop_mix()
6065{
6066 // mix buffers...
6067 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006068 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006069 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006070 if (mMixerBufferValid) {
6071 memset(mMixerBuffer, 0, mMixerBufferSize);
6072 } else {
6073 memset(mSinkBuffer, 0, mSinkBufferSize);
6074 }
Eric Laurent81784c32012-11-19 14:55:58 -08006075 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006076 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006077 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006078 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006079 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006080}
6081
6082void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6083{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006084 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006085 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006086 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006087 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006088 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006089 }
6090 } else if (mBytesWritten != 0) {
6091 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6092 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006093 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006094 } else {
6095 // flush remaining overflow buffers in output tracks
6096 writeFrames = 0;
6097 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006098 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006099 }
6100}
6101
Eric Laurentbfb1b832013-01-07 09:53:42 -08006102ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006103{
6104 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08006105 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08006106 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006107 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006108 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006109}
6110
6111void AudioFlinger::DuplicatingThread::threadLoop_standby()
6112{
6113 // DuplicatingThread implements standby by stopping all tracks
6114 for (size_t i = 0; i < outputTracks.size(); i++) {
6115 outputTracks[i]->stop();
6116 }
6117}
6118
Andy Hung1bc088a2018-02-09 15:57:31 -08006119void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6120{
6121 MixerThread::dumpInternals(fd, args);
6122
6123 std::stringstream ss;
6124 const size_t numTracks = mOutputTracks.size();
6125 ss << " " << numTracks << " OutputTracks";
6126 if (numTracks > 0) {
6127 ss << ":";
6128 for (const auto &track : mOutputTracks) {
6129 const sp<ThreadBase> thread = track->thread().promote();
6130 ss << " (" << track->name() << " : ";
6131 if (thread.get() != nullptr) {
6132 ss << thread.get() << ", " << thread->id();
6133 } else {
6134 ss << "null";
6135 }
6136 ss << ")";
6137 }
6138 }
6139 ss << "\n";
6140 std::string result = ss.str();
6141 write(fd, result.c_str(), result.size());
6142}
6143
Eric Laurent81784c32012-11-19 14:55:58 -08006144void AudioFlinger::DuplicatingThread::saveOutputTracks()
6145{
6146 outputTracks = mOutputTracks;
6147}
6148
6149void AudioFlinger::DuplicatingThread::clearOutputTracks()
6150{
6151 outputTracks.clear();
6152}
6153
6154void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6155{
6156 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006157 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6158 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6159 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6160 const size_t frameCount =
6161 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6162 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6163 // from different OutputTracks and their associated MixerThreads (e.g. one may
6164 // nearly empty and the other may be dropping data).
6165
6166 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006167 this,
6168 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006169 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006170 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006171 frameCount,
6172 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006173 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6174 if (status != NO_ERROR) {
6175 ALOGE("addOutputTrack() initCheck failed %d", status);
6176 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006177 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006178 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6179 mOutputTracks.add(outputTrack);
6180 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6181 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006182}
6183
6184void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6185{
6186 Mutex::Autolock _l(mLock);
6187 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6188 if (mOutputTracks[i]->thread() == thread) {
6189 mOutputTracks[i]->destroy();
6190 mOutputTracks.removeAt(i);
6191 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006192 if (thread->getOutput() == mOutput) {
6193 mOutput = NULL;
6194 }
Eric Laurent81784c32012-11-19 14:55:58 -08006195 return;
6196 }
6197 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006198 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006199}
6200
6201// caller must hold mLock
6202void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6203{
6204 mWaitTimeMs = UINT_MAX;
6205 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6206 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6207 if (strong != 0) {
6208 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6209 if (waitTimeMs < mWaitTimeMs) {
6210 mWaitTimeMs = waitTimeMs;
6211 }
6212 }
6213 }
6214}
6215
6216
6217bool AudioFlinger::DuplicatingThread::outputsReady(
6218 const SortedVector< sp<OutputTrack> > &outputTracks)
6219{
6220 for (size_t i = 0; i < outputTracks.size(); i++) {
6221 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6222 if (thread == 0) {
6223 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6224 outputTracks[i].get());
6225 return false;
6226 }
6227 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6228 // see note at standby() declaration
6229 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6230 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6231 thread.get());
6232 return false;
6233 }
6234 }
6235 return true;
6236}
6237
Kevin Rocard12381092018-04-11 09:19:59 -07006238void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6239 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006240{
Kevin Rocard12381092018-04-11 09:19:59 -07006241 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6242 outputTrack->setMetadatas(metadata.tracks);
6243 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006244}
6245
Eric Laurent81784c32012-11-19 14:55:58 -08006246uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6247{
6248 return (mWaitTimeMs * 1000) / 2;
6249}
6250
6251void AudioFlinger::DuplicatingThread::cacheParameters_l()
6252{
6253 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6254 updateWaitTime_l();
6255
6256 MixerThread::cacheParameters_l();
6257}
6258
Eric Laurent6acd1d42017-01-04 14:23:29 -08006259
Eric Laurent81784c32012-11-19 14:55:58 -08006260// ----------------------------------------------------------------------------
6261// Record
6262// ----------------------------------------------------------------------------
6263
6264AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6265 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006266 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006267 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006268 audio_devices_t inDevice,
6269 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006270#ifdef TEE_SINK
6271 , const sp<NBAIO_Sink>& teeSink
6272#endif
6273 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006274 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006275 mInput(input),
6276 mActiveTracks(&this->mLocalLog),
6277 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006278 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006279 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006280#ifdef TEE_SINK
6281 , mTeeSink(teeSink)
6282#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006283 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6284 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006285 // mFastCapture below
6286 , mFastCaptureFutex(0)
6287 // mInputSource
6288 // mPipeSink
6289 // mPipeSource
6290 , mPipeFramesP2(0)
6291 // mPipeMemory
6292 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006293 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006294 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
Glenn Kastend7dca052015-03-05 16:05:54 -08006296 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6297 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006298
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006299 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006300
6301 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006302 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006303 size_t numCounterOffers = 0;
6304 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006305#if !LOG_NDEBUG
6306 ssize_t index =
6307#else
6308 (void)
6309#endif
6310 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006311 ALOG_ASSERT(index == 0);
6312
6313 // initialize fast capture depending on configuration
6314 bool initFastCapture;
6315 switch (kUseFastCapture) {
6316 case FastCapture_Never:
6317 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006318 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006319 break;
6320 case FastCapture_Always:
6321 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006322 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006323 break;
6324 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006325 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006326 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6327 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6328 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006329 break;
6330 // case FastCapture_Dynamic:
6331 }
6332
6333 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006334 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006335 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006336 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6337 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006338 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006339 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006340 const sp<MemoryDealer> roHeap(readOnlyHeap());
6341 sp<IMemory> pipeMemory;
6342 if ((roHeap == 0) ||
6343 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006344 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6345 ALOGE("not enough memory for pipe buffer size=%zu; "
6346 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6347 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6348 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006349 goto failed;
6350 }
6351 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6352 memset(pipeBuffer, 0, pipeSize);
6353 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6354 const NBAIO_Format offers[1] = {format};
6355 size_t numCounterOffers = 0;
6356 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6357 ALOG_ASSERT(index == 0);
6358 mPipeSink = pipe;
6359 PipeReader *pipeReader = new PipeReader(*pipe);
6360 numCounterOffers = 0;
6361 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6362 ALOG_ASSERT(index == 0);
6363 mPipeSource = pipeReader;
6364 mPipeFramesP2 = pipeFramesP2;
6365 mPipeMemory = pipeMemory;
6366
6367 // create fast capture
6368 mFastCapture = new FastCapture();
6369 FastCaptureStateQueue *sq = mFastCapture->sq();
6370#ifdef STATE_QUEUE_DUMP
6371 // FIXME
6372#endif
6373 FastCaptureState *state = sq->begin();
6374 state->mCblk = NULL;
6375 state->mInputSource = mInputSource.get();
6376 state->mInputSourceGen++;
6377 state->mPipeSink = pipe;
6378 state->mPipeSinkGen++;
6379 state->mFrameCount = mFrameCount;
6380 state->mCommand = FastCaptureState::COLD_IDLE;
6381 // already done in constructor initialization list
6382 //mFastCaptureFutex = 0;
6383 state->mColdFutexAddr = &mFastCaptureFutex;
6384 state->mColdGen++;
6385 state->mDumpState = &mFastCaptureDumpState;
6386#ifdef TEE_SINK
6387 // FIXME
6388#endif
6389 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6390 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6391 sq->end();
6392 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6393
6394 // start the fast capture
6395 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6396 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006397 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006398 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006399#ifdef AUDIO_WATCHDOG
6400 // FIXME
6401#endif
6402
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006403 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006404 }
6405failed: ;
6406
6407 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006408}
6409
Eric Laurent81784c32012-11-19 14:55:58 -08006410AudioFlinger::RecordThread::~RecordThread()
6411{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006412 if (mFastCapture != 0) {
6413 FastCaptureStateQueue *sq = mFastCapture->sq();
6414 FastCaptureState *state = sq->begin();
6415 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6416 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6417 if (old == -1) {
6418 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6419 }
6420 }
6421 state->mCommand = FastCaptureState::EXIT;
6422 sq->end();
6423 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6424 mFastCapture->join();
6425 mFastCapture.clear();
6426 }
6427 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006428 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006429 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006430}
6431
6432void AudioFlinger::RecordThread::onFirstRef()
6433{
Glenn Kastend7dca052015-03-05 16:05:54 -08006434 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006435}
6436
Eric Laurent555530a2017-02-07 18:17:24 -08006437void AudioFlinger::RecordThread::preExit()
6438{
6439 ALOGV(" preExit()");
6440 Mutex::Autolock _l(mLock);
6441 for (size_t i = 0; i < mTracks.size(); i++) {
6442 sp<RecordTrack> track = mTracks[i];
6443 track->invalidate();
6444 }
6445 mActiveTracks.clear();
6446 mStartStopCond.broadcast();
6447}
6448
Eric Laurent81784c32012-11-19 14:55:58 -08006449bool AudioFlinger::RecordThread::threadLoop()
6450{
Eric Laurent81784c32012-11-19 14:55:58 -08006451 nsecs_t lastWarning = 0;
6452
6453 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006454
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006455reacquire_wakelock:
6456 sp<RecordTrack> activeTrack;
6457 {
6458 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006459 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006460 }
6461
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006462 // used to request a deferred sleep, to be executed later while mutex is unlocked
6463 uint32_t sleepUs = 0;
6464
6465 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006466 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006467 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006468
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006469 // activeTracks accumulates a copy of a subset of mActiveTracks
6470 Vector< sp<RecordTrack> > activeTracks;
6471
Glenn Kasten735f45f2014-08-18 15:51:59 -07006472 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006473 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006474
Glenn Kasten735f45f2014-08-18 15:51:59 -07006475 // reference to a fast track which is about to be removed
6476 sp<RecordTrack> fastTrackToRemove;
6477
Eric Laurent81784c32012-11-19 14:55:58 -08006478 { // scope for mLock
6479 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006480
Eric Laurent021cf962014-05-13 10:18:14 -07006481 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006482
Eric Laurent000a4192014-01-29 15:17:32 -08006483 // check exitPending here because checkForNewParameters_l() and
6484 // checkForNewParameters_l() can temporarily release mLock
6485 if (exitPending()) {
6486 break;
6487 }
6488
Eric Laurent5c25d562016-07-13 17:17:45 -07006489 // sleep with mutex unlocked
6490 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006491 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006492 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6493 ATRACE_END();
6494 sleepUs = 0;
6495 continue;
6496 }
6497
Glenn Kasten2b806402013-11-20 16:37:38 -08006498 // if no active track(s), then standby and release wakelock
6499 size_t size = mActiveTracks.size();
6500 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006501 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006502 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006503 releaseWakeLock_l();
6504 ALOGV("RecordThread: loop stopping");
6505 // go to sleep
6506 mWaitWorkCV.wait(mLock);
6507 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006508 goto reacquire_wakelock;
6509 }
6510
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006511 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006512 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006513 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006514
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006515 activeTrack = mActiveTracks[i];
6516 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006517 if (activeTrack->isFastTrack()) {
6518 ALOG_ASSERT(fastTrackToRemove == 0);
6519 fastTrackToRemove = activeTrack;
6520 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006521 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006522 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006523 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006524 continue;
6525 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006526
6527 TrackBase::track_state activeTrackState = activeTrack->mState;
6528 switch (activeTrackState) {
6529
6530 case TrackBase::PAUSING:
6531 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006532 doBroadcast = true;
6533 size--;
6534 continue;
6535
6536 case TrackBase::STARTING_1:
6537 sleepUs = 10000;
6538 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006539 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006540 continue;
6541
6542 case TrackBase::STARTING_2:
6543 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006544 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006545 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006546 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006547 break;
6548
6549 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006550 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006551 break;
6552
6553 case TrackBase::IDLE:
6554 i++;
6555 continue;
6556
6557 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006558 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006559 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006560
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006561 activeTracks.add(activeTrack);
6562 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006563
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006564 if (activeTrack->isFastTrack()) {
6565 ALOG_ASSERT(!mFastTrackAvail);
6566 ALOG_ASSERT(fastTrack == 0);
6567 fastTrack = activeTrack;
6568 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006569 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006570
Andy Hungdae27702016-10-31 14:01:16 -07006571 mActiveTracks.updatePowerState(this);
6572
Kevin Rocard069c2712018-03-29 19:09:14 -07006573 updateMetadata_l();
6574
Eric Laurent5c25d562016-07-13 17:17:45 -07006575 if (allStopped) {
6576 standbyIfNotAlreadyInStandby();
6577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006578 if (doBroadcast) {
6579 mStartStopCond.broadcast();
6580 }
6581
6582 // sleep if there are no active tracks to process
6583 if (activeTracks.size() == 0) {
6584 if (sleepUs == 0) {
6585 sleepUs = kRecordThreadSleepUs;
6586 }
6587 continue;
6588 }
6589 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006590
Eric Laurent81784c32012-11-19 14:55:58 -08006591 lockEffectChains_l(effectChains);
6592 }
6593
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006594 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006595
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006596 size_t size = effectChains.size();
6597 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006598 // thread mutex is not locked, but effect chain is locked
6599 effectChains[i]->process_l();
6600 }
6601
Glenn Kasten735f45f2014-08-18 15:51:59 -07006602 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006603 if (mFastCapture != 0) {
6604 FastCaptureStateQueue *sq = mFastCapture->sq();
6605 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006606 bool didModify = false;
6607 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006608 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6609 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6610 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6611 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6612 if (old == -1) {
6613 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6614 }
6615 }
6616 state->mCommand = FastCaptureState::READ_WRITE;
6617#if 0 // FIXME
6618 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006619 FastThreadDumpState::kSamplingNforLowRamDevice :
6620 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006621#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006622 didModify = true;
6623 }
6624 audio_track_cblk_t *cblkOld = state->mCblk;
6625 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6626 if (cblkNew != cblkOld) {
6627 state->mCblk = cblkNew;
6628 // block until acked if removing a fast track
6629 if (cblkOld != NULL) {
6630 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6631 }
6632 didModify = true;
6633 }
6634 sq->end(didModify);
6635 if (didModify) {
6636 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006637#if 0
6638 if (kUseFastCapture == FastCapture_Dynamic) {
6639 mNormalSource = mPipeSource;
6640 }
6641#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006642 }
6643 }
6644
Glenn Kasten735f45f2014-08-18 15:51:59 -07006645 // now run the fast track destructor with thread mutex unlocked
6646 fastTrackToRemove.clear();
6647
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006648 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6649 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6650 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6651 // If destination is non-contiguous, first read past the nominal end of buffer, then
6652 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006653
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006654 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006655 ssize_t framesRead;
6656
6657 // If an NBAIO source is present, use it to read the normal capture's data
6658 if (mPipeSource != 0) {
6659 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006660 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006661
6662 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6663 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6664 // we immediately retry the read() to get data and prevent another overflow.
6665 for (int retries = 0; retries <= 2; ++retries) {
6666 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6667 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6668 framesToRead);
6669 if (framesRead != OVERRUN) break;
6670 }
6671
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006672 const ssize_t availableToRead = mPipeSource->availableToRead();
6673 if (availableToRead >= 0) {
6674 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6675 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6676 "more frames to read than fifo size, %zd > %zu",
6677 availableToRead, mPipeFramesP2);
6678 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6679 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6680 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6681 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006682 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6683 }
6684 if (framesRead < 0) {
6685 status_t status = (status_t) framesRead;
6686 switch (status) {
6687 case OVERRUN:
6688 ALOGW("overrun on read from pipe");
6689 framesRead = 0;
6690 break;
6691 case NEGOTIATE:
6692 ALOGE("re-negotiation is needed");
6693 framesRead = -1; // Will cause an attempt to recover.
6694 break;
6695 default:
6696 ALOGE("unknown error %d on read from pipe", status);
6697 break;
6698 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006699 }
6700 // otherwise use the HAL / AudioStreamIn directly
6701 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006702 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006703 size_t bytesRead;
6704 status_t result = mInput->stream->read(
6705 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006706 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006707 if (result < 0) {
6708 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006709 } else {
6710 framesRead = bytesRead / mFrameSize;
6711 }
6712 }
6713
Andy Hung3f0c9022016-01-15 17:49:46 -08006714 // Update server timestamp with server stats
6715 // systemTime() is optional if the hardware supports timestamps.
6716 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6717 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6718
6719 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006720 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006721 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006722 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006723 if (ret == NO_ERROR) {
6724 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6725 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6726 // Note: In general record buffers should tend to be empty in
6727 // a properly running pipeline.
6728 //
6729 // Also, it is not advantageous to call get_presentation_position during the read
6730 // as the read obtains a lock, preventing the timestamp call from executing.
6731 }
6732 }
6733 // Use this to track timestamp information
6734 // ALOGD("%s", mTimestamp.toString().c_str());
6735
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006736 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006737 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006738 // Force input into standby so that it tries to recover at next read attempt
6739 inputStandBy();
6740 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006741 }
6742 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006743 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006744 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006745 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006746
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006747 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006748 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006749 }
6750 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006751 {
6752 size_t part1 = mRsmpInFramesP2 - rear;
6753 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006754 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006755 (framesRead - part1) * mFrameSize);
6756 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006757 }
6758 rear = mRsmpInRear += framesRead;
6759
6760 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006761
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006762 // loop over each active track
6763 for (size_t i = 0; i < size; i++) {
6764 activeTrack = activeTracks[i];
6765
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006766 // skip fast tracks, as those are handled directly by FastCapture
6767 if (activeTrack->isFastTrack()) {
6768 continue;
6769 }
6770
Andy Hung73c02e42015-03-29 01:13:58 -07006771 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006772 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6773
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006774 enum {
6775 OVERRUN_UNKNOWN,
6776 OVERRUN_TRUE,
6777 OVERRUN_FALSE
6778 } overrun = OVERRUN_UNKNOWN;
6779
6780 // loop over getNextBuffer to handle circular sink
6781 for (;;) {
6782
6783 activeTrack->mSink.frameCount = ~0;
6784 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6785 size_t framesOut = activeTrack->mSink.frameCount;
6786 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6787
Andy Hung73c02e42015-03-29 01:13:58 -07006788 // check available frames and handle overrun conditions
6789 // if the record track isn't draining fast enough.
6790 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006791 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006792 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6793 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006794 overrun = OVERRUN_TRUE;
6795 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006796 if (framesOut == 0 || framesIn == 0) {
6797 break;
6798 }
6799
Andy Hung6770c6f2015-04-07 13:43:36 -07006800 // Don't allow framesOut to be larger than what is possible with resampling
6801 // from framesIn.
6802 // This isn't strictly necessary but helps limit buffer resizing in
6803 // RecordBufferConverter. TODO: remove when no longer needed.
6804 framesOut = min(framesOut,
6805 destinationFramesPossible(
6806 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006807 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6808 framesOut = activeTrack->mRecordBufferConverter->convert(
6809 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006810
6811 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6812 overrun = OVERRUN_FALSE;
6813 }
6814
6815 if (activeTrack->mFramesToDrop == 0) {
6816 if (framesOut > 0) {
6817 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006818 // Sanitize before releasing if the track has no access to the source data
6819 // An idle UID receives silence from non virtual devices until active
6820 if (activeTrack->isSilenced()) {
6821 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6822 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006823 activeTrack->releaseBuffer(&activeTrack->mSink);
6824 }
6825 } else {
6826 // FIXME could do a partial drop of framesOut
6827 if (activeTrack->mFramesToDrop > 0) {
6828 activeTrack->mFramesToDrop -= framesOut;
6829 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006830 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006831 }
6832 } else {
6833 activeTrack->mFramesToDrop += framesOut;
6834 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6835 activeTrack->mSyncStartEvent->isCancelled()) {
6836 ALOGW("Synced record %s, session %d, trigger session %d",
6837 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6838 activeTrack->sessionId(),
6839 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006840 activeTrack->mSyncStartEvent->triggerSession() :
6841 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006842 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006843 }
6844 }
6845 }
6846
6847 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006848 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006849 }
6850 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006851
6852 switch (overrun) {
6853 case OVERRUN_TRUE:
6854 // client isn't retrieving buffers fast enough
6855 if (!activeTrack->setOverflow()) {
6856 nsecs_t now = systemTime();
6857 // FIXME should lastWarning per track?
6858 if ((now - lastWarning) > kWarningThrottleNs) {
6859 ALOGW("RecordThread: buffer overflow");
6860 lastWarning = now;
6861 }
6862 }
6863 break;
6864 case OVERRUN_FALSE:
6865 activeTrack->clearOverflow();
6866 break;
6867 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006868 break;
6869 }
6870
Andy Hung3f0c9022016-01-15 17:49:46 -08006871 // update frame information and push timestamp out
6872 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006873 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006874 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6875 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006876 }
6877
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006878unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006879 // enable changes in effect chain
6880 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006881 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006882 }
6883
Glenn Kasten93e471f2013-08-19 08:40:07 -07006884 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006885
6886 {
6887 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006888 for (size_t i = 0; i < mTracks.size(); i++) {
6889 sp<RecordTrack> track = mTracks[i];
6890 track->invalidate();
6891 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006892 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006893 mStartStopCond.broadcast();
6894 }
6895
6896 releaseWakeLock();
6897
6898 ALOGV("RecordThread %p exiting", this);
6899 return false;
6900}
6901
Glenn Kasten93e471f2013-08-19 08:40:07 -07006902void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006903{
6904 if (!mStandby) {
6905 inputStandBy();
6906 mStandby = true;
6907 }
6908}
6909
6910void AudioFlinger::RecordThread::inputStandBy()
6911{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006912 // Idle the fast capture if it's currently running
6913 if (mFastCapture != 0) {
6914 FastCaptureStateQueue *sq = mFastCapture->sq();
6915 FastCaptureState *state = sq->begin();
6916 if (!(state->mCommand & FastCaptureState::IDLE)) {
6917 state->mCommand = FastCaptureState::COLD_IDLE;
6918 state->mColdFutexAddr = &mFastCaptureFutex;
6919 state->mColdGen++;
6920 mFastCaptureFutex = 0;
6921 sq->end();
6922 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6923 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6924#if 0
6925 if (kUseFastCapture == FastCapture_Dynamic) {
6926 // FIXME
6927 }
6928#endif
6929#ifdef AUDIO_WATCHDOG
6930 // FIXME
6931#endif
6932 } else {
6933 sq->end(false /*didModify*/);
6934 }
6935 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006936 status_t result = mInput->stream->standby();
6937 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006938
6939 // If going into standby, flush the pipe source.
6940 if (mPipeSource.get() != nullptr) {
6941 const ssize_t flushed = mPipeSource->flush();
6942 if (flushed > 0) {
6943 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6944 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6945 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6946 }
6947 }
Eric Laurent81784c32012-11-19 14:55:58 -08006948}
6949
Glenn Kasten05997e22014-03-13 15:08:33 -07006950// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006951sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006952 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006953 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006954 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006955 audio_format_t format,
6956 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006957 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006958 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006959 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006960 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006961 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006962 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006963 status_t *status,
6964 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006965{
Glenn Kasten74935e42013-12-19 08:56:45 -08006966 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006967 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006968 sp<RecordTrack> track;
6969 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006970 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006971 audio_input_flags_t requestedFlags = *flags;
6972 uint32_t sampleRate;
6973
6974 lStatus = initCheck();
6975 if (lStatus != NO_ERROR) {
6976 ALOGE("createRecordTrack_l() audio driver not initialized");
6977 goto Exit;
6978 }
6979
6980 if (*pSampleRate == 0) {
6981 *pSampleRate = mSampleRate;
6982 }
6983 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006984
6985 // special case for FAST flag considered OK if fast capture is present
6986 if (hasFastCapture()) {
6987 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6988 }
6989
Eric Laurentf14db3c2017-12-08 14:20:36 -08006990 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006991 if ((*flags & inputFlags) != *flags) {
6992 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6993 " input flags (%08x)",
6994 *flags, inputFlags);
6995 *flags = (audio_input_flags_t)(*flags & inputFlags);
6996 }
Eric Laurent81784c32012-11-19 14:55:58 -08006997
Glenn Kasten90e58b12013-07-31 16:16:02 -07006998 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006999 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007000 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007001 // we formerly checked for a callback handler (non-0 tid),
7002 // but that is no longer required for TRANSFER_OBTAIN mode
7003 //
Glenn Kasten74105912014-07-03 12:28:53 -07007004 // frame count is not specified, or is exactly the pipe depth
7005 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007006 // PCM data
7007 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007008 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007009 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007010 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007011 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007012 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007013 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007014 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007015 hasFastCapture() &&
7016 // there are sufficient fast track slots available
7017 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007018 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007019 // check compatibility with audio effects.
7020 Mutex::Autolock _l(mLock);
7021 // Do not accept FAST flag if the session has software effects
7022 sp<EffectChain> chain = getEffectChain_l(sessionId);
7023 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007024 audio_input_flags_t old = *flags;
7025 chain->checkInputFlagCompatibility(flags);
7026 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007027 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7028 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007029 }
7030 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007031 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007032 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7033 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007034 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007035 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7036 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007037 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007038 this, frameCount, mFrameCount, mPipeFramesP2,
7039 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007040 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007041 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007042 }
7043 }
7044
Eric Laurentf14db3c2017-12-08 14:20:36 -08007045 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7046 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7047 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7048 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7049 lStatus = BAD_TYPE;
7050 goto Exit;
7051 }
7052
Glenn Kasten74105912014-07-03 12:28:53 -07007053 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007054 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007055 // fast track: frame count is exactly the pipe depth
7056 frameCount = mPipeFramesP2;
7057 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007058 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007059 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007060 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7061 // or 20 ms if there is a fast capture
7062 // TODO This could be a roundupRatio inline, and const
7063 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7064 * sampleRate + mSampleRate - 1) / mSampleRate;
7065 // minimum number of notification periods is at least kMinNotifications,
7066 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7067 static const size_t kMinNotifications = 3;
7068 static const uint32_t kMinMs = 30;
7069 // TODO This could be a roundupRatio inline
7070 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7071 // TODO This could be a roundupRatio inline
7072 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7073 maxNotificationFrames;
7074 const size_t minFrameCount = maxNotificationFrames *
7075 max(kMinNotifications, minNotificationsByMs);
7076 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007077 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7078 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007079 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007080 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007081 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007082 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007083
7084 { // scope for mLock
7085 Mutex::Autolock _l(mLock);
7086
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007087 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007088 format, channelMask, frameCount,
7089 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007090 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007091
Glenn Kasten03003332013-08-06 15:40:54 -07007092 lStatus = track->initCheck();
7093 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007094 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007095 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007096 goto Exit;
7097 }
7098 mTracks.add(track);
7099
Eric Laurent05067782016-06-01 18:27:28 -07007100 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007101 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7102 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7103 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007104 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007105 }
Eric Laurent81784c32012-11-19 14:55:58 -08007106 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007107
Eric Laurent81784c32012-11-19 14:55:58 -08007108 lStatus = NO_ERROR;
7109
7110Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007111 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007112 return track;
7113}
7114
7115status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7116 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007117 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007118{
7119 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7120 sp<ThreadBase> strongMe = this;
7121 status_t status = NO_ERROR;
7122
7123 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007124 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007125 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007126 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007127 triggerSession,
7128 recordTrack->sessionId(),
7129 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007130 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007131 // Sync event can be cancelled by the trigger session if the track is not in a
7132 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007133 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007134 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007135 } else {
7136 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007137 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007138 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007139 }
7140 }
7141
7142 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007143 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007144 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007145 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7146 if (recordTrack->mState == TrackBase::PAUSING) {
7147 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007148 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007149 } else {
7150 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007151 }
7152 return status;
7153 }
7154
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007155 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7156 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7157 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007158 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007159 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007160 status_t status = NO_ERROR;
7161 if (recordTrack->isExternalTrack()) {
7162 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007163 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007164 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007165 mLock.lock();
7166 // FIXME should verify that recordTrack is still in mActiveTracks
7167 if (status != NO_ERROR) {
7168 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007169 recordTrack->clearSyncStartEvent();
7170 ALOGV("RecordThread::start error %d", status);
7171 return status;
7172 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007173 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007174 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007175 // Catch up with current buffer indices if thread is already running.
7176 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7177 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7178 // see previously buffered data before it called start(), but with greater risk of overrun.
7179
Andy Hung73c02e42015-03-29 01:13:58 -07007180 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07007181 // clear any converter state as new data will be discontinuous
7182 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007184 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007185 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007186 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007187 ALOGV("Record failed to start");
7188 status = BAD_VALUE;
7189 goto startError;
7190 }
Eric Laurent81784c32012-11-19 14:55:58 -08007191 return status;
7192 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007193
Eric Laurent81784c32012-11-19 14:55:58 -08007194startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007195 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007196 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007197 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007198 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007199 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007200 return status;
7201}
7202
Eric Laurent81784c32012-11-19 14:55:58 -08007203void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7204{
7205 sp<SyncEvent> strongEvent = event.promote();
7206
7207 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007208 sp<RefBase> ptr = strongEvent->cookie().promote();
7209 if (ptr != 0) {
7210 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7211 recordTrack->handleSyncStartEvent(strongEvent);
7212 }
Eric Laurent81784c32012-11-19 14:55:58 -08007213 }
7214}
7215
Glenn Kastena8356f62013-07-25 14:37:52 -07007216bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007217 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007218 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007219 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007220 return false;
7221 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007222 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007223 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007224 // signal thread to stop
7225 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007226 // do not wait for mStartStopCond if exiting
7227 if (exitPending()) {
7228 return true;
7229 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007230 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007231 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007232 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007233 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007234 ALOGV("Record stopped OK");
7235 return true;
7236 }
7237 return false;
7238}
7239
Glenn Kasten0f11b512014-01-31 16:18:54 -08007240bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007241{
7242 return false;
7243}
7244
Glenn Kasten0f11b512014-01-31 16:18:54 -08007245status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007246{
7247#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7248 if (!isValidSyncEvent(event)) {
7249 return BAD_VALUE;
7250 }
7251
Glenn Kastend848eb42016-03-08 13:42:11 -08007252 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007253 status_t ret = NAME_NOT_FOUND;
7254
7255 Mutex::Autolock _l(mLock);
7256
7257 for (size_t i = 0; i < mTracks.size(); i++) {
7258 sp<RecordTrack> track = mTracks[i];
7259 if (eventSession == track->sessionId()) {
7260 (void) track->setSyncEvent(event);
7261 ret = NO_ERROR;
7262 }
7263 }
7264 return ret;
7265#else
7266 return BAD_VALUE;
7267#endif
7268}
7269
jiabin653cc0a2018-01-17 17:54:10 -08007270status_t AudioFlinger::RecordThread::getActiveMicrophones(
7271 std::vector<media::MicrophoneInfo>* activeMicrophones)
7272{
7273 ALOGV("RecordThread::getActiveMicrophones");
7274 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007275 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7276 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007277}
7278
Kevin Rocard069c2712018-03-29 19:09:14 -07007279void AudioFlinger::RecordThread::updateMetadata_l()
7280{
7281 if (mInput == nullptr || mInput->stream == nullptr ||
7282 !mActiveTracks.readAndClearHasChanged()) {
7283 return;
7284 }
7285 StreamInHalInterface::SinkMetadata metadata;
7286 for (const sp<RecordTrack> &track : mActiveTracks) {
7287 // No track is invalid as this is called after prepareTrack_l in the same critical section
7288 metadata.tracks.push_back({
7289 .source = track->attributes().source,
7290 .gain = 1, // capture tracks do not have volumes
7291 });
7292 }
7293 mInput->stream->updateSinkMetadata(metadata);
7294}
7295
Eric Laurent81784c32012-11-19 14:55:58 -08007296// destroyTrack_l() must be called with ThreadBase::mLock held
7297void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7298{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007299 track->terminate();
7300 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007301 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007302 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007303 removeTrack_l(track);
7304 }
7305}
7306
7307void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7308{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007309 String8 result;
7310 track->appendDump(result, false /* active */);
7311 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7312
Eric Laurent81784c32012-11-19 14:55:58 -08007313 mTracks.remove(track);
7314 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007315 if (track->isFastTrack()) {
7316 ALOG_ASSERT(!mFastTrackAvail);
7317 mFastTrackAvail = true;
7318 }
Eric Laurent81784c32012-11-19 14:55:58 -08007319}
7320
7321void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7322{
7323 dumpInternals(fd, args);
7324 dumpTracks(fd, args);
7325 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007326 dprintf(fd, " Local log:\n");
7327 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007328}
7329
7330void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7331{
Glenn Kasten44182c22015-03-05 17:12:23 -08007332 dumpBase(fd, args);
7333
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007334 AudioStreamIn *input = mInput;
7335 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7336 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7337 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007338 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007339 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007340 }
Andy Hungbfa64962017-06-12 14:43:19 -07007341
7342 if (input != nullptr) {
7343 dprintf(fd, " Hal stream dump:\n");
7344 (void)input->stream->dump(fd);
7345 }
7346
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007347 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007348 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007349
Glenn Kasten2f90c512015-12-02 11:40:09 -08007350 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7351 // while we are dumping it. It may be inconsistent, but it won't mutate!
7352 // This is a large object so we place it on the heap.
7353 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7354 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7355 copy->dump(fd);
7356 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007357}
7358
Glenn Kasten0f11b512014-01-31 16:18:54 -08007359void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007360{
Eric Laurent81784c32012-11-19 14:55:58 -08007361 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007362 size_t numtracks = mTracks.size();
7363 size_t numactive = mActiveTracks.size();
7364 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007365 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007366 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007367 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007368 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007369 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007370 RecordTrack::appendDumpHeader(result);
7371 for (size_t i = 0; i < numtracks ; ++i) {
7372 sp<RecordTrack> track = mTracks[i];
7373 if (track != 0) {
7374 bool active = mActiveTracks.indexOf(track) >= 0;
7375 if (active) {
7376 numactiveseen++;
7377 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007378 result.append(prefix);
7379 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007380 }
Eric Laurent81784c32012-11-19 14:55:58 -08007381 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007382 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007383 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007384 }
7385
Marco Nelissenb2208842014-02-07 14:00:50 -08007386 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007387 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007388 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007389 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007390 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007391 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007392 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007393 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007394 result.append(prefix);
7395 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007396 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007397 }
Eric Laurent81784c32012-11-19 14:55:58 -08007398
7399 }
7400 write(fd, result.string(), result.size());
7401}
7402
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007403void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7404{
7405 Mutex::Autolock _l(mLock);
7406 for (size_t i = 0; i < mTracks.size() ; i++) {
7407 sp<RecordTrack> track = mTracks[i];
7408 if (track != 0 && track->uid() == uid) {
7409 track->setSilenced(silenced);
7410 }
7411 }
7412}
Andy Hung73c02e42015-03-29 01:13:58 -07007413
7414void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7415{
7416 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7417 RecordThread *recordThread = (RecordThread *) threadBase.get();
7418 mRsmpInFront = recordThread->mRsmpInRear;
7419 mRsmpInUnrel = 0;
7420}
7421
7422void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7423 size_t *framesAvailable, bool *hasOverrun)
7424{
7425 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7426 RecordThread *recordThread = (RecordThread *) threadBase.get();
7427 const int32_t rear = recordThread->mRsmpInRear;
7428 const int32_t front = mRsmpInFront;
7429 const ssize_t filled = rear - front;
7430
7431 size_t framesIn;
7432 bool overrun = false;
7433 if (filled < 0) {
7434 // should not happen, but treat like a massive overrun and re-sync
7435 framesIn = 0;
7436 mRsmpInFront = rear;
7437 overrun = true;
7438 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7439 framesIn = (size_t) filled;
7440 } else {
7441 // client is not keeping up with server, but give it latest data
7442 framesIn = recordThread->mRsmpInFrames;
7443 mRsmpInFront = /* front = */ rear - framesIn;
7444 overrun = true;
7445 }
7446 if (framesAvailable != NULL) {
7447 *framesAvailable = framesIn;
7448 }
7449 if (hasOverrun != NULL) {
7450 *hasOverrun = overrun;
7451 }
7452}
7453
Eric Laurent81784c32012-11-19 14:55:58 -08007454// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007455status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007456 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007457{
Andy Hung73c02e42015-03-29 01:13:58 -07007458 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007459 if (threadBase == 0) {
7460 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007461 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007462 return NOT_ENOUGH_DATA;
7463 }
7464 RecordThread *recordThread = (RecordThread *) threadBase.get();
7465 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007466 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007467 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007468 // FIXME should not be P2 (don't want to increase latency)
7469 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007470 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007471 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007472 front &= recordThread->mRsmpInFramesP2 - 1;
7473 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007474 if (part1 > (size_t) filled) {
7475 part1 = filled;
7476 }
7477 size_t ask = buffer->frameCount;
7478 ALOG_ASSERT(ask > 0);
7479 if (part1 > ask) {
7480 part1 = ask;
7481 }
7482 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007483 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007484 buffer->raw = NULL;
7485 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007486 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007487 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007488 }
7489
Andy Hung57446612015-04-19 23:56:46 -07007490 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007491 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007492 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007493 return NO_ERROR;
7494}
7495
7496// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007497void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7498 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007499{
Glenn Kasten85948432013-08-19 12:09:05 -07007500 size_t stepCount = buffer->frameCount;
7501 if (stepCount == 0) {
7502 return;
7503 }
Andy Hung73c02e42015-03-29 01:13:58 -07007504 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7505 mRsmpInUnrel -= stepCount;
7506 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007507 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007508 buffer->frameCount = 0;
7509}
7510
Eric Laurentd8365c52017-07-16 15:27:05 -07007511void AudioFlinger::RecordThread::checkBtNrec()
7512{
7513 Mutex::Autolock _l(mLock);
7514 checkBtNrec_l();
7515}
7516
7517void AudioFlinger::RecordThread::checkBtNrec_l()
7518{
7519 // disable AEC and NS if the device is a BT SCO headset supporting those
7520 // pre processings
7521 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7522 mAudioFlinger->btNrecIsOff();
7523 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7524 for (size_t i = 0; i < mEffectChains.size(); i++) {
7525 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7526 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7527 }
7528 }
7529}
7530
Andy Hung97a893e2015-03-29 01:03:07 -07007531
Eric Laurent10351942014-05-08 18:49:52 -07007532bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7533 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007534{
7535 bool reconfig = false;
7536
Eric Laurent10351942014-05-08 18:49:52 -07007537 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007538
Eric Laurent10351942014-05-08 18:49:52 -07007539 audio_format_t reqFormat = mFormat;
7540 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007541 // 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 -07007542 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7543
7544 AudioParameter param = AudioParameter(keyValuePair);
7545 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007546
7547 // scope for AutoPark extends to end of method
7548 AutoPark<FastCapture> park(mFastCapture);
7549
Eric Laurent10351942014-05-08 18:49:52 -07007550 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7551 // channel count change can be requested. Do we mandate the first client defines the
7552 // HAL sampling rate and channel count or do we allow changes on the fly?
7553 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7554 samplingRate = value;
7555 reconfig = true;
7556 }
7557 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007558 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007559 status = BAD_VALUE;
7560 } else {
7561 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007562 reconfig = true;
7563 }
Eric Laurent10351942014-05-08 18:49:52 -07007564 }
7565 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7566 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007567 if (!audio_is_input_channel(mask) ||
7568 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007569 status = BAD_VALUE;
7570 } else {
7571 channelMask = mask;
7572 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007573 }
Eric Laurent10351942014-05-08 18:49:52 -07007574 }
7575 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7576 // do not accept frame count changes if tracks are open as the track buffer
7577 // size depends on frame count and correct behavior would not be guaranteed
7578 // if frame count is changed after track creation
7579 if (mActiveTracks.size() > 0) {
7580 status = INVALID_OPERATION;
7581 } else {
7582 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007583 }
Eric Laurent10351942014-05-08 18:49:52 -07007584 }
7585 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7586 // forward device change to effects that have requested to be
7587 // aware of attached audio device.
7588 for (size_t i = 0; i < mEffectChains.size(); i++) {
7589 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007590 }
Eric Laurent81784c32012-11-19 14:55:58 -08007591
Eric Laurent10351942014-05-08 18:49:52 -07007592 // store input device and output device but do not forward output device to audio HAL.
7593 // Note that status is ignored by the caller for output device
7594 // (see AudioFlinger::setParameters()
7595 if (audio_is_output_devices(value)) {
7596 mOutDevice = value;
7597 status = BAD_VALUE;
7598 } else {
7599 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007600 if (value != AUDIO_DEVICE_NONE) {
7601 mPrevInDevice = value;
7602 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007603 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007604 }
Eric Laurent10351942014-05-08 18:49:52 -07007605 }
7606 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7607 mAudioSource != (audio_source_t)value) {
7608 // forward device change to effects that have requested to be
7609 // aware of attached audio device.
7610 for (size_t i = 0; i < mEffectChains.size(); i++) {
7611 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007612 }
Eric Laurent10351942014-05-08 18:49:52 -07007613 mAudioSource = (audio_source_t)value;
7614 }
Glenn Kastene198c362013-08-13 09:13:36 -07007615
Eric Laurent10351942014-05-08 18:49:52 -07007616 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007617 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007618 if (status == INVALID_OPERATION) {
7619 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007620 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007621 }
7622 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007623 if (status == BAD_VALUE) {
7624 uint32_t sRate;
7625 audio_channel_mask_t channelMask;
7626 audio_format_t format;
7627 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7628 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7629 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7630 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7631 status = NO_ERROR;
7632 }
Eric Laurent81784c32012-11-19 14:55:58 -08007633 }
Eric Laurent10351942014-05-08 18:49:52 -07007634 if (status == NO_ERROR) {
7635 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007636 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007637 }
7638 }
Eric Laurent81784c32012-11-19 14:55:58 -08007639 }
Eric Laurent10351942014-05-08 18:49:52 -07007640
Eric Laurent81784c32012-11-19 14:55:58 -08007641 return reconfig;
7642}
7643
7644String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7645{
Eric Laurent81784c32012-11-19 14:55:58 -08007646 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007647 if (initCheck() == NO_ERROR) {
7648 String8 out_s8;
7649 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7650 return out_s8;
7651 }
Eric Laurent81784c32012-11-19 14:55:58 -08007652 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007653 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007654}
7655
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007656void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007657 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7658
7659 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007660
7661 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007662 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007663 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007664 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007665 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007666 desc->mChannelMask = mChannelMask;
7667 desc->mSamplingRate = mSampleRate;
7668 desc->mFormat = mFormat;
7669 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007670 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007671 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007672 break;
7673
Eric Laurent73e26b62015-04-27 16:55:58 -07007674 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007675 default:
7676 break;
7677 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007678 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007679}
7680
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007681void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007682{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007683 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7684 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007685 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007686 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007687 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007688 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7689 result = mInput->stream->getFrameSize(&mFrameSize);
7690 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7691 result = mInput->stream->getBufferSize(&mBufferSize);
7692 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007693 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007694 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7695 "mBufferSize=%lld, mFrameCount=%lld",
7696 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7697 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007698 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007699 // 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 -07007700 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007701 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007702 // A larger value should allow more old data to be read after a track calls start(),
7703 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007704 //
7705 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007706 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007707 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007708 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007709 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007710
7711 // TODO optimize audio capture buffer sizes ...
7712 // Here we calculate the size of the sliding buffer used as a source
7713 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7714 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7715 // be better to have it derived from the pipe depth in the long term.
7716 // The current value is higher than necessary. However it should not add to latency.
7717
Glenn Kasten85948432013-08-19 12:09:05 -07007718 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007719 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7720 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007721 // if posix_memalign fails, will segv here.
7722 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007723
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007724 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7725 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007726}
7727
Glenn Kasten5f972c02014-01-13 09:59:31 -08007728uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007729{
7730 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007731 uint32_t result;
7732 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7733 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007734 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007735 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007736}
7737
Eric Laurent4c415062016-06-17 16:14:16 -07007738// hasAudioSession_l() must be called with ThreadBase::mLock held
7739uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007740{
Eric Laurent81784c32012-11-19 14:55:58 -08007741 uint32_t result = 0;
7742 if (getEffectChain_l(sessionId) != 0) {
7743 result = EFFECT_SESSION;
7744 }
7745
7746 for (size_t i = 0; i < mTracks.size(); ++i) {
7747 if (sessionId == mTracks[i]->sessionId()) {
7748 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007749 if (mTracks[i]->isFastTrack()) {
7750 result |= FAST_SESSION;
7751 }
Eric Laurent81784c32012-11-19 14:55:58 -08007752 break;
7753 }
7754 }
7755
7756 return result;
7757}
7758
Glenn Kastend848eb42016-03-08 13:42:11 -08007759KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007760{
Glenn Kastend848eb42016-03-08 13:42:11 -08007761 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007762 Mutex::Autolock _l(mLock);
7763 for (size_t j = 0; j < mTracks.size(); ++j) {
7764 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007765 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007766 if (ids.indexOfKey(sessionId) < 0) {
7767 ids.add(sessionId, true);
7768 }
7769 }
7770 return ids;
7771}
7772
7773AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7774{
7775 Mutex::Autolock _l(mLock);
7776 AudioStreamIn *input = mInput;
7777 mInput = NULL;
7778 return input;
7779}
7780
7781// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007782sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007783{
7784 if (mInput == NULL) {
7785 return NULL;
7786 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007787 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007788}
7789
7790status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7791{
7792 // only one chain per input thread
7793 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007794 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007795 return INVALID_OPERATION;
7796 }
7797 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007798 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007799 chain->setInBuffer(NULL);
7800 chain->setOutBuffer(NULL);
7801
7802 checkSuspendOnAddEffectChain_l(chain);
7803
Eric Laurent1b928682014-10-02 19:41:47 -07007804 // make sure enabled pre processing effects state is communicated to the HAL as we
7805 // just moved them to a new input stream.
7806 chain->syncHalEffectsState();
7807
Eric Laurent81784c32012-11-19 14:55:58 -08007808 mEffectChains.add(chain);
7809
7810 return NO_ERROR;
7811}
7812
7813size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7814{
7815 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7816 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007817 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007818 chain.get(), mEffectChains.size(), this);
7819 if (mEffectChains.size() == 1) {
7820 mEffectChains.removeAt(0);
7821 }
7822 return 0;
7823}
7824
Eric Laurent1c333e22014-05-20 10:48:17 -07007825status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7826 audio_patch_handle_t *handle)
7827{
7828 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007829
7830 // store new device and send to effects
7831 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007832 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007833 for (size_t i = 0; i < mEffectChains.size(); i++) {
7834 mEffectChains[i]->setDevice_l(mInDevice);
7835 }
7836
Eric Laurentd8365c52017-07-16 15:27:05 -07007837 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007838
7839 // store new source and send to effects
7840 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7841 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007842 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007843 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007844 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007845 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007846
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007847 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007848 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7849 status = hwDevice->createAudioPatch(patch->num_sources,
7850 patch->sources,
7851 patch->num_sinks,
7852 patch->sinks,
7853 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007854 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007855 char *address;
7856 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7857 address = audio_device_address_to_parameter(
7858 patch->sources[0].ext.device.type,
7859 patch->sources[0].ext.device.address);
7860 } else {
7861 address = (char *)calloc(1, 1);
7862 }
7863 AudioParameter param = AudioParameter(String8(address));
7864 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007865 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007866 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007867 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007868 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007869 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007870 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007871 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007872
Eric Laurente8726fe2015-06-26 09:39:24 -07007873 if (mInDevice != mPrevInDevice) {
7874 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7875 mPrevInDevice = mInDevice;
7876 }
Eric Laurent296fb132015-05-01 11:38:42 -07007877
Eric Laurent1c333e22014-05-20 10:48:17 -07007878 return status;
7879}
7880
7881status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7882{
7883 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007884
7885 mInDevice = AUDIO_DEVICE_NONE;
7886
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007887 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007888 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7889 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007890 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007891 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007892 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007893 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007894 }
7895 return status;
7896}
7897
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007898void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007899{
7900 Mutex::Autolock _l(mLock);
7901 mTracks.add(record);
7902}
7903
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007904void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007905{
7906 Mutex::Autolock _l(mLock);
7907 destroyTrack_l(record);
7908}
7909
Mikhail Naganovdc769682018-05-04 15:34:08 -07007910void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07007911{
Mikhail Naganovdc769682018-05-04 15:34:08 -07007912 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07007913 config->role = AUDIO_PORT_ROLE_SINK;
7914 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7915 config->ext.mix.usecase.source = mAudioSource;
7916}
Eric Laurent1c333e22014-05-20 10:48:17 -07007917
Eric Laurent6acd1d42017-01-04 14:23:29 -08007918// ----------------------------------------------------------------------------
7919// Mmap
7920// ----------------------------------------------------------------------------
7921
7922AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7923 : mThread(thread)
7924{
Phil Burk9fabbf82017-08-03 12:02:00 -07007925 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007926}
7927
7928AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7929{
Phil Burk9fabbf82017-08-03 12:02:00 -07007930 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007931}
7932
7933status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7934 struct audio_mmap_buffer_info *info)
7935{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007936 return mThread->createMmapBuffer(minSizeFrames, info);
7937}
7938
7939status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7940{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007941 return mThread->getMmapPosition(position);
7942}
7943
Eric Laurenta54f1282017-07-01 19:39:32 -07007944status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007945 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007946
7947{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007948 return mThread->start(client, handle);
7949}
7950
7951status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7952{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007953 return mThread->stop(handle);
7954}
7955
Eric Laurent18b57012017-02-13 16:23:52 -08007956status_t AudioFlinger::MmapThreadHandle::standby()
7957{
Eric Laurent18b57012017-02-13 16:23:52 -08007958 return mThread->standby();
7959}
7960
Eric Laurent6acd1d42017-01-04 14:23:29 -08007961
7962AudioFlinger::MmapThread::MmapThread(
7963 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7964 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7965 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7966 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007967 mSessionId(AUDIO_SESSION_NONE),
7968 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007969 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07007970 mActiveTracks(&this->mLocalLog),
7971 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
7972 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007973{
Eric Laurent18b57012017-02-13 16:23:52 -08007974 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007975 readHalParameters_l();
7976}
7977
7978AudioFlinger::MmapThread::~MmapThread()
7979{
Eric Laurent18b57012017-02-13 16:23:52 -08007980 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007981}
7982
7983void AudioFlinger::MmapThread::onFirstRef()
7984{
7985 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7986}
7987
7988void AudioFlinger::MmapThread::disconnect()
7989{
Eric Laurent331679c2018-04-16 17:03:16 -07007990 ActiveTracks<MmapTrack> activeTracks;
7991 {
7992 Mutex::Autolock _l(mLock);
7993 for (const sp<MmapTrack> &t : mActiveTracks) {
7994 activeTracks.add(t);
7995 }
7996 }
7997 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007998 stop(t->portId());
7999 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008000 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008001 if (isOutput()) {
8002 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
8003 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008004 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008005 }
8006}
8007
8008
8009void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8010 audio_stream_type_t streamType __unused,
8011 audio_session_t sessionId,
8012 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008013 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008014 audio_port_handle_t portId)
8015{
8016 mAttr = *attr;
8017 mSessionId = sessionId;
8018 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008019 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008020 mPortId = portId;
8021}
8022
8023status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8024 struct audio_mmap_buffer_info *info)
8025{
8026 if (mHalStream == 0) {
8027 return NO_INIT;
8028 }
Eric Laurent18b57012017-02-13 16:23:52 -08008029 mStandby = true;
8030 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008031 return mHalStream->createMmapBuffer(minSizeFrames, info);
8032}
8033
8034status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8035{
8036 if (mHalStream == 0) {
8037 return NO_INIT;
8038 }
8039 return mHalStream->getMmapPosition(position);
8040}
8041
Eric Laurent331679c2018-04-16 17:03:16 -07008042status_t AudioFlinger::MmapThread::exitStandby()
8043{
8044 status_t ret = mHalStream->start();
8045 if (ret != NO_ERROR) {
8046 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8047 return ret;
8048 }
8049 mStandby = false;
8050 return NO_ERROR;
8051}
8052
Eric Laurenta54f1282017-07-01 19:39:32 -07008053status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008054 audio_port_handle_t *handle)
8055{
Eric Laurenta54f1282017-07-01 19:39:32 -07008056 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8057 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008058 if (mHalStream == 0) {
8059 return NO_INIT;
8060 }
8061
8062 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008063
Eric Laurenta54f1282017-07-01 19:39:32 -07008064 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008065 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008066 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008067 }
8068
8069 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8070
8071 audio_io_handle_t io = mId;
8072 if (isOutput()) {
8073 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8074 config.sample_rate = mSampleRate;
8075 config.channel_mask = mChannelMask;
8076 config.format = mFormat;
8077 audio_stream_type_t stream = streamType();
8078 audio_output_flags_t flags =
8079 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008080 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008081 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8082 mSessionId,
8083 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008084 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008085 client.clientUid,
8086 &config,
8087 flags,
8088 &deviceId,
8089 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008090 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008091 audio_config_base_t config;
8092 config.sample_rate = mSampleRate;
8093 config.channel_mask = mChannelMask;
8094 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008095 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008096 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8097 mSessionId,
8098 client.clientPid,
8099 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008100 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008101 &config,
8102 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8103 &deviceId,
8104 &portId);
8105 }
8106 // APM should not chose a different input or output stream for the same set of attributes
8107 // and audo configuration
8108 if (ret != NO_ERROR || io != mId) {
8109 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8110 __FUNCTION__, ret, io, mId);
8111 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008112 }
8113
Eric Laurent331679c2018-04-16 17:03:16 -07008114 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008115 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008116 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008117 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008118 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008119 }
8120
Eric Laurent331679c2018-04-16 17:03:16 -07008121 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008122 // abort if start is rejected by audio policy manager
8123 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008124 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008125 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008126 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008127 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008128 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008129 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008130 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008131 }
Eric Laurent331679c2018-04-16 17:03:16 -07008132 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008133 } else {
8134 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008135 }
8136 return PERMISSION_DENIED;
8137 }
8138
Eric Laurent67f97292018-04-20 18:05:41 -07008139 if (isOutput()) {
8140 // force volume update when a new track is added
8141 mHalVolFloat = -1.0f;
8142 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008143 for (const sp<MmapTrack> &track : mActiveTracks) {
8144 if (track->isSilenced_l() && track->uid() != client.clientUid)
8145 track->invalidate();
8146 }
8147 }
8148
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008149 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8150 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -07008151 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008152
Eric Laurent331679c2018-04-16 17:03:16 -07008153 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008154 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008155 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008156 if (chain != 0) {
8157 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8158 chain->incTrackCnt();
8159 chain->incActiveTrackCnt();
8160 }
8161
8162 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008163 broadcast_l();
8164
Eric Laurenta54f1282017-07-01 19:39:32 -07008165 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008166
8167 return NO_ERROR;
8168}
8169
8170status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8171{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008172 ALOGV("%s handle %d", __FUNCTION__, handle);
8173
8174 if (mHalStream == 0) {
8175 return NO_INIT;
8176 }
8177
Eric Laurenta54f1282017-07-01 19:39:32 -07008178 if (handle == mPortId) {
8179 mHalStream->stop();
8180 return NO_ERROR;
8181 }
8182
Eric Laurent331679c2018-04-16 17:03:16 -07008183 Mutex::Autolock _l(mLock);
8184
Eric Laurent6acd1d42017-01-04 14:23:29 -08008185 sp<MmapTrack> track;
8186 for (const sp<MmapTrack> &t : mActiveTracks) {
8187 if (handle == t->portId()) {
8188 track = t;
8189 break;
8190 }
8191 }
8192 if (track == 0) {
8193 return BAD_VALUE;
8194 }
8195
8196 mActiveTracks.remove(track);
8197
Eric Laurent331679c2018-04-16 17:03:16 -07008198 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008199 if (isOutput()) {
8200 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008201 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008202 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008203 AudioSystem::stopInput(track->portId());
8204 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008205 }
Eric Laurent331679c2018-04-16 17:03:16 -07008206 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008207
8208 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8209 if (chain != 0) {
8210 chain->decActiveTrackCnt();
8211 chain->decTrackCnt();
8212 }
8213
8214 broadcast_l();
8215
Eric Laurent6acd1d42017-01-04 14:23:29 -08008216 return NO_ERROR;
8217}
8218
Eric Laurent18b57012017-02-13 16:23:52 -08008219status_t AudioFlinger::MmapThread::standby()
8220{
8221 ALOGV("%s", __FUNCTION__);
8222
8223 if (mHalStream == 0) {
8224 return NO_INIT;
8225 }
8226 if (mActiveTracks.size() != 0) {
8227 return INVALID_OPERATION;
8228 }
8229 mHalStream->standby();
8230 mStandby = true;
8231 releaseWakeLock();
8232 return NO_ERROR;
8233}
8234
Eric Laurent6acd1d42017-01-04 14:23:29 -08008235
8236void AudioFlinger::MmapThread::readHalParameters_l()
8237{
8238 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8239 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8240 mFormat = mHALFormat;
8241 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8242 result = mHalStream->getFrameSize(&mFrameSize);
8243 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8244 result = mHalStream->getBufferSize(&mBufferSize);
8245 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8246 mFrameCount = mBufferSize / mFrameSize;
8247}
8248
8249bool AudioFlinger::MmapThread::threadLoop()
8250{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008251 checkSilentMode_l();
8252
8253 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8254
8255 while (!exitPending())
8256 {
8257 Mutex::Autolock _l(mLock);
8258 Vector< sp<EffectChain> > effectChains;
8259
8260 if (mSignalPending) {
8261 // A signal was raised while we were unlocked
8262 mSignalPending = false;
8263 } else {
8264 if (mConfigEvents.isEmpty()) {
8265 // we're about to wait, flush the binder command buffer
8266 IPCThreadState::self()->flushCommands();
8267
8268 if (exitPending()) {
8269 break;
8270 }
8271
Eric Laurent6acd1d42017-01-04 14:23:29 -08008272 // wait until we have something to do...
8273 ALOGV("%s going to sleep", myName.string());
8274 mWaitWorkCV.wait(mLock);
8275 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008276
8277 checkSilentMode_l();
8278
8279 continue;
8280 }
8281 }
8282
8283 processConfigEvents_l();
8284
8285 processVolume_l();
8286
8287 checkInvalidTracks_l();
8288
8289 mActiveTracks.updatePowerState(this);
8290
Kevin Rocard069c2712018-03-29 19:09:14 -07008291 updateMetadata_l();
8292
Eric Laurent6acd1d42017-01-04 14:23:29 -08008293 lockEffectChains_l(effectChains);
8294 for (size_t i = 0; i < effectChains.size(); i ++) {
8295 effectChains[i]->process_l();
8296 }
8297 // enable changes in effect chain
8298 unlockEffectChains(effectChains);
8299 // Effect chains will be actually deleted here if they were removed from
8300 // mEffectChains list during mixing or effects processing
8301 }
8302
8303 threadLoop_exit();
8304
8305 if (!mStandby) {
8306 threadLoop_standby();
8307 mStandby = true;
8308 }
8309
Eric Laurent6acd1d42017-01-04 14:23:29 -08008310 ALOGV("Thread %p type %d exiting", this, mType);
8311 return false;
8312}
8313
8314// checkForNewParameter_l() must be called with ThreadBase::mLock held
8315bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8316 status_t& status)
8317{
8318 AudioParameter param = AudioParameter(keyValuePair);
8319 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008320 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008321 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008322 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008323 // forward device change to effects that have requested to be
8324 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008325 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008326 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008327 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008328 }
8329 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008330 if (audio_is_output_devices(device)) {
8331 mOutDevice = device;
8332 if (!isOutput()) {
8333 sendToHal = false;
8334 }
8335 } else {
8336 mInDevice = device;
8337 if (device != AUDIO_DEVICE_NONE) {
8338 mPrevInDevice = value;
8339 }
8340 // TODO: implement and call checkBtNrec_l();
8341 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008342 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008343 if (sendToHal) {
8344 status = mHalStream->setParameters(keyValuePair);
8345 } else {
8346 status = NO_ERROR;
8347 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008348
8349 return false;
8350}
8351
8352String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8353{
8354 Mutex::Autolock _l(mLock);
8355 String8 out_s8;
8356 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8357 return out_s8;
8358 }
8359 return String8();
8360}
8361
8362void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8363 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8364
8365 desc->mIoHandle = mId;
8366
8367 switch (event) {
8368 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008369 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008370 case AUDIO_INPUT_CONFIG_CHANGED:
8371 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008372 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008373 case AUDIO_OUTPUT_CONFIG_CHANGED:
8374 desc->mPatch = mPatch;
8375 desc->mChannelMask = mChannelMask;
8376 desc->mSamplingRate = mSampleRate;
8377 desc->mFormat = mFormat;
8378 desc->mFrameCount = mFrameCount;
8379 desc->mFrameCountHAL = mFrameCount;
8380 desc->mLatency = 0;
8381 break;
8382
8383 case AUDIO_INPUT_CLOSED:
8384 case AUDIO_OUTPUT_CLOSED:
8385 default:
8386 break;
8387 }
8388 mAudioFlinger->ioConfigChanged(event, desc, pid);
8389}
8390
8391status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8392 audio_patch_handle_t *handle)
8393{
8394 status_t status = NO_ERROR;
8395
8396 // store new device and send to effects
8397 audio_devices_t type = AUDIO_DEVICE_NONE;
8398 audio_port_handle_t deviceId;
8399 if (isOutput()) {
8400 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8401 type |= patch->sinks[i].ext.device.type;
8402 }
8403 deviceId = patch->sinks[0].id;
8404 } else {
8405 type = patch->sources[0].ext.device.type;
8406 deviceId = patch->sources[0].id;
8407 }
8408
8409 for (size_t i = 0; i < mEffectChains.size(); i++) {
8410 mEffectChains[i]->setDevice_l(type);
8411 }
8412
8413 if (isOutput()) {
8414 mOutDevice = type;
8415 } else {
8416 mInDevice = type;
8417 // store new source and send to effects
8418 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8419 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8420 for (size_t i = 0; i < mEffectChains.size(); i++) {
8421 mEffectChains[i]->setAudioSource_l(mAudioSource);
8422 }
8423 }
8424 }
8425
8426 if (mAudioHwDev->supportsAudioPatches()) {
8427 status = mHalDevice->createAudioPatch(patch->num_sources,
8428 patch->sources,
8429 patch->num_sinks,
8430 patch->sinks,
8431 handle);
8432 } else {
8433 char *address;
8434 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8435 //FIXME: we only support address on first sink with HAL version < 3.0
8436 address = audio_device_address_to_parameter(
8437 patch->sinks[0].ext.device.type,
8438 patch->sinks[0].ext.device.address);
8439 } else {
8440 address = (char *)calloc(1, 1);
8441 }
8442 AudioParameter param = AudioParameter(String8(address));
8443 free(address);
8444 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8445 if (!isOutput()) {
8446 param.addInt(String8(AudioParameter::keyInputSource),
8447 (int)patch->sinks[0].ext.mix.usecase.source);
8448 }
8449 status = mHalStream->setParameters(param.toString());
8450 *handle = AUDIO_PATCH_HANDLE_NONE;
8451 }
8452
8453 if (isOutput() && mPrevOutDevice != mOutDevice) {
8454 mPrevOutDevice = type;
8455 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008456 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008457 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008458 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008459 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008460 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008461 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008462 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008463 }
8464 if (!isOutput() && mPrevInDevice != mInDevice) {
8465 mPrevInDevice = type;
8466 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008467 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008468 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008469 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008470 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008471 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008472 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008473 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008474 }
8475 return status;
8476}
8477
8478status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8479{
8480 status_t status = NO_ERROR;
8481
8482 mInDevice = AUDIO_DEVICE_NONE;
8483
8484 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8485 supportsAudioPatches : false;
8486
8487 if (supportsAudioPatches) {
8488 status = mHalDevice->releaseAudioPatch(handle);
8489 } else {
8490 AudioParameter param;
8491 param.addInt(String8(AudioParameter::keyRouting), 0);
8492 status = mHalStream->setParameters(param.toString());
8493 }
8494 return status;
8495}
8496
Mikhail Naganovdc769682018-05-04 15:34:08 -07008497void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008498{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008499 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008500 if (isOutput()) {
8501 config->role = AUDIO_PORT_ROLE_SOURCE;
8502 config->ext.mix.hw_module = mAudioHwDev->handle();
8503 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8504 } else {
8505 config->role = AUDIO_PORT_ROLE_SINK;
8506 config->ext.mix.hw_module = mAudioHwDev->handle();
8507 config->ext.mix.usecase.source = mAudioSource;
8508 }
8509}
8510
8511status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8512{
8513 audio_session_t session = chain->sessionId();
8514
8515 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8516 // Attach all tracks with same session ID to this chain.
8517 // indicate all active tracks in the chain
8518 for (const sp<MmapTrack> &track : mActiveTracks) {
8519 if (session == track->sessionId()) {
8520 chain->incTrackCnt();
8521 chain->incActiveTrackCnt();
8522 }
8523 }
8524
8525 chain->setThread(this);
8526 chain->setInBuffer(nullptr);
8527 chain->setOutBuffer(nullptr);
8528 chain->syncHalEffectsState();
8529
8530 mEffectChains.add(chain);
8531 checkSuspendOnAddEffectChain_l(chain);
8532 return NO_ERROR;
8533}
8534
8535size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8536{
8537 audio_session_t session = chain->sessionId();
8538
8539 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8540
8541 for (size_t i = 0; i < mEffectChains.size(); i++) {
8542 if (chain == mEffectChains[i]) {
8543 mEffectChains.removeAt(i);
8544 // detach all active tracks from the chain
8545 // detach all tracks with same session ID from this chain
8546 for (const sp<MmapTrack> &track : mActiveTracks) {
8547 if (session == track->sessionId()) {
8548 chain->decActiveTrackCnt();
8549 chain->decTrackCnt();
8550 }
8551 }
8552 break;
8553 }
8554 }
8555 return mEffectChains.size();
8556}
8557
8558// hasAudioSession_l() must be called with ThreadBase::mLock held
8559uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8560{
8561 uint32_t result = 0;
8562 if (getEffectChain_l(sessionId) != 0) {
8563 result = EFFECT_SESSION;
8564 }
8565
8566 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8567 sp<MmapTrack> track = mActiveTracks[i];
8568 if (sessionId == track->sessionId()) {
8569 result |= TRACK_SESSION;
8570 if (track->isFastTrack()) {
8571 result |= FAST_SESSION;
8572 }
8573 break;
8574 }
8575 }
8576
8577 return result;
8578}
8579
8580void AudioFlinger::MmapThread::threadLoop_standby()
8581{
8582 mHalStream->standby();
8583}
8584
8585void AudioFlinger::MmapThread::threadLoop_exit()
8586{
Phil Burk7dce7282017-09-27 13:51:41 -07008587 // Do not call callback->onTearDown() because it is redundant for thread exit
8588 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008589}
8590
8591status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8592{
8593 return BAD_VALUE;
8594}
8595
8596bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8597{
8598 return false;
8599}
8600
8601status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8602 const effect_descriptor_t *desc, audio_session_t sessionId)
8603{
8604 // No global effect sessions on mmap threads
8605 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8606 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8607 desc->name, mThreadName);
8608 return BAD_VALUE;
8609 }
8610
8611 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8612 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8613 desc->name);
8614 return BAD_VALUE;
8615 }
8616 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008617 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8618 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008619 return BAD_VALUE;
8620 }
8621
8622 // Only allow effects without processing load or latency
8623 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8624 return BAD_VALUE;
8625 }
8626
8627 return NO_ERROR;
8628
8629}
8630
8631void AudioFlinger::MmapThread::checkInvalidTracks_l()
8632{
8633 for (const sp<MmapTrack> &track : mActiveTracks) {
8634 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008635 sp<MmapStreamCallback> callback = mCallback.promote();
8636 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008637 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008638 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008639 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008640 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8641 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8642 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008643 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008644 }
8645 }
8646}
8647
8648void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8649{
8650 dumpInternals(fd, args);
8651 dumpTracks(fd, args);
8652 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008653 dprintf(fd, " Local log:\n");
8654 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008655}
8656
8657void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8658{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008659 dumpBase(fd, args);
8660
8661 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8662 mAttr.content_type, mAttr.usage, mAttr.source);
8663 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8664 if (mActiveTracks.size() == 0) {
8665 dprintf(fd, " No active clients\n");
8666 }
8667}
8668
8669void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8670{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008671 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008672 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008673 dprintf(fd, " %zu Tracks\n", numtracks);
8674 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008675 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008676 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008677 MmapTrack::appendDumpHeader(result);
8678 for (size_t i = 0; i < numtracks ; ++i) {
8679 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008680 result.append(prefix);
8681 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008682 }
8683 } else {
8684 dprintf(fd, "\n");
8685 }
8686 write(fd, result.string(), result.size());
8687}
8688
8689AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8690 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8691 AudioHwDevice *hwDev, AudioStreamOut *output,
8692 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8693 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8694 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008695 mStreamVolume(1.0),
8696 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008697 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008698{
8699 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8700 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8701 mMasterVolume = audioFlinger->masterVolume_l();
8702 mMasterMute = audioFlinger->masterMute_l();
8703 if (mAudioHwDev) {
8704 if (mAudioHwDev->canSetMasterVolume()) {
8705 mMasterVolume = 1.0;
8706 }
8707
8708 if (mAudioHwDev->canSetMasterMute()) {
8709 mMasterMute = false;
8710 }
8711 }
8712}
8713
8714void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8715 audio_stream_type_t streamType,
8716 audio_session_t sessionId,
8717 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008718 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008719 audio_port_handle_t portId)
8720{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008721 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008722 mStreamType = streamType;
8723}
8724
8725AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8726{
8727 Mutex::Autolock _l(mLock);
8728 AudioStreamOut *output = mOutput;
8729 mOutput = NULL;
8730 return output;
8731}
8732
8733void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8734{
8735 Mutex::Autolock _l(mLock);
8736 // Don't apply master volume in SW if our HAL can do it for us.
8737 if (mAudioHwDev &&
8738 mAudioHwDev->canSetMasterVolume()) {
8739 mMasterVolume = 1.0;
8740 } else {
8741 mMasterVolume = value;
8742 }
8743}
8744
8745void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8746{
8747 Mutex::Autolock _l(mLock);
8748 // Don't apply master mute in SW if our HAL can do it for us.
8749 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8750 mMasterMute = false;
8751 } else {
8752 mMasterMute = muted;
8753 }
8754}
8755
8756void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8757{
8758 Mutex::Autolock _l(mLock);
8759 if (stream == mStreamType) {
8760 mStreamVolume = value;
8761 broadcast_l();
8762 }
8763}
8764
8765float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8766{
8767 Mutex::Autolock _l(mLock);
8768 if (stream == mStreamType) {
8769 return mStreamVolume;
8770 }
8771 return 0.0f;
8772}
8773
8774void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8775{
8776 Mutex::Autolock _l(mLock);
8777 if (stream == mStreamType) {
8778 mStreamMute= muted;
8779 broadcast_l();
8780 }
8781}
8782
8783void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8784{
8785 Mutex::Autolock _l(mLock);
8786 if (streamType == mStreamType) {
8787 for (const sp<MmapTrack> &track : mActiveTracks) {
8788 track->invalidate();
8789 }
8790 broadcast_l();
8791 }
8792}
8793
8794void AudioFlinger::MmapPlaybackThread::processVolume_l()
8795{
8796 float volume;
8797
8798 if (mMasterMute || mStreamMute) {
8799 volume = 0;
8800 } else {
8801 volume = mMasterVolume * mStreamVolume;
8802 }
8803
8804 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008805
8806 // Convert volumes from float to 8.24
8807 uint32_t vol = (uint32_t)(volume * (1 << 24));
8808
8809 // Delegate volume control to effect in track effect chain if needed
8810 // only one effect chain can be present on DirectOutputThread, so if
8811 // there is one, the track is connected to it
8812 if (!mEffectChains.isEmpty()) {
8813 mEffectChains[0]->setVolume_l(&vol, &vol);
8814 volume = (float)vol / (1 << 24);
8815 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008816 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008817 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8818 mHalVolFloat = volume; // HW volume control worked, so update value.
8819 mNoCallbackWarningCount = 0;
8820 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008821 sp<MmapStreamCallback> callback = mCallback.promote();
8822 if (callback != 0) {
8823 int channelCount;
8824 if (isOutput()) {
8825 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8826 } else {
8827 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8828 }
8829 Vector<float> values;
8830 for (int i = 0; i < channelCount; i++) {
8831 values.add(volume);
8832 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008833 mHalVolFloat = volume; // SW volume control worked, so update value.
8834 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008835 mLock.unlock();
8836 callback->onVolumeChanged(mChannelMask, values);
8837 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008838 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008839 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8840 ALOGW("Could not set MMAP stream volume: no volume callback!");
8841 mNoCallbackWarningCount++;
8842 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008843 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008844 }
8845 }
8846}
8847
Kevin Rocard069c2712018-03-29 19:09:14 -07008848void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8849{
8850 if (mOutput == nullptr || mOutput->stream == nullptr ||
8851 !mActiveTracks.readAndClearHasChanged()) {
8852 return;
8853 }
8854 StreamOutHalInterface::SourceMetadata metadata;
8855 for (const sp<MmapTrack> &track : mActiveTracks) {
8856 // No track is invalid as this is called after prepareTrack_l in the same critical section
8857 metadata.tracks.push_back({
8858 .usage = track->attributes().usage,
8859 .content_type = track->attributes().content_type,
8860 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8861 });
8862 }
8863 mOutput->stream->updateSourceMetadata(metadata);
8864}
8865
Eric Laurent6acd1d42017-01-04 14:23:29 -08008866void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8867{
8868 if (!mMasterMute) {
8869 char value[PROPERTY_VALUE_MAX];
8870 if (property_get("ro.audio.silent", value, "0") > 0) {
8871 char *endptr;
8872 unsigned long ul = strtoul(value, &endptr, 0);
8873 if (*endptr == '\0' && ul != 0) {
8874 ALOGD("Silence is golden");
8875 // The setprop command will not allow a property to be changed after
8876 // the first time it is set, so we don't have to worry about un-muting.
8877 setMasterMute_l(true);
8878 }
8879 }
8880 }
8881}
8882
8883void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8884{
8885 MmapThread::dumpInternals(fd, args);
8886
Glenn Kastend3bb6452016-12-05 18:14:37 -08008887 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8888 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008889 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8890}
8891
8892AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8893 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8894 AudioHwDevice *hwDev, AudioStreamIn *input,
8895 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8896 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8897 mInput(input)
8898{
8899 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8900 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8901}
8902
Eric Laurent331679c2018-04-16 17:03:16 -07008903status_t AudioFlinger::MmapCaptureThread::exitStandby()
8904{
8905 mInput->stream->setGain(1.0f);
8906 return MmapThread::exitStandby();
8907}
8908
Eric Laurent6acd1d42017-01-04 14:23:29 -08008909AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8910{
8911 Mutex::Autolock _l(mLock);
8912 AudioStreamIn *input = mInput;
8913 mInput = NULL;
8914 return input;
8915}
Kevin Rocard069c2712018-03-29 19:09:14 -07008916
Eric Laurent331679c2018-04-16 17:03:16 -07008917
8918void AudioFlinger::MmapCaptureThread::processVolume_l()
8919{
8920 bool changed = false;
8921 bool silenced = false;
8922
8923 sp<MmapStreamCallback> callback = mCallback.promote();
8924 if (callback == 0) {
8925 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8926 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
8927 mNoCallbackWarningCount++;
8928 }
8929 }
8930
8931 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
8932 // track is silenced and unmute otherwise
8933 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
8934 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
8935 changed = true;
8936 silenced = mActiveTracks[i]->isSilenced_l();
8937 }
8938 }
8939
8940 if (changed) {
8941 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
8942 }
8943}
8944
Kevin Rocard069c2712018-03-29 19:09:14 -07008945void AudioFlinger::MmapCaptureThread::updateMetadata_l()
8946{
8947 if (mInput == nullptr || mInput->stream == nullptr ||
8948 !mActiveTracks.readAndClearHasChanged()) {
8949 return;
8950 }
8951 StreamInHalInterface::SinkMetadata 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 .source = track->attributes().source,
8956 .gain = 1, // capture tracks do not have volumes
8957 });
8958 }
8959 mInput->stream->updateSinkMetadata(metadata);
8960}
8961
Eric Laurent331679c2018-04-16 17:03:16 -07008962void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
8963{
8964 Mutex::Autolock _l(mLock);
8965 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
8966 if (mActiveTracks[i]->uid() == uid) {
8967 mActiveTracks[i]->setSilenced_l(silenced);
8968 broadcast_l();
8969 }
8970 }
8971}
8972
Glenn Kasten63238ef2015-03-02 15:50:29 -08008973} // namespace android