blob: 90e2e8e746be1dd93ae3490cc4e4d41692425ff8 [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 Hung8946a282018-04-19 20:04:56 -07001582#ifdef TEE_SINK
1583 track->dumpTee(-1 /* fd */, "_REMOVE");
1584#endif
Andy Hungdae27702016-10-31 14:01:16 -07001585 return index;
1586}
1587
1588template <typename T>
1589void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1590 for (const sp<T> &track : mActiveTracks) {
1591 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001592 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001593 }
1594 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001595 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001596 mActiveTracks.clear();
1597 mLatestActiveTrack.clear();
1598 mBatteryCounter.clear();
1599}
1600
1601template <typename T>
1602void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1603 sp<ThreadBase> thread, bool force) {
1604 // Updates ActiveTracks client uids to the thread wakelock.
1605 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1606 thread->updateWakeLockUids_l(getWakeLockUids());
1607 mLastActiveTracksGeneration = mActiveTracksGeneration;
1608 }
1609
1610 // Updates BatteryNotifier uids
1611 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1612 const uid_t uid = it->first;
1613 ssize_t &previous = it->second.first;
1614 ssize_t &current = it->second.second;
1615 if (current > 0) {
1616 if (previous == 0) {
1617 BatteryNotifier::getInstance().noteStartAudio(uid);
1618 }
1619 previous = current;
1620 ++it;
1621 } else if (current == 0) {
1622 if (previous > 0) {
1623 BatteryNotifier::getInstance().noteStopAudio(uid);
1624 }
1625 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1626 } else /* (current < 0) */ {
1627 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1628 }
1629 }
1630}
Eric Laurent83b88082014-06-20 18:31:16 -07001631
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001632template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001633bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1634 const bool hasChanged = mHasChanged;
1635 mHasChanged = false;
1636 return hasChanged;
1637}
1638
1639template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001640void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1641 const char *funcName, const sp<T> &track) const {
1642 if (mLocalLog != nullptr) {
1643 String8 result;
1644 track->appendDump(result, false /* active */);
1645 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1646 }
1647}
1648
Eric Laurent6acd1d42017-01-04 14:23:29 -08001649void AudioFlinger::ThreadBase::broadcast_l()
1650{
1651 // Thread could be blocked waiting for async
1652 // so signal it to handle state changes immediately
1653 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1654 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1655 mSignalPending = true;
1656 mWaitWorkCV.broadcast();
1657}
1658
Eric Laurent81784c32012-11-19 14:55:58 -08001659// ----------------------------------------------------------------------------
1660// Playback
1661// ----------------------------------------------------------------------------
1662
1663AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1664 AudioStreamOut* output,
1665 audio_io_handle_t id,
1666 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001667 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001668 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001669 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001670 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001671 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001672 mMixerBuffer(NULL),
1673 mMixerBufferSize(0),
1674 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1675 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001676 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001677 mEffectBuffer(NULL),
1678 mEffectBufferSize(0),
1679 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1680 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001681 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001682 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001683 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001684 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001685 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001686 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001687 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001688 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001689 mMixerStatus(MIXER_IDLE),
1690 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001691 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001692 mBytesRemaining(0),
1693 mCurrentWriteLength(0),
1694 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001695 mWriteAckSequence(0),
1696 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001697 mScreenState(AudioFlinger::mScreenState),
1698 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001699 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001700 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1701 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001702{
Glenn Kastend7dca052015-03-05 16:05:54 -08001703 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1704 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001705
1706 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1707 // it would be safer to explicitly pass initial masterVolume/masterMute as
1708 // parameter.
1709 //
1710 // If the HAL we are using has support for master volume or master mute,
1711 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1712 // and the mute set to false).
1713 mMasterVolume = audioFlinger->masterVolume_l();
1714 mMasterMute = audioFlinger->masterMute_l();
1715 if (mOutput && mOutput->audioHwDev) {
1716 if (mOutput->audioHwDev->canSetMasterVolume()) {
1717 mMasterVolume = 1.0;
1718 }
1719
1720 if (mOutput->audioHwDev->canSetMasterMute()) {
1721 mMasterMute = false;
1722 }
1723 }
1724
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001725 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001726
Eric Laurent223fd5c2014-11-11 13:43:36 -08001727 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001728 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001729 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001730 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001731 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1732 }
Eric Laurent98e38192018-02-15 18:31:53 -08001733 // Audio patch volume is always max
1734 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1735 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001736}
1737
1738AudioFlinger::PlaybackThread::~PlaybackThread()
1739{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001740 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001741 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001742 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001743 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001744}
1745
1746void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1747{
1748 dumpInternals(fd, args);
1749 dumpTracks(fd, args);
1750 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001751 dprintf(fd, " Local log:\n");
1752 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001753}
1754
Glenn Kasten0f11b512014-01-31 16:18:54 -08001755void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001756{
Eric Laurent81784c32012-11-19 14:55:58 -08001757 String8 result;
1758
Marco Nelissenb2208842014-02-07 14:00:50 -08001759 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001760 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1761 const stream_type_t *st = &mStreamTypes[i];
1762 if (i > 0) {
1763 result.appendFormat(", ");
1764 }
1765 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1766 if (st->mute) {
1767 result.append("M");
1768 }
1769 }
1770 result.append("\n");
1771 write(fd, result.string(), result.length());
1772 result.clear();
1773
Eric Laurent81784c32012-11-19 14:55:58 -08001774 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1775 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001776 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001777 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001778
1779 size_t numtracks = mTracks.size();
1780 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001781 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001782 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001783 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001784 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001785 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001786 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001787 Track::appendDumpHeader(result);
1788 for (size_t i = 0; i < numtracks; ++i) {
1789 sp<Track> track = mTracks[i];
1790 if (track != 0) {
1791 bool active = mActiveTracks.indexOf(track) >= 0;
1792 if (active) {
1793 numactiveseen++;
1794 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001795 result.append(prefix);
1796 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001797 }
1798 }
1799 } else {
1800 result.append("\n");
1801 }
1802 if (numactiveseen != numactive) {
1803 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001804 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001805 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001806 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001807 Track::appendDumpHeader(result);
1808 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001809 sp<Track> track = mActiveTracks[i];
1810 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001811 result.append(prefix);
1812 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001813 }
1814 }
1815 }
1816
1817 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001818}
1819
1820void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1821{
Glenn Kasten44182c22015-03-05 17:12:23 -08001822 dumpBase(fd, args);
1823
Elliott Hughes87cebad2014-05-22 10:14:43 -07001824 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001825 dprintf(fd, " Last write occurred (msecs): %llu\n",
1826 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001827 dprintf(fd, " Total writes: %d\n", mNumWrites);
1828 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1829 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1830 dprintf(fd, " Suspend count: %d\n", mSuspended);
1831 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1832 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1833 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1834 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001835 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001836 AudioStreamOut *output = mOutput;
1837 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001838 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1839 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001840 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1841 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1842 if (mPipeSink.get() != nullptr) {
1843 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1844 }
1845 if (output != nullptr) {
1846 dprintf(fd, " Hal stream dump:\n");
1847 (void)output->stream->dump(fd);
1848 }
Eric Laurent81784c32012-11-19 14:55:58 -08001849}
1850
1851// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001852
1853void AudioFlinger::PlaybackThread::onFirstRef()
1854{
Glenn Kastend7dca052015-03-05 16:05:54 -08001855 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001856}
1857
1858// ThreadBase virtuals
1859void AudioFlinger::PlaybackThread::preExit()
1860{
1861 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001862 // FIXME this is using hard-coded strings but in the future, this functionality will be
1863 // converted to use audio HAL extensions required to support tunneling
1864 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1865 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001866}
1867
1868// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1869sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1870 const sp<AudioFlinger::Client>& client,
1871 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001872 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001873 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001874 audio_format_t format,
1875 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001876 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001877 size_t *pNotificationFrameCount,
1878 uint32_t notificationsPerBuffer,
1879 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001880 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001881 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001882 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001883 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001884 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001885 status_t *status,
1886 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001887{
Glenn Kasten74935e42013-12-19 08:56:45 -08001888 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001889 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001890 sp<Track> track;
1891 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001892 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001893 audio_output_flags_t requestedFlags = *flags;
1894
1895 if (*pSampleRate == 0) {
1896 *pSampleRate = mSampleRate;
1897 }
1898 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001899
1900 // special case for FAST flag considered OK if fast mixer is present
1901 if (hasFastMixer()) {
1902 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1903 }
1904
1905 // Check if requested flags are compatible with output stream flags
1906 if ((*flags & outputFlags) != *flags) {
1907 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1908 *flags, outputFlags);
1909 *flags = (audio_output_flags_t)(*flags & outputFlags);
1910 }
Eric Laurent81784c32012-11-19 14:55:58 -08001911
Eric Laurent81784c32012-11-19 14:55:58 -08001912 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001913 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001914 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001915 // PCM data
1916 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001917 // TODO: extract as a data library function that checks that a computationally
1918 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001919 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001920 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1921 (channelMask == AUDIO_CHANNEL_OUT_MONO
1922 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001923 // hardware sample rate
1924 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001925 // normal mixer has an associated fast mixer
1926 hasFastMixer() &&
1927 // there are sufficient fast track slots available
1928 (mFastTrackAvailMask != 0)
1929 // FIXME test that MixerThread for this fast track has a capable output HAL
1930 // FIXME add a permission test also?
1931 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001932 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1933 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001934 // read the fast track multiplier property the first time it is needed
1935 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1936 if (ok != 0) {
1937 ALOGE("%s pthread_once failed: %d", __func__, ok);
1938 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001939 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001940 }
Eric Laurent4c415062016-06-17 16:14:16 -07001941
1942 // check compatibility with audio effects.
1943 { // scope for mLock
1944 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001945 for (audio_session_t session : {
1946 AUDIO_SESSION_OUTPUT_STAGE,
1947 AUDIO_SESSION_OUTPUT_MIX,
1948 sessionId,
1949 }) {
1950 sp<EffectChain> chain = getEffectChain_l(session);
1951 if (chain.get() != nullptr) {
1952 audio_output_flags_t old = *flags;
1953 chain->checkOutputFlagCompatibility(flags);
1954 if (old != *flags) {
1955 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1956 (int)session, (int)old, (int)*flags);
1957 }
Eric Laurent4c415062016-06-17 16:14:16 -07001958 }
1959 }
1960 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001961 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001962 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1963 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001964 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001965 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1966 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001967 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001968 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001969 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001970 audio_is_linear_pcm(format),
1971 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001972 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001973 }
1974 }
Eric Laurent21da6472017-11-09 16:29:26 -08001975
1976 if (!audio_has_proportional_frames(format)) {
1977 if (sharedBuffer != 0) {
1978 // Same comment as below about ignoring frameCount parameter for set()
1979 frameCount = sharedBuffer->size();
1980 } else if (frameCount == 0) {
1981 frameCount = mNormalFrameCount;
1982 }
1983 if (notificationFrameCount != frameCount) {
1984 notificationFrameCount = frameCount;
1985 }
1986 } else if (sharedBuffer != 0) {
1987 // FIXME: Ensure client side memory buffers need
1988 // not have additional alignment beyond sample
1989 // (e.g. 16 bit stereo accessed as 32 bit frame).
1990 size_t alignment = audio_bytes_per_sample(format);
1991 if (alignment & 1) {
1992 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1993 alignment = 1;
1994 }
1995 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1996 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1997 if (channelCount > 1) {
1998 // More than 2 channels does not require stronger alignment than stereo
1999 alignment <<= 1;
2000 }
2001 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2002 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2003 sharedBuffer->pointer(), channelCount);
2004 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002005 goto Exit;
2006 }
Eric Laurent21da6472017-11-09 16:29:26 -08002007
2008 // When initializing a shared buffer AudioTrack via constructors,
2009 // there's no frameCount parameter.
2010 // But when initializing a shared buffer AudioTrack via set(),
2011 // there _is_ a frameCount parameter. We silently ignore it.
2012 frameCount = sharedBuffer->size() / frameSize;
2013 } else {
2014 size_t minFrameCount = 0;
2015 // For fast tracks we try to respect the application's request for notifications per buffer.
2016 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2017 if (notificationsPerBuffer > 0) {
2018 // Avoid possible arithmetic overflow during multiplication.
2019 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2020 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2021 notificationsPerBuffer, mFrameCount);
2022 } else {
2023 minFrameCount = mFrameCount * notificationsPerBuffer;
2024 }
2025 }
2026 } else {
2027 // For normal PCM streaming tracks, update minimum frame count.
2028 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2029 // cover audio hardware latency.
2030 // This is probably too conservative, but legacy application code may depend on it.
2031 // If you change this calculation, also review the start threshold which is related.
2032 uint32_t latencyMs = latency_l();
2033 if (latencyMs == 0) {
2034 ALOGE("Error when retrieving output stream latency");
2035 lStatus = UNKNOWN_ERROR;
2036 goto Exit;
2037 }
2038
2039 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2040 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2041
Eric Laurent81784c32012-11-19 14:55:58 -08002042 }
Eric Laurent21da6472017-11-09 16:29:26 -08002043 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002044 frameCount = minFrameCount;
2045 }
Eric Laurent81784c32012-11-19 14:55:58 -08002046 }
Eric Laurent21da6472017-11-09 16:29:26 -08002047
2048 // Make sure that application is notified with sufficient margin before underrun.
2049 // The client can divide the AudioTrack buffer into sub-buffers,
2050 // and expresses its desire to server as the notification frame count.
2051 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2052 size_t maxNotificationFrames;
2053 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2054 // notify every HAL buffer, regardless of the size of the track buffer
2055 maxNotificationFrames = mFrameCount;
2056 } else {
2057 // For normal tracks, use at least double-buffering if no sample rate conversion,
2058 // or at least triple-buffering if there is sample rate conversion
2059 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2060 maxNotificationFrames = frameCount / nBuffering;
2061 // If client requested a fast track but this was denied, then use the smaller maximum.
2062 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2063 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2064 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2065 maxNotificationFrames = maxNotificationFramesFastDenied;
2066 }
2067 }
2068 }
2069 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2070 if (notificationFrameCount == 0) {
2071 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2072 maxNotificationFrames, frameCount);
2073 } else {
2074 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2075 notificationFrameCount, maxNotificationFrames, frameCount);
2076 }
2077 notificationFrameCount = maxNotificationFrames;
2078 }
2079 }
2080
Glenn Kasten74935e42013-12-19 08:56:45 -08002081 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002082 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002083
Glenn Kastenc3df8382014-03-13 15:05:25 -07002084 switch (mType) {
2085
2086 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002087 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002088 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002089 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2090 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002091 sampleRate, format, channelMask, mOutput, mFormat);
2092 lStatus = BAD_VALUE;
2093 goto Exit;
2094 }
2095 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002096 break;
2097
2098 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002099 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002100 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2101 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002102 sampleRate, format, channelMask, mOutput, mFormat);
2103 lStatus = BAD_VALUE;
2104 goto Exit;
2105 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002106 break;
2107
2108 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002109 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002110 ALOGE("createTrack_l() Bad parameter: format %#x \""
2111 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002112 format, mOutput, mFormat);
2113 lStatus = BAD_VALUE;
2114 goto Exit;
2115 }
Andy Hungcd044842014-08-07 11:04:34 -07002116 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002117 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2118 lStatus = BAD_VALUE;
2119 goto Exit;
2120 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002121 break;
2122
Eric Laurent81784c32012-11-19 14:55:58 -08002123 }
2124
2125 lStatus = initCheck();
2126 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002127 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002128 goto Exit;
2129 }
2130
2131 { // scope for mLock
2132 Mutex::Autolock _l(mLock);
2133
2134 // all tracks in same audio session must share the same routing strategy otherwise
2135 // conflicts will happen when tracks are moved from one output to another by audio policy
2136 // manager
2137 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2138 for (size_t i = 0; i < mTracks.size(); ++i) {
2139 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002140 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002141 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2142 if (sessionId == t->sessionId() && strategy != actual) {
2143 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2144 strategy, actual);
2145 lStatus = BAD_VALUE;
2146 goto Exit;
2147 }
2148 }
2149 }
2150
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002151 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002152 channelMask, frameCount,
2153 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002154 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002155
Glenn Kasten03003332013-08-06 15:40:54 -07002156 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2157 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002158 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002159 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002160 goto Exit;
2161 }
2162 mTracks.add(track);
2163
2164 sp<EffectChain> chain = getEffectChain_l(sessionId);
2165 if (chain != 0) {
2166 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2167 track->setMainBuffer(chain->inBuffer());
2168 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2169 chain->incTrackCnt();
2170 }
2171
Eric Laurent05067782016-06-01 18:27:28 -07002172 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002173 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2174 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2175 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002176 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002177 }
2178 }
2179
2180 lStatus = NO_ERROR;
2181
2182Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002183 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002184 return track;
2185}
2186
Andy Hung1bc088a2018-02-09 15:57:31 -08002187template<typename T>
2188ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2189{
2190 const ssize_t index = mTracks.add(track);
2191 if (index >= 0) {
2192 // set name for track when adding.
2193 int name;
2194 if (mUnusedTrackNames.empty()) {
2195 name = mTracks.size() - 1; // new name {0 ... size-1}.
2196 } else {
2197 // reuse smallest name for deleted track.
2198 auto it = mUnusedTrackNames.begin();
2199 name = *it;
2200 (void)mUnusedTrackNames.erase(it);
2201 }
2202 track->setName(name);
2203 } else {
2204 LOG_ALWAYS_FATAL("cannot add track");
2205 }
2206 return index;
2207}
2208
2209template<typename T>
2210ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2211{
2212 const int name = track->name();
2213 const ssize_t index = mTracks.remove(track);
2214 if (index >= 0) {
2215 // invalidate name when removing from mTracks.
2216 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2217
2218 if (mSaveDeletedTrackNames) {
2219 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2220 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2221 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2222 mDeletedTrackNames.emplace(name);
2223 }
2224
2225 mUnusedTrackNames.emplace(name);
2226 track->setName(T::TRACK_NAME_PENDING);
2227 } else {
2228 LOG_ALWAYS_FATAL_IF(name >= 0,
2229 "valid name %d for track not in mTracks (returned %zd)", name, index);
2230 }
2231 return index;
2232}
2233
Eric Laurent81784c32012-11-19 14:55:58 -08002234uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2235{
2236 return latency;
2237}
2238
2239uint32_t AudioFlinger::PlaybackThread::latency() const
2240{
2241 Mutex::Autolock _l(mLock);
2242 return latency_l();
2243}
2244uint32_t AudioFlinger::PlaybackThread::latency_l() const
2245{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002246 uint32_t latency;
2247 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2248 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002249 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002250 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002251}
2252
2253void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2254{
2255 Mutex::Autolock _l(mLock);
2256 // Don't apply master volume in SW if our HAL can do it for us.
2257 if (mOutput && mOutput->audioHwDev &&
2258 mOutput->audioHwDev->canSetMasterVolume()) {
2259 mMasterVolume = 1.0;
2260 } else {
2261 mMasterVolume = value;
2262 }
2263}
2264
2265void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2266{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002267 if (isDuplicating()) {
2268 return;
2269 }
Eric Laurent81784c32012-11-19 14:55:58 -08002270 Mutex::Autolock _l(mLock);
2271 // Don't apply master mute in SW if our HAL can do it for us.
2272 if (mOutput && mOutput->audioHwDev &&
2273 mOutput->audioHwDev->canSetMasterMute()) {
2274 mMasterMute = false;
2275 } else {
2276 mMasterMute = muted;
2277 }
2278}
2279
2280void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2281{
2282 Mutex::Autolock _l(mLock);
2283 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002284 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002285}
2286
2287void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2288{
2289 Mutex::Autolock _l(mLock);
2290 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002291 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002292}
2293
2294float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2295{
2296 Mutex::Autolock _l(mLock);
2297 return mStreamTypes[stream].volume;
2298}
2299
2300// addTrack_l() must be called with ThreadBase::mLock held
2301status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2302{
2303 status_t status = ALREADY_EXISTS;
2304
Eric Laurent81784c32012-11-19 14:55:58 -08002305 if (mActiveTracks.indexOf(track) < 0) {
2306 // the track is newly added, make sure it fills up all its
2307 // buffers before playing. This is to ensure the client will
2308 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002309 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 TrackBase::track_state state = track->mState;
2311 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002312 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002313 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002314 mLock.lock();
2315 // abort track was stopped/paused while we released the lock
2316 if (state != track->mState) {
2317 if (status == NO_ERROR) {
2318 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002319 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002320 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002321 mLock.lock();
2322 }
2323 return INVALID_OPERATION;
2324 }
2325 // abort if start is rejected by audio policy manager
2326 if (status != NO_ERROR) {
2327 return PERMISSION_DENIED;
2328 }
2329#ifdef ADD_BATTERY_DATA
2330 // to track the speaker usage
2331 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2332#endif
2333 }
2334
Eric Laurent51716182016-02-29 18:00:56 -08002335 // set retry count for buffer fill
2336 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002337 if (track->isStopping_1()) {
2338 track->mRetryCount = kMaxTrackStopRetriesOffload;
2339 } else {
2340 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2341 }
2342 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002343 } else {
2344 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002345 track->mFillingUpStatus =
2346 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002347 }
2348
Eric Laurent81784c32012-11-19 14:55:58 -08002349 track->mResetDone = false;
2350 track->mPresentationCompleteFrames = 0;
2351 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002352 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2353 if (chain != 0) {
2354 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2355 track->sessionId());
2356 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002357 }
2358
2359 status = NO_ERROR;
2360 }
2361
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002362 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002363 return status;
2364}
2365
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002367{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002368 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002369 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002370 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2371 track->mState = TrackBase::STOPPED;
2372 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002373 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002374 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002375 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002376 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002377
2378 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002379}
2380
2381void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2382{
2383 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002384
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002385 String8 result;
2386 track->appendDump(result, false /* active */);
2387 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002388
Eric Laurent81784c32012-11-19 14:55:58 -08002389 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002390 if (track->isFastTrack()) {
2391 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002392 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002393 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2394 mFastTrackAvailMask |= 1 << index;
2395 // redundant as track is about to be destroyed, for dumpsys only
2396 track->mFastIndex = -1;
2397 }
2398 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2399 if (chain != 0) {
2400 chain->decTrackCnt();
2401 }
2402}
2403
2404String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2405{
Eric Laurent81784c32012-11-19 14:55:58 -08002406 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002407 String8 out_s8;
2408 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2409 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002410 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002411 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002412}
2413
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002414void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002415 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2416 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002417
Eric Laurent73e26b62015-04-27 16:55:58 -07002418 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002419
2420 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002421 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002422 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002423 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002424 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002425 desc->mChannelMask = mChannelMask;
2426 desc->mSamplingRate = mSampleRate;
2427 desc->mFormat = mFormat;
2428 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002429 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002430 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002431 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002432 break;
2433
Eric Laurent73e26b62015-04-27 16:55:58 -07002434 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002435 default:
2436 break;
2437 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002438 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002439}
2440
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002441void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002442{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002443 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002444}
2445
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002446void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002447{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002448 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002449}
2450
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002451void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002452{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002453 mCallbackThread->setAsyncError();
2454}
2455
Eric Laurent3b4529e2013-09-05 18:09:19 -07002456void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002457{
2458 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002459 // reject out of sequence requests
2460 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2461 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002462 mWaitWorkCV.signal();
2463 }
2464}
2465
Eric Laurent3b4529e2013-09-05 18:09:19 -07002466void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002467{
2468 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002469 // reject out of sequence requests
2470 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2471 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002472 mWaitWorkCV.signal();
2473 }
2474}
2475
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002476void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002477{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002478 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002479 mSampleRate = mOutput->getSampleRate();
2480 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002481 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002482 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002483 }
Andy Hung9a592762014-07-21 21:56:01 -07002484 if ((mType == MIXER || mType == DUPLICATING)
2485 && !isValidPcmSinkChannelMask(mChannelMask)) {
2486 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2487 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002488 }
Andy Hunge5412692014-05-16 11:25:07 -07002489 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002490
2491 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002492 status_t result = mOutput->stream->getFormat(&mHALFormat);
2493 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002494 // Get format from the shim, which will be different than the HAL format
2495 // if playing compressed audio over HDMI passthrough.
2496 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002497 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002498 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002499 }
Andy Hung6146c082014-03-18 11:56:15 -07002500 if ((mType == MIXER || mType == DUPLICATING)
2501 && !isValidPcmSinkFormat(mFormat)) {
2502 LOG_FATAL("HAL format %#x not supported for mixed output",
2503 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002504 }
Phil Burk062e67a2015-02-11 13:40:50 -08002505 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002506 result = mOutput->stream->getBufferSize(&mBufferSize);
2507 LOG_ALWAYS_FATAL_IF(result != OK,
2508 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002509 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002510 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002511 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002512 mFrameCount);
2513 }
2514
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002515 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2516 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002517 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002518 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002519 }
2520 }
2521
Eric Laurentd1f69b02014-12-15 14:33:13 -08002522 mHwSupportsPause = false;
2523 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002524 bool supportsPause = false, supportsResume = false;
2525 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2526 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002527 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002528 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002529 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002530 } else if (supportsResume) {
2531 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002532 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002533 }
2534 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002535 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2536 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2537 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002538
Andy Hungfbfc3952015-01-15 13:33:51 -08002539 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2540 // For best precision, we use float instead of the associated output
2541 // device format (typically PCM 16 bit).
2542
2543 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2544 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2545 mBufferSize = mFrameSize * mFrameCount;
2546
2547 // TODO: We currently use the associated output device channel mask and sample rate.
2548 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2549 // (if a valid mask) to avoid premature downmix.
2550 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2551 // instead of the output device sample rate to avoid loss of high frequency information.
2552 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2553 }
2554
Andy Hung09a50072014-02-27 14:30:47 -08002555 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002556 double multiplier = 1.0;
2557 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2558 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002559 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2560 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002561
Eric Laurent81784c32012-11-19 14:55:58 -08002562 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2563 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2564 maxNormalFrameCount = maxNormalFrameCount & ~15;
2565 if (maxNormalFrameCount < minNormalFrameCount) {
2566 maxNormalFrameCount = minNormalFrameCount;
2567 }
2568 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2569 if (multiplier <= 1.0) {
2570 multiplier = 1.0;
2571 } else if (multiplier <= 2.0) {
2572 if (2 * mFrameCount <= maxNormalFrameCount) {
2573 multiplier = 2.0;
2574 } else {
2575 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2576 }
2577 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002578 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002579 }
2580 }
2581 mNormalFrameCount = multiplier * mFrameCount;
2582 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002583 if (mType == MIXER || mType == DUPLICATING) {
2584 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2585 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002586 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002587 mNormalFrameCount);
2588
Andy Hung08fb1742015-05-31 23:22:10 -07002589 // Check if we want to throttle the processing to no more than 2x normal rate
2590 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002591 mThreadThrottleTimeMs = 0;
2592 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002593 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2594
Andy Hung010a1a12014-03-13 13:57:33 -07002595 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2596 // Originally this was int16_t[] array, need to remove legacy implications.
2597 free(mSinkBuffer);
2598 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002599 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2600 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2601 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002602 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002603
Andy Hung69aed5f2014-02-25 17:24:40 -08002604 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2605 // drives the output.
2606 free(mMixerBuffer);
2607 mMixerBuffer = NULL;
2608 if (mMixerBufferEnabled) {
2609 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2610 mMixerBufferSize = mNormalFrameCount * mChannelCount
2611 * audio_bytes_per_sample(mMixerBufferFormat);
2612 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2613 }
Andy Hung98ef9782014-03-04 14:46:50 -08002614 free(mEffectBuffer);
2615 mEffectBuffer = NULL;
2616 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002617 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002618 mEffectBufferSize = mNormalFrameCount * mChannelCount
2619 * audio_bytes_per_sample(mEffectBufferFormat);
2620 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2621 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002622
Eric Laurent81784c32012-11-19 14:55:58 -08002623 // force reconfiguration of effect chains and engines to take new buffer size and audio
2624 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002625 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002626 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2627 // matter.
2628 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2629 Vector< sp<EffectChain> > effectChains = mEffectChains;
2630 for (size_t i = 0; i < effectChains.size(); i ++) {
2631 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2632 }
2633}
2634
Kevin Rocard069c2712018-03-29 19:09:14 -07002635void AudioFlinger::PlaybackThread::updateMetadata_l()
2636{
Kevin Rocard12381092018-04-11 09:19:59 -07002637 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2638 return; // That should not happen
2639 }
2640 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2641 for (const sp<Track> &track : mActiveTracks) {
2642 // Do not short-circuit as all hasChanged states must be reset
2643 // as all the metadata are going to be sent
2644 hasChanged |= track->readAndClearHasChanged();
2645 }
2646 if (!hasChanged) {
2647 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002648 }
2649 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002650 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002651 for (const sp<Track> &track : mActiveTracks) {
2652 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002653 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002654 }
Kevin Rocard12381092018-04-11 09:19:59 -07002655 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002656}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002657
Kevin Rocard12381092018-04-11 09:19:59 -07002658void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2659 const StreamOutHalInterface::SourceMetadata& metadata)
2660{
2661 mOutput->stream->updateSourceMetadata(metadata);
2662};
2663
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002664status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002665{
2666 if (halFrames == NULL || dspFrames == NULL) {
2667 return BAD_VALUE;
2668 }
2669 Mutex::Autolock _l(mLock);
2670 if (initCheck() != NO_ERROR) {
2671 return INVALID_OPERATION;
2672 }
Andy Hung818e7a32016-02-16 18:08:07 -08002673 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002674 *halFrames = framesWritten;
2675
2676 if (isSuspended()) {
2677 // return an estimation of rendered frames when the output is suspended
2678 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002679 *dspFrames = (uint32_t)
2680 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002681 return NO_ERROR;
2682 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002683 status_t status;
2684 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002685 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002686 *dspFrames = (size_t)frames;
2687 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002688 }
2689}
2690
Eric Laurent4c415062016-06-17 16:14:16 -07002691// hasAudioSession_l() must be called with ThreadBase::mLock held
2692uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002693{
Eric Laurent81784c32012-11-19 14:55:58 -08002694 uint32_t result = 0;
2695 if (getEffectChain_l(sessionId) != 0) {
2696 result = EFFECT_SESSION;
2697 }
2698
2699 for (size_t i = 0; i < mTracks.size(); ++i) {
2700 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002701 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002702 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002703 if (track->isFastTrack()) {
2704 result |= FAST_SESSION;
2705 }
Eric Laurent81784c32012-11-19 14:55:58 -08002706 break;
2707 }
2708 }
2709
2710 return result;
2711}
2712
Glenn Kastend848eb42016-03-08 13:42:11 -08002713uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002714{
2715 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2716 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2717 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2718 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2719 }
2720 for (size_t i = 0; i < mTracks.size(); i++) {
2721 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002722 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002723 return AudioSystem::getStrategyForStream(track->streamType());
2724 }
2725 }
2726 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2727}
2728
2729
Phil Burk062e67a2015-02-11 13:40:50 -08002730AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002731{
2732 Mutex::Autolock _l(mLock);
2733 return mOutput;
2734}
2735
Phil Burk062e67a2015-02-11 13:40:50 -08002736AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002737{
2738 Mutex::Autolock _l(mLock);
2739 AudioStreamOut *output = mOutput;
2740 mOutput = NULL;
2741 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2742 // must push a NULL and wait for ack
2743 mOutputSink.clear();
2744 mPipeSink.clear();
2745 mNormalSink.clear();
2746 return output;
2747}
2748
2749// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002750sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002751{
2752 if (mOutput == NULL) {
2753 return NULL;
2754 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002755 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002756}
2757
2758uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2759{
2760 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2761}
2762
2763status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2764{
2765 if (!isValidSyncEvent(event)) {
2766 return BAD_VALUE;
2767 }
2768
2769 Mutex::Autolock _l(mLock);
2770
2771 for (size_t i = 0; i < mTracks.size(); ++i) {
2772 sp<Track> track = mTracks[i];
2773 if (event->triggerSession() == track->sessionId()) {
2774 (void) track->setSyncEvent(event);
2775 return NO_ERROR;
2776 }
2777 }
2778
2779 return NAME_NOT_FOUND;
2780}
2781
2782bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2783{
2784 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2785}
2786
2787void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2788 const Vector< sp<Track> >& tracksToRemove)
2789{
2790 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002791 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002792 for (size_t i = 0 ; i < count ; i++) {
2793 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002794 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002795 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002796 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002797#ifdef ADD_BATTERY_DATA
2798 // to track the speaker usage
2799 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2800#endif
2801 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002802 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002803 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002804 }
Eric Laurent81784c32012-11-19 14:55:58 -08002805 }
2806 }
2807 }
Eric Laurent81784c32012-11-19 14:55:58 -08002808}
2809
2810void AudioFlinger::PlaybackThread::checkSilentMode_l()
2811{
2812 if (!mMasterMute) {
2813 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002814 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2815 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2816 return;
2817 }
Eric Laurent81784c32012-11-19 14:55:58 -08002818 if (property_get("ro.audio.silent", value, "0") > 0) {
2819 char *endptr;
2820 unsigned long ul = strtoul(value, &endptr, 0);
2821 if (*endptr == '\0' && ul != 0) {
2822 ALOGD("Silence is golden");
2823 // The setprop command will not allow a property to be changed after
2824 // the first time it is set, so we don't have to worry about un-muting.
2825 setMasterMute_l(true);
2826 }
2827 }
2828 }
2829}
2830
2831// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002832ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002833{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002834 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002835 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002836 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002837 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002838
2839 // If an NBAIO sink is present, use it to write the normal mixer's submix
2840 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002841
Andy Hung010a1a12014-03-13 13:57:33 -07002842 const size_t count = mBytesRemaining / mFrameSize;
2843
Simon Wilson2d590962012-11-29 15:18:50 -08002844 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002845 // update the setpoint when AudioFlinger::mScreenState changes
2846 uint32_t screenState = AudioFlinger::mScreenState;
2847 if (screenState != mScreenState) {
2848 mScreenState = screenState;
2849 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2850 if (pipe != NULL) {
2851 pipe->setAvgFrames((mScreenState & 1) ?
2852 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2853 }
2854 }
Andy Hung010a1a12014-03-13 13:57:33 -07002855 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002856 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002857 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002858 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002859#ifdef TEE_SINK
2860 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2861#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002862 } else {
2863 bytesWritten = framesWritten;
2864 }
2865 // otherwise use the HAL / AudioStreamOut directly
2866 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002867 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002868
Eric Laurentbfb1b832013-01-07 09:53:42 -08002869 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002870 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2871 mWriteAckSequence += 2;
2872 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002874 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002876 // FIXME We should have an implementation of timestamps for direct output threads.
2877 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002878 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002879
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 if (mUseAsyncWrite &&
2881 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2882 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002883 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002884 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002885 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 }
Eric Laurent81784c32012-11-19 14:55:58 -08002887 }
2888
Eric Laurent81784c32012-11-19 14:55:58 -08002889 mNumWrites++;
2890 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002891 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 return bytesWritten;
2893}
2894
2895void AudioFlinger::PlaybackThread::threadLoop_drain()
2896{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002897 bool supportsDrain = false;
2898 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2900 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002901 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2902 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002904 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002906 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002907 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 }
2909}
2910
2911void AudioFlinger::PlaybackThread::threadLoop_exit()
2912{
Eric Laurent275e8e92014-11-30 15:14:47 -08002913 {
2914 Mutex::Autolock _l(mLock);
2915 for (size_t i = 0; i < mTracks.size(); i++) {
2916 sp<Track> track = mTracks[i];
2917 track->invalidate();
2918 }
Andy Hungdae27702016-10-31 14:01:16 -07002919 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2920 // After we exit there are no more track changes sent to BatteryNotifier
2921 // because that requires an active threadLoop.
2922 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2923 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002924 }
Eric Laurent81784c32012-11-19 14:55:58 -08002925}
2926
2927/*
2928The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002929 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002930 - mActiveSleepTimeUs from activeSleepTimeUs()
2931 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002932 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2933 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002934 - maxPeriod from frame count and sample rate (MIXER only)
2935
2936The parameters that affect these derived values are:
2937 - frame count
2938 - frame size
2939 - sample rate
2940 - device type: A2DP or not
2941 - device latency
2942 - format: PCM or not
2943 - active sleep time
2944 - idle sleep time
2945*/
2946
2947void AudioFlinger::PlaybackThread::cacheParameters_l()
2948{
Andy Hung25c2dac2014-02-27 14:56:00 -08002949 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002950 mActiveSleepTimeUs = activeSleepTimeUs();
2951 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002952
2953 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2954 // truncating audio when going to standby.
2955 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2956 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2957 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2958 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2959 }
2960 }
Eric Laurent81784c32012-11-19 14:55:58 -08002961}
2962
Eric Laurent13084622016-05-17 10:51:49 -07002963bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002964{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002965 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002966 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002967 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002968 size_t size = mTracks.size();
2969 for (size_t i = 0; i < size; i++) {
2970 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002971 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002972 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002973 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002974 }
2975 }
Eric Laurent13084622016-05-17 10:51:49 -07002976 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002977}
2978
Haynes Mathew George05317d22016-05-03 16:34:26 -07002979void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2980{
2981 Mutex::Autolock _l(mLock);
2982 invalidateTracks_l(streamType);
2983}
2984
Eric Laurent81784c32012-11-19 14:55:58 -08002985status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2986{
Glenn Kastend848eb42016-03-08 13:42:11 -08002987 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002988 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002989 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002990 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2991 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2992 &halInBuffer);
2993 if (result != OK) return result;
2994 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002995 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002996 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002997 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002998 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002999 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003000 if (mType != DIRECT) {
3001 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003002 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003003 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003004 &halInBuffer);
3005 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003006#ifdef FLOAT_EFFECT_CHAIN
3007 buffer = halInBuffer->audioBuffer()->f32;
3008#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003009 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003010#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003011 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3012 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003013 }
3014
3015 // Attach all tracks with same session ID to this chain.
3016 for (size_t i = 0; i < mTracks.size(); ++i) {
3017 sp<Track> track = mTracks[i];
3018 if (session == track->sessionId()) {
3019 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3020 buffer);
3021 track->setMainBuffer(buffer);
3022 chain->incTrackCnt();
3023 }
3024 }
3025
3026 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003027 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003028 if (session == track->sessionId()) {
3029 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3030 chain->incActiveTrackCnt();
3031 }
3032 }
3033 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003034 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003035 chain->setInBuffer(halInBuffer);
3036 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003037 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003038 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003039 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3040 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003041 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003042 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003043 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003044 // Effect chain for other sessions are inserted at beginning of effect
3045 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003046 // sessions is not important.
3047 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3048 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3049 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003050 size_t size = mEffectChains.size();
3051 size_t i = 0;
3052 for (i = 0; i < size; i++) {
3053 if (mEffectChains[i]->sessionId() < session) {
3054 break;
3055 }
3056 }
3057 mEffectChains.insertAt(chain, i);
3058 checkSuspendOnAddEffectChain_l(chain);
3059
3060 return NO_ERROR;
3061}
3062
3063size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3064{
Glenn Kastend848eb42016-03-08 13:42:11 -08003065 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003066
3067 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3068
3069 for (size_t i = 0; i < mEffectChains.size(); i++) {
3070 if (chain == mEffectChains[i]) {
3071 mEffectChains.removeAt(i);
3072 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003073 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003074 if (session == track->sessionId()) {
3075 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3076 chain.get(), session);
3077 chain->decActiveTrackCnt();
3078 }
3079 }
3080
3081 // detach all tracks with same session ID from this chain
3082 for (size_t i = 0; i < mTracks.size(); ++i) {
3083 sp<Track> track = mTracks[i];
3084 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003085 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003086 chain->decTrackCnt();
3087 }
3088 }
3089 break;
3090 }
3091 }
3092 return mEffectChains.size();
3093}
3094
3095status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003096 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003097{
3098 Mutex::Autolock _l(mLock);
3099 return attachAuxEffect_l(track, EffectId);
3100}
3101
3102status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003103 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003104{
3105 status_t status = NO_ERROR;
3106
3107 if (EffectId == 0) {
3108 track->setAuxBuffer(0, NULL);
3109 } else {
3110 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3111 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3112 if (effect != 0) {
3113 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3114 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3115 } else {
3116 status = INVALID_OPERATION;
3117 }
3118 } else {
3119 status = BAD_VALUE;
3120 }
3121 }
3122 return status;
3123}
3124
3125void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3126{
3127 for (size_t i = 0; i < mTracks.size(); ++i) {
3128 sp<Track> track = mTracks[i];
3129 if (track->auxEffectId() == effectId) {
3130 attachAuxEffect_l(track, 0);
3131 }
3132 }
3133}
3134
3135bool AudioFlinger::PlaybackThread::threadLoop()
3136{
Glenn Kasten388d5712017-04-07 14:38:41 -07003137 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003138
Eric Laurent81784c32012-11-19 14:55:58 -08003139 Vector< sp<Track> > tracksToRemove;
3140
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003141 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003142 nsecs_t lastWriteFinished = -1; // time last server write completed
3143 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003144
3145 // MIXER
3146 nsecs_t lastWarning = 0;
3147
3148 // DUPLICATING
3149 // FIXME could this be made local to while loop?
3150 writeFrames = 0;
3151
3152 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003153 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003154
3155 if (mType == MIXER) {
3156 sleepTimeShift = 0;
3157 }
3158
3159 CpuStats cpuStats;
3160 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3161
3162 acquireWakeLock();
3163
Glenn Kasteneef598c2017-04-03 14:41:13 -07003164 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3165 // thread associated with this PlaybackThread.
3166 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3167 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003168 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3169 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003170 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003171 const char *logString = NULL;
3172
rago1bb90822017-05-02 18:31:48 -07003173 // Estimated time for next buffer to be written to hal. This is used only on
3174 // suspended mode (for now) to help schedule the wait time until next iteration.
3175 nsecs_t timeLoopNextNs = 0;
3176
Eric Laurent664539d2013-09-23 18:24:31 -07003177 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003178
Eric Laurent81784c32012-11-19 14:55:58 -08003179 while (!exitPending())
3180 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003181 // Log merge requests are performed during AudioFlinger binder transactions, but
3182 // that does not cover audio playback. It's requested here for that reason.
3183 mAudioFlinger->requestLogMerge();
3184
Eric Laurent81784c32012-11-19 14:55:58 -08003185 cpuStats.sample(myName);
3186
3187 Vector< sp<EffectChain> > effectChains;
3188
Eric Laurent81784c32012-11-19 14:55:58 -08003189 { // scope for mLock
3190
3191 Mutex::Autolock _l(mLock);
3192
Eric Laurent021cf962014-05-13 10:18:14 -07003193 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003194
Glenn Kasteneef598c2017-04-03 14:41:13 -07003195 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003196 if (logString != NULL) {
3197 mNBLogWriter->logTimestamp();
3198 mNBLogWriter->log(logString);
3199 logString = NULL;
3200 }
3201
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003202 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003203 // and associate with the sink frames written out. We need
3204 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003205 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003206 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003207 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003208 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003209 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003210 ExtendedTimestamp timestamp; // use private copy to fetch
3211 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003212
3213 // We keep track of the last valid kernel position in case we are in underrun
3214 // and the normal mixer period is the same as the fast mixer period, or there
3215 // is some error from the HAL.
3216 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3217 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3218 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3219 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3220 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3221
3222 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3223 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3224 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3225 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003226 }
3227
3228 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3229 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003230 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003231 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003232 }
3233
Andy Hung818e7a32016-02-16 18:08:07 -08003234 // copy over kernel info
3235 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003236 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3237 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003238 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3239 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003240 }
3241 // mFramesWritten for non-offloaded tracks are contiguous
3242 // even after standby() is called. This is useful for the track frame
3243 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003244 bool serverLocationUpdate = false;
3245 if (mFramesWritten != lastFramesWritten) {
3246 serverLocationUpdate = true;
3247 lastFramesWritten = mFramesWritten;
3248 }
3249 // Only update timestamps if there is a meaningful change.
3250 // Either the kernel timestamp must be valid or we have written something.
3251 if (kernelLocationUpdate || serverLocationUpdate) {
3252 if (serverLocationUpdate) {
3253 // use the time before we called the HAL write - it is a bit more accurate
3254 // to when the server last read data than the current time here.
3255 //
3256 // If we haven't written anything, mLastWriteTime will be -1
3257 // and we use systemTime().
3258 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3259 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3260 ? systemTime() : mLastWriteTime;
3261 }
Andy Hungdae27702016-10-31 14:01:16 -07003262
3263 for (const sp<Track> &t : mActiveTracks) {
3264 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003265 t->updateTrackFrameInfo(
3266 t->mAudioTrackServerProxy->framesReleased(),
3267 mFramesWritten,
3268 mTimestamp);
3269 }
Andy Hunge10393e2015-06-12 13:59:33 -07003270 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003271 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003272#if 0
3273 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003274 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003275 timespec ts;
3276 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003277 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003278 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003279 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003280 }
3281 ++z;
3282#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003283 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003284 if (mSignalPending) {
3285 // A signal was raised while we were unlocked
3286 mSignalPending = false;
3287 } else if (waitingAsyncCallback_l()) {
3288 if (exitPending()) {
3289 break;
3290 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003291 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003292 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003293 releaseWakeLock_l();
3294 released = true;
3295 }
Andy Hung10cbff12017-02-21 17:30:14 -08003296
3297 const int64_t waitNs = computeWaitTimeNs_l();
3298 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3299 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3300 if (status == TIMED_OUT) {
3301 mSignalPending = true; // if timeout recheck everything
3302 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003303 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003304 if (released) {
3305 acquireWakeLock_l();
3306 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003307 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3308 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003309
3310 continue;
3311 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003312 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003313 isSuspended()) {
3314 // put audio hardware into standby after short delay
3315 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003316
3317 threadLoop_standby();
3318
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003319 // This is where we go into standby
3320 if (!mStandby) {
3321 LOG_AUDIO_STATE();
3322 }
Eric Laurent81784c32012-11-19 14:55:58 -08003323 mStandby = true;
3324 }
3325
3326 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3327 // we're about to wait, flush the binder command buffer
3328 IPCThreadState::self()->flushCommands();
3329
3330 clearOutputTracks();
3331
3332 if (exitPending()) {
3333 break;
3334 }
3335
3336 releaseWakeLock_l();
3337 // wait until we have something to do...
3338 ALOGV("%s going to sleep", myName.string());
3339 mWaitWorkCV.wait(mLock);
3340 ALOGV("%s waking up", myName.string());
3341 acquireWakeLock_l();
3342
3343 mMixerStatus = MIXER_IDLE;
3344 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3345 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003346 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003347 checkSilentMode_l();
3348
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003349 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3350 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003351 if (mType == MIXER) {
3352 sleepTimeShift = 0;
3353 }
3354
3355 continue;
3356 }
3357 }
Eric Laurent81784c32012-11-19 14:55:58 -08003358 // mMixerStatusIgnoringFastTracks is also updated internally
3359 mMixerStatus = prepareTracks_l(&tracksToRemove);
3360
Andy Hungdae27702016-10-31 14:01:16 -07003361 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003362
Kevin Rocard069c2712018-03-29 19:09:14 -07003363 updateMetadata_l();
3364
Eric Laurent81784c32012-11-19 14:55:58 -08003365 // prevent any changes in effect chain list and in each effect chain
3366 // during mixing and effect process as the audio buffers could be deleted
3367 // or modified if an effect is created or deleted
3368 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003369 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003370
Eric Laurentbfb1b832013-01-07 09:53:42 -08003371 if (mBytesRemaining == 0) {
3372 mCurrentWriteLength = 0;
3373 if (mMixerStatus == MIXER_TRACKS_READY) {
3374 // threadLoop_mix() sets mCurrentWriteLength
3375 threadLoop_mix();
3376 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3377 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003378 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003379 // must be written to HAL
3380 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003381 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003382 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003383 }
3384 }
Andy Hung98ef9782014-03-04 14:46:50 -08003385 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003386 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003387 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3388 // or mSinkBuffer (if there are no effects).
3389 //
3390 // This is done pre-effects computation; if effects change to
3391 // support higher precision, this needs to move.
3392 //
3393 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003394 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003395 if (mMixerBufferValid) {
3396 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3397 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3398
Andy Hung2ddee192015-12-18 17:34:44 -08003399 // mono blend occurs for mixer threads only (not direct or offloaded)
3400 // and is handled here if we're going directly to the sink.
3401 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003402 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3403 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003404 }
3405
Andy Hung98ef9782014-03-04 14:46:50 -08003406 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3407 mNormalFrameCount * mChannelCount);
3408 }
3409
Eric Laurentbfb1b832013-01-07 09:53:42 -08003410 mBytesRemaining = mCurrentWriteLength;
3411 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003412 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3413 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3414 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3415 mBytesWritten += mBytesRemaining;
3416 mFramesWritten += framesRemaining;
3417 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003418 mBytesRemaining = 0;
3419 }
Eric Laurent81784c32012-11-19 14:55:58 -08003420
Eric Laurentbfb1b832013-01-07 09:53:42 -08003421 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003422 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003423 for (size_t i = 0; i < effectChains.size(); i ++) {
3424 effectChains[i]->process_l();
3425 }
Eric Laurent81784c32012-11-19 14:55:58 -08003426 }
3427 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003428 // Process effect chains for offloaded thread even if no audio
3429 // was read from audio track: process only updates effect state
3430 // and thus does have to be synchronized with audio writes but may have
3431 // to be called while waiting for async write callback
3432 if (mType == OFFLOAD) {
3433 for (size_t i = 0; i < effectChains.size(); i ++) {
3434 effectChains[i]->process_l();
3435 }
3436 }
Eric Laurent81784c32012-11-19 14:55:58 -08003437
Andy Hung98ef9782014-03-04 14:46:50 -08003438 // Only if the Effects buffer is enabled and there is data in the
3439 // Effects buffer (buffer valid), we need to
3440 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003441 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003442 if (mEffectBufferValid) {
3443 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003444
3445 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003446 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3447 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003448 }
3449
Andy Hung98ef9782014-03-04 14:46:50 -08003450 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3451 mNormalFrameCount * mChannelCount);
3452 }
3453
Eric Laurent81784c32012-11-19 14:55:58 -08003454 // enable changes in effect chain
3455 unlockEffectChains(effectChains);
3456
Eric Laurentbfb1b832013-01-07 09:53:42 -08003457 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003458 // mSleepTimeUs == 0 means we must write to audio hardware
3459 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003460 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003461 // We save lastWriteFinished here, as previousLastWriteFinished,
3462 // for throttling. On thread start, previousLastWriteFinished will be
3463 // set to -1, which properly results in no throttling after the first write.
3464 nsecs_t previousLastWriteFinished = lastWriteFinished;
3465 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003466 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003467 // FIXME rewrite to reduce number of system calls
3468 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003469 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003470 lastWriteFinished = systemTime();
3471 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003472 if (ret < 0) {
3473 mBytesRemaining = 0;
3474 } else {
3475 mBytesWritten += ret;
3476 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003477 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003478 }
3479 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3480 (mMixerStatus == MIXER_DRAIN_ALL)) {
3481 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003482 }
Andy Hung08fb1742015-05-31 23:22:10 -07003483 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003484 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003485 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003486 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003487 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003488 ATRACE_NAME("underrun");
3489 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003490 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003491 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003492 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003493 }
Andy Hung08fb1742015-05-31 23:22:10 -07003494
3495 if (mThreadThrottle
3496 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3497 && ret > 0) { // we wrote something
3498 // Limit MixerThread data processing to no more than twice the
3499 // expected processing rate.
3500 //
3501 // This helps prevent underruns with NuPlayer and other applications
3502 // which may set up buffers that are close to the minimum size, or use
3503 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3504 //
3505 // The throttle smooths out sudden large data drains from the device,
3506 // e.g. when it comes out of standby, which often causes problems with
3507 // (1) mixer threads without a fast mixer (which has its own warm-up)
3508 // (2) minimum buffer sized tracks (even if the track is full,
3509 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003510 //
3511 // Total time spent in last processing cycle equals time spent in
3512 // 1. threadLoop_write, as well as time spent in
3513 // 2. threadLoop_mix (significant for heavy mixing, especially
3514 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003515
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003516 // it's OK if deltaMs (and deltaNs) is an overestimate.
3517 nsecs_t deltaNs;
3518 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3519 __builtin_sub_overflow(
3520 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3521 const int32_t deltaMs = deltaNs / 1000000;
3522
Ivan Lozanoea04d392017-11-07 14:37:07 -08003523 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003524 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3525 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003526 // notify of throttle start on verbose log
3527 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3528 "mixer(%p) throttle begin:"
3529 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003530 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003531 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003532 // Throttle must be attributed to the previous mixer loop's write time
3533 // to allow back-to-back throttling.
3534 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003535 } else {
3536 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3537 if (diff > 0) {
3538 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003539 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003540 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3541 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003542 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003543 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3544 }
Andy Hung08fb1742015-05-31 23:22:10 -07003545 }
3546 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003547 }
Eric Laurent81784c32012-11-19 14:55:58 -08003548
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003550 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003551 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003552 // suspended requires accurate metering of sleep time.
3553 if (isSuspended()) {
3554 // advance by expected sleepTime
3555 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3556 const nsecs_t nowNs = systemTime();
3557
3558 // compute expected next time vs current time.
3559 // (negative deltas are treated as delays).
3560 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3561 if (deltaNs < -kMaxNextBufferDelayNs) {
3562 // Delays longer than the max allowed trigger a reset.
3563 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3564 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3565 timeLoopNextNs = nowNs + deltaNs;
3566 } else if (deltaNs < 0) {
3567 // Delays within the max delay allowed: zero the delta/sleepTime
3568 // to help the system catch up in the next iteration(s)
3569 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3570 deltaNs = 0;
3571 }
3572 // update sleep time (which is >= 0)
3573 mSleepTimeUs = deltaNs / 1000;
3574 }
Eric Laurente93cc032016-05-05 10:15:10 -07003575 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3576 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003577 }
Glenn Kastene7754022014-10-31 12:11:26 -07003578 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 }
Eric Laurent81784c32012-11-19 14:55:58 -08003580 }
3581
3582 // Finally let go of removed track(s), without the lock held
3583 // since we can't guarantee the destructors won't acquire that
3584 // same lock. This will also mutate and push a new fast mixer state.
3585 threadLoop_removeTracks(tracksToRemove);
3586 tracksToRemove.clear();
3587
3588 // FIXME I don't understand the need for this here;
3589 // it was in the original code but maybe the
3590 // assignment in saveOutputTracks() makes this unnecessary?
3591 clearOutputTracks();
3592
3593 // Effect chains will be actually deleted here if they were removed from
3594 // mEffectChains list during mixing or effects processing
3595 effectChains.clear();
3596
3597 // FIXME Note that the above .clear() is no longer necessary since effectChains
3598 // is now local to this block, but will keep it for now (at least until merge done).
3599 }
3600
Eric Laurentbfb1b832013-01-07 09:53:42 -08003601 threadLoop_exit();
3602
Eric Laurentcf817a22014-08-04 20:36:31 -07003603 if (!mStandby) {
3604 threadLoop_standby();
3605 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003606 }
3607
3608 releaseWakeLock();
3609
3610 ALOGV("Thread %p type %d exiting", this, mType);
3611 return false;
3612}
3613
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614// removeTracks_l() must be called with ThreadBase::mLock held
3615void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3616{
3617 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003618 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003619 for (size_t i=0 ; i<count ; i++) {
3620 const sp<Track>& track = tracksToRemove.itemAt(i);
3621 mActiveTracks.remove(track);
3622 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3623 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3624 if (chain != 0) {
3625 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3626 track->sessionId());
3627 chain->decActiveTrackCnt();
3628 }
3629 if (track->isTerminated()) {
3630 removeTrack_l(track);
3631 }
3632 }
3633 }
3634
3635}
Eric Laurent81784c32012-11-19 14:55:58 -08003636
Eric Laurentaccc1472013-09-20 09:36:34 -07003637status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3638{
3639 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003640 ExtendedTimestamp ets;
3641 status_t status = mNormalSink->getTimestamp(ets);
3642 if (status == NO_ERROR) {
3643 status = ets.getBestTimestamp(&timestamp);
3644 }
3645 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003646 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003647 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003648 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003649 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003650 timestamp.mPosition = (uint32_t)position64;
3651 return NO_ERROR;
3652 }
3653 }
3654 return INVALID_OPERATION;
3655}
Eric Laurent1c333e22014-05-20 10:48:17 -07003656
Eric Laurent054d9d32015-04-24 08:48:48 -07003657status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3658 audio_patch_handle_t *handle)
3659{
Andy Hungf60abce2016-08-26 11:37:54 -07003660 status_t status;
3661 if (property_get_bool("af.patch_park", false /* default_value */)) {
3662 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3663 // or if HAL does not properly lock against access.
3664 AutoPark<FastMixer> park(mFastMixer);
3665 status = PlaybackThread::createAudioPatch_l(patch, handle);
3666 } else {
3667 status = PlaybackThread::createAudioPatch_l(patch, handle);
3668 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003669 return status;
3670}
3671
Eric Laurent1c333e22014-05-20 10:48:17 -07003672status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3673 audio_patch_handle_t *handle)
3674{
3675 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003676
3677 // store new device and send to effects
3678 audio_devices_t type = AUDIO_DEVICE_NONE;
3679 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3680 type |= patch->sinks[i].ext.device.type;
3681 }
3682
3683#ifdef ADD_BATTERY_DATA
3684 // when changing the audio output device, call addBatteryData to notify
3685 // the change
3686 if (mOutDevice != type) {
3687 uint32_t params = 0;
3688 // check whether speaker is on
3689 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3690 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003691 }
3692
Eric Laurent054d9d32015-04-24 08:48:48 -07003693 audio_devices_t deviceWithoutSpeaker
3694 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3695 // check if any other device (except speaker) is on
3696 if (type & deviceWithoutSpeaker) {
3697 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3698 }
3699
3700 if (params != 0) {
3701 addBatteryData(params);
3702 }
3703 }
3704#endif
3705
3706 for (size_t i = 0; i < mEffectChains.size(); i++) {
3707 mEffectChains[i]->setDevice_l(type);
3708 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003709
3710 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3711 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3712 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003713 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003714 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003715
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003716 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003717 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3718 status = hwDevice->createAudioPatch(patch->num_sources,
3719 patch->sources,
3720 patch->num_sinks,
3721 patch->sinks,
3722 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003723 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003724 char *address;
3725 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3726 //FIXME: we only support address on first sink with HAL version < 3.0
3727 address = audio_device_address_to_parameter(
3728 patch->sinks[0].ext.device.type,
3729 patch->sinks[0].ext.device.address);
3730 } else {
3731 address = (char *)calloc(1, 1);
3732 }
3733 AudioParameter param = AudioParameter(String8(address));
3734 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003735 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003736 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003737 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003738 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003739 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003740 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003741 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3742 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003743 return status;
3744}
3745
Eric Laurent054d9d32015-04-24 08:48:48 -07003746status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3747{
Andy Hungf60abce2016-08-26 11:37:54 -07003748 status_t status;
3749 if (property_get_bool("af.patch_park", false /* default_value */)) {
3750 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3751 // or if HAL does not properly lock against access.
3752 AutoPark<FastMixer> park(mFastMixer);
3753 status = PlaybackThread::releaseAudioPatch_l(handle);
3754 } else {
3755 status = PlaybackThread::releaseAudioPatch_l(handle);
3756 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003757 return status;
3758}
3759
Eric Laurent1c333e22014-05-20 10:48:17 -07003760status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3761{
3762 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003763
3764 mOutDevice = AUDIO_DEVICE_NONE;
3765
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003766 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003767 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3768 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003769 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003770 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003771 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003772 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003773 }
3774 return status;
3775}
3776
Eric Laurent83b88082014-06-20 18:31:16 -07003777void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3778{
3779 Mutex::Autolock _l(mLock);
3780 mTracks.add(track);
3781}
3782
3783void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3784{
3785 Mutex::Autolock _l(mLock);
3786 destroyTrack_l(track);
3787}
3788
Mikhail Naganovdc769682018-05-04 15:34:08 -07003789void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003790{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003791 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003792 config->role = AUDIO_PORT_ROLE_SOURCE;
3793 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3794 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3795}
3796
Eric Laurent81784c32012-11-19 14:55:58 -08003797// ----------------------------------------------------------------------------
3798
3799AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003800 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3801 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003802 // mAudioMixer below
3803 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003804 mFastMixerFutex(0),
3805 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003806 // mOutputSink below
3807 // mPipeSink below
3808 // mNormalSink below
3809{
3810 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003811 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003812 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003813 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3814 mNormalFrameCount);
3815 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3816
Andy Hungfbfc3952015-01-15 13:33:51 -08003817 if (type == DUPLICATING) {
3818 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3819 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3820 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3821 return;
3822 }
Eric Laurent81784c32012-11-19 14:55:58 -08003823 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003824 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003825 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003826 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003827#if !LOG_NDEBUG
3828 ssize_t index =
3829#else
3830 (void)
3831#endif
3832 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003833 ALOG_ASSERT(index == 0);
3834
3835 // initialize fast mixer depending on configuration
3836 bool initFastMixer;
3837 switch (kUseFastMixer) {
3838 case FastMixer_Never:
3839 initFastMixer = false;
3840 break;
3841 case FastMixer_Always:
3842 initFastMixer = true;
3843 break;
3844 case FastMixer_Static:
3845 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003846 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3847 // where the period is less than an experimentally determined threshold that can be
3848 // scheduled reliably with CFS. However, the BT A2DP HAL is
3849 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3850 initFastMixer = mFrameCount < mNormalFrameCount
3851 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003852 break;
3853 }
Andy Hungfda69402017-02-15 14:33:12 -08003854 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3855 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3856 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003857 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003858 audio_format_t fastMixerFormat;
3859 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3860 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3861 } else {
3862 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3863 }
3864 if (mFormat != fastMixerFormat) {
3865 // change our Sink format to accept our intermediate precision
3866 mFormat = fastMixerFormat;
3867 free(mSinkBuffer);
3868 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3869 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3870 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3871 }
Eric Laurent81784c32012-11-19 14:55:58 -08003872
3873 // create a MonoPipe to connect our submix to FastMixer
3874 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003875
Andy Hung1258c1a2014-05-23 21:22:17 -07003876 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003877 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003878 format.mFormat = fastMixerFormat;
3879 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3880
Eric Laurent81784c32012-11-19 14:55:58 -08003881 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3882 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3883 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3884 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3885 const NBAIO_Format offers[1] = {format};
3886 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003887#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003888 ssize_t index =
3889#else
3890 (void)
3891#endif
3892 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003893 ALOG_ASSERT(index == 0);
3894 monoPipe->setAvgFrames((mScreenState & 1) ?
3895 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3896 mPipeSink = monoPipe;
3897
Eric Laurent81784c32012-11-19 14:55:58 -08003898 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003899 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003900 FastMixerStateQueue *sq = mFastMixer->sq();
3901#ifdef STATE_QUEUE_DUMP
3902 sq->setObserverDump(&mStateQueueObserverDump);
3903 sq->setMutatorDump(&mStateQueueMutatorDump);
3904#endif
3905 FastMixerState *state = sq->begin();
3906 FastTrack *fastTrack = &state->mFastTracks[0];
3907 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3908 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3909 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003910 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3911 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003912 fastTrack->mGeneration++;
3913 state->mFastTracksGen++;
3914 state->mTrackMask = 1;
3915 // fast mixer will use the HAL output sink
3916 state->mOutputSink = mOutputSink.get();
3917 state->mOutputSinkGen++;
3918 state->mFrameCount = mFrameCount;
3919 state->mCommand = FastMixerState::COLD_IDLE;
3920 // already done in constructor initialization list
3921 //mFastMixerFutex = 0;
3922 state->mColdFutexAddr = &mFastMixerFutex;
3923 state->mColdGen++;
3924 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003925 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3926 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003927 sq->end();
3928 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3929
3930 // start the fast mixer
3931 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3932 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003933 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003934 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003935
3936#ifdef AUDIO_WATCHDOG
3937 // create and start the watchdog
3938 mAudioWatchdog = new AudioWatchdog();
3939 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3940 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3941 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003942 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003943#endif
Andy Hung8946a282018-04-19 20:04:56 -07003944 } else {
3945#ifdef TEE_SINK
3946 // Only use the MixerThread tee if there is no FastMixer.
3947 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3948 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3949#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003950 }
3951
3952 switch (kUseFastMixer) {
3953 case FastMixer_Never:
3954 case FastMixer_Dynamic:
3955 mNormalSink = mOutputSink;
3956 break;
3957 case FastMixer_Always:
3958 mNormalSink = mPipeSink;
3959 break;
3960 case FastMixer_Static:
3961 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3962 break;
3963 }
3964}
3965
3966AudioFlinger::MixerThread::~MixerThread()
3967{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003968 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003969 FastMixerStateQueue *sq = mFastMixer->sq();
3970 FastMixerState *state = sq->begin();
3971 if (state->mCommand == FastMixerState::COLD_IDLE) {
3972 int32_t old = android_atomic_inc(&mFastMixerFutex);
3973 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003974 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003975 }
3976 }
3977 state->mCommand = FastMixerState::EXIT;
3978 sq->end();
3979 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3980 mFastMixer->join();
3981 // Though the fast mixer thread has exited, it's state queue is still valid.
3982 // We'll use that extract the final state which contains one remaining fast track
3983 // corresponding to our sub-mix.
3984 state = sq->begin();
3985 ALOG_ASSERT(state->mTrackMask == 1);
3986 FastTrack *fastTrack = &state->mFastTracks[0];
3987 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3988 delete fastTrack->mBufferProvider;
3989 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003990 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003991#ifdef AUDIO_WATCHDOG
3992 if (mAudioWatchdog != 0) {
3993 mAudioWatchdog->requestExit();
3994 mAudioWatchdog->requestExitAndWait();
3995 mAudioWatchdog.clear();
3996 }
3997#endif
3998 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003999 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004000 delete mAudioMixer;
4001}
4002
4003
4004uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4005{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004006 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004007 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4008 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4009 }
4010 return latency;
4011}
4012
4013
4014void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4015{
4016 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4017}
4018
Eric Laurentbfb1b832013-01-07 09:53:42 -08004019ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004020{
4021 // FIXME we should only do one push per cycle; confirm this is true
4022 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004023 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004024 FastMixerStateQueue *sq = mFastMixer->sq();
4025 FastMixerState *state = sq->begin();
4026 if (state->mCommand != FastMixerState::MIX_WRITE &&
4027 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4028 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004029
4030 // FIXME workaround for first HAL write being CPU bound on some devices
4031 ATRACE_BEGIN("write");
4032 mOutput->write((char *)mSinkBuffer, 0);
4033 ATRACE_END();
4034
Eric Laurent81784c32012-11-19 14:55:58 -08004035 int32_t old = android_atomic_inc(&mFastMixerFutex);
4036 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004037 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004038 }
4039#ifdef AUDIO_WATCHDOG
4040 if (mAudioWatchdog != 0) {
4041 mAudioWatchdog->resume();
4042 }
4043#endif
4044 }
4045 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004046#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004047 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004048 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004049#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004050 sq->end();
4051 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4052 if (kUseFastMixer == FastMixer_Dynamic) {
4053 mNormalSink = mPipeSink;
4054 }
4055 } else {
4056 sq->end(false /*didModify*/);
4057 }
4058 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004059 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004060}
4061
4062void AudioFlinger::MixerThread::threadLoop_standby()
4063{
4064 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004065 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004066 FastMixerStateQueue *sq = mFastMixer->sq();
4067 FastMixerState *state = sq->begin();
4068 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004069 // Report any frames trapped in the Monopipe
4070 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4071 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4072 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4073 "monoPipeWritten:%lld monoPipeLeft:%lld",
4074 (long long)mFramesWritten, (long long)mSuspendedFrames,
4075 (long long)mPipeSink->framesWritten(), pipeFrames);
4076 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4077
Eric Laurent81784c32012-11-19 14:55:58 -08004078 state->mCommand = FastMixerState::COLD_IDLE;
4079 state->mColdFutexAddr = &mFastMixerFutex;
4080 state->mColdGen++;
4081 mFastMixerFutex = 0;
4082 sq->end();
4083 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4084 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4085 if (kUseFastMixer == FastMixer_Dynamic) {
4086 mNormalSink = mOutputSink;
4087 }
4088#ifdef AUDIO_WATCHDOG
4089 if (mAudioWatchdog != 0) {
4090 mAudioWatchdog->pause();
4091 }
4092#endif
4093 } else {
4094 sq->end(false /*didModify*/);
4095 }
4096 }
4097 PlaybackThread::threadLoop_standby();
4098}
4099
Eric Laurentbfb1b832013-01-07 09:53:42 -08004100bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4101{
4102 return false;
4103}
4104
4105bool AudioFlinger::PlaybackThread::shouldStandby_l()
4106{
4107 return !mStandby;
4108}
4109
4110bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4111{
4112 Mutex::Autolock _l(mLock);
4113 return waitingAsyncCallback_l();
4114}
4115
Eric Laurent81784c32012-11-19 14:55:58 -08004116// shared by MIXER and DIRECT, overridden by DUPLICATING
4117void AudioFlinger::PlaybackThread::threadLoop_standby()
4118{
4119 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004120 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004121 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004122 // discard any pending drain or write ack by incrementing sequence
4123 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4124 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004126 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4127 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004128 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004129 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004130}
4131
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004132void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4133{
4134 ALOGV("signal playback thread");
4135 broadcast_l();
4136}
4137
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004138void AudioFlinger::PlaybackThread::onAsyncError()
4139{
4140 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4141 invalidateTracks((audio_stream_type_t)i);
4142 }
4143}
4144
Eric Laurent81784c32012-11-19 14:55:58 -08004145void AudioFlinger::MixerThread::threadLoop_mix()
4146{
Eric Laurent81784c32012-11-19 14:55:58 -08004147 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004148 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004149 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004150 // increase sleep time progressively when application underrun condition clears.
4151 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4152 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4153 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004154 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004155 sleepTimeShift--;
4156 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004157 mSleepTimeUs = 0;
4158 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004159 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004160
Eric Laurent81784c32012-11-19 14:55:58 -08004161}
4162
4163void AudioFlinger::MixerThread::threadLoop_sleepTime()
4164{
4165 // If no tracks are ready, sleep once for the duration of an output
4166 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004167 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004168 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004169 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4170 // Using the Monopipe availableToWrite, we estimate the
4171 // sleep time to retry for more data (before we underrun).
4172 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4173 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4174 const size_t pipeFrames = monoPipe->maxFrames();
4175 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4176 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4177 const size_t framesDelay = std::min(
4178 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4179 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4180 pipeFrames, framesLeft, framesDelay);
4181 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4182 } else {
4183 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4184 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4185 mSleepTimeUs = kMinThreadSleepTimeUs;
4186 }
4187 // reduce sleep time in case of consecutive application underruns to avoid
4188 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4189 // duration we would end up writing less data than needed by the audio HAL if
4190 // the condition persists.
4191 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4192 sleepTimeShift++;
4193 }
Eric Laurent81784c32012-11-19 14:55:58 -08004194 }
4195 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004196 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004197 }
4198 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004199 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4200 // before effects processing or output.
4201 if (mMixerBufferValid) {
4202 memset(mMixerBuffer, 0, mMixerBufferSize);
4203 } else {
4204 memset(mSinkBuffer, 0, mSinkBufferSize);
4205 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004206 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004207 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4208 "anticipated start");
4209 }
4210 // TODO add standby time extension fct of effect tail
4211}
4212
4213// prepareTracks_l() must be called with ThreadBase::mLock held
4214AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4215 Vector< sp<Track> > *tracksToRemove)
4216{
Andy Hung1bc088a2018-02-09 15:57:31 -08004217 // clean up deleted track names in AudioMixer before allocating new tracks
4218 (void)mTracks.processDeletedTrackNames([this](int name) {
4219 // for each name, destroy it in the AudioMixer
4220 if (mAudioMixer->exists(name)) {
4221 mAudioMixer->destroy(name);
4222 }
4223 });
4224 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004225
4226 mixer_state mixerStatus = MIXER_IDLE;
4227 // find out which tracks need to be processed
4228 size_t count = mActiveTracks.size();
4229 size_t mixedTracks = 0;
4230 size_t tracksWithEffect = 0;
4231 // counts only _active_ fast tracks
4232 size_t fastTracks = 0;
4233 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4234
4235 float masterVolume = mMasterVolume;
4236 bool masterMute = mMasterMute;
4237
4238 if (masterMute) {
4239 masterVolume = 0;
4240 }
4241 // Delegate master volume control to effect in output mix effect chain if needed
4242 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4243 if (chain != 0) {
4244 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4245 chain->setVolume_l(&v, &v);
4246 masterVolume = (float)((v + (1 << 23)) >> 24);
4247 chain.clear();
4248 }
4249
4250 // prepare a new state to push
4251 FastMixerStateQueue *sq = NULL;
4252 FastMixerState *state = NULL;
4253 bool didModify = false;
4254 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004255 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004256 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004257 sq = mFastMixer->sq();
4258 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004259 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004260 }
4261
Andy Hung69aed5f2014-02-25 17:24:40 -08004262 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004263 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004264
Andy Hungbd3b2b02018-05-21 10:53:11 -07004265 // DeferredOperations handles statistics after setting mixerStatus.
4266 class DeferredOperations {
4267 public:
4268 DeferredOperations(mixer_state *mixerStatus)
4269 : mMixerStatus(mixerStatus) { }
4270
4271 // when leaving scope, tally frames properly.
4272 ~DeferredOperations() {
4273 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4274 // because that is when the underrun occurs.
4275 // We do not distinguish between FastTracks and NormalTracks here.
4276 if (*mMixerStatus == MIXER_TRACKS_READY) {
4277 for (const auto &underrun : mUnderrunFrames) {
4278 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4279 underrun.second);
4280 }
4281 }
4282 }
4283
4284 // tallyUnderrunFrames() is called to update the track counters
4285 // with the number of underrun frames for a particular mixer period.
4286 // We defer tallying until we know the final mixer status.
4287 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4288 mUnderrunFrames.emplace_back(track, underrunFrames);
4289 }
4290
4291 private:
4292 const mixer_state * const mMixerStatus;
4293 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4294 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4295
Eric Laurent81784c32012-11-19 14:55:58 -08004296 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004297 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004298
4299 // this const just means the local variable doesn't change
4300 Track* const track = t.get();
4301
4302 // process fast tracks
4303 if (track->isFastTrack()) {
4304
4305 // It's theoretically possible (though unlikely) for a fast track to be created
4306 // and then removed within the same normal mix cycle. This is not a problem, as
4307 // the track never becomes active so it's fast mixer slot is never touched.
4308 // The converse, of removing an (active) track and then creating a new track
4309 // at the identical fast mixer slot within the same normal mix cycle,
4310 // is impossible because the slot isn't marked available until the end of each cycle.
4311 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004312 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004313 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4314 FastTrack *fastTrack = &state->mFastTracks[j];
4315
4316 // Determine whether the track is currently in underrun condition,
4317 // and whether it had a recent underrun.
4318 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4319 FastTrackUnderruns underruns = ftDump->mUnderruns;
4320 uint32_t recentFull = (underruns.mBitFields.mFull -
4321 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4322 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4323 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4324 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4325 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4326 uint32_t recentUnderruns = recentPartial + recentEmpty;
4327 track->mObservedUnderruns = underruns;
4328 // don't count underruns that occur while stopping or pausing
4329 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004330 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004331 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4332 recentUnderruns > 0) {
4333 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004334 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004335 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004336 // Immediately account for FastTrack underruns.
4337 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004338
4339 // This is similar to the state machine for normal tracks,
4340 // with a few modifications for fast tracks.
4341 bool isActive = true;
4342 switch (track->mState) {
4343 case TrackBase::STOPPING_1:
4344 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004345 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004346 track->mState = TrackBase::STOPPING_2;
4347 }
4348 break;
4349 case TrackBase::PAUSING:
4350 // ramp down is not yet implemented
4351 track->setPaused();
4352 break;
4353 case TrackBase::RESUMING:
4354 // ramp up is not yet implemented
4355 track->mState = TrackBase::ACTIVE;
4356 break;
4357 case TrackBase::ACTIVE:
4358 if (recentFull > 0 || recentPartial > 0) {
4359 // track has provided at least some frames recently: reset retry count
4360 track->mRetryCount = kMaxTrackRetries;
4361 }
4362 if (recentUnderruns == 0) {
4363 // no recent underruns: stay active
4364 break;
4365 }
4366 // there has recently been an underrun of some kind
4367 if (track->sharedBuffer() == 0) {
4368 // were any of the recent underruns "empty" (no frames available)?
4369 if (recentEmpty == 0) {
4370 // no, then ignore the partial underruns as they are allowed indefinitely
4371 break;
4372 }
4373 // there has recently been an "empty" underrun: decrement the retry counter
4374 if (--(track->mRetryCount) > 0) {
4375 break;
4376 }
4377 // indicate to client process that the track was disabled because of underrun;
4378 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004379 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004380 // remove from active list, but state remains ACTIVE [confusing but true]
4381 isActive = false;
4382 break;
4383 }
4384 // fall through
4385 case TrackBase::STOPPING_2:
4386 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004387 case TrackBase::STOPPED:
4388 case TrackBase::FLUSHED: // flush() while active
4389 // Check for presentation complete if track is inactive
4390 // We have consumed all the buffers of this track.
4391 // This would be incomplete if we auto-paused on underrun
4392 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004393 uint32_t latency = 0;
4394 status_t result = mOutput->stream->getLatency(&latency);
4395 ALOGE_IF(result != OK,
4396 "Error when retrieving output stream latency: %d", result);
4397 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004398 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004399 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4400 // track stays in active list until presentation is complete
4401 break;
4402 }
4403 }
4404 if (track->isStopping_2()) {
4405 track->mState = TrackBase::STOPPED;
4406 }
4407 if (track->isStopped()) {
4408 // Can't reset directly, as fast mixer is still polling this track
4409 // track->reset();
4410 // So instead mark this track as needing to be reset after push with ack
4411 resetMask |= 1 << i;
4412 }
4413 isActive = false;
4414 break;
4415 case TrackBase::IDLE:
4416 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004417 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004418 }
4419
4420 if (isActive) {
4421 // was it previously inactive?
4422 if (!(state->mTrackMask & (1 << j))) {
4423 ExtendedAudioBufferProvider *eabp = track;
4424 VolumeProvider *vp = track;
4425 fastTrack->mBufferProvider = eabp;
4426 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004427 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004428 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004429 fastTrack->mGeneration++;
4430 state->mTrackMask |= 1 << j;
4431 didModify = true;
4432 // no acknowledgement required for newly active tracks
4433 }
Kevin Rocard12381092018-04-11 09:19:59 -07004434 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004435 // cache the combined master volume and stream type volume for fast mixer; this
4436 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004437 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004438 proxy->framesReleased()).first;
4439 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004440 * mStreamTypes[track->streamType()].volume
4441 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004442 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004443 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4444 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4445 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4446 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004447 ++fastTracks;
4448 } else {
4449 // was it previously active?
4450 if (state->mTrackMask & (1 << j)) {
4451 fastTrack->mBufferProvider = NULL;
4452 fastTrack->mGeneration++;
4453 state->mTrackMask &= ~(1 << j);
4454 didModify = true;
4455 // If any fast tracks were removed, we must wait for acknowledgement
4456 // because we're about to decrement the last sp<> on those tracks.
4457 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4458 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004459 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4460 // AudioTrack may start (which may not be with a start() but with a write()
4461 // after underrun) and immediately paused or released. In that case the
4462 // FastTrack state hasn't had time to update.
4463 // TODO Remove the ALOGW when this theory is confirmed.
4464 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004465 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4466 j, track->mState, state->mTrackMask, recentUnderruns,
4467 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004468 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004469 }
4470 tracksToRemove->add(track);
4471 // Avoids a misleading display in dumpsys
4472 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4473 }
4474 continue;
4475 }
4476
4477 { // local variable scope to avoid goto warning
4478
4479 audio_track_cblk_t* cblk = track->cblk();
4480
4481 // The first time a track is added we wait
4482 // for all its buffers to be filled before processing it
4483 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004484
4485 // if an active track doesn't exist in the AudioMixer, create it.
4486 if (!mAudioMixer->exists(name)) {
4487 status_t status = mAudioMixer->create(
4488 name,
4489 track->mChannelMask,
4490 track->mFormat,
4491 track->mSessionId);
4492 if (status != OK) {
4493 ALOGW("%s: cannot create track name"
4494 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4495 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4496 tracksToRemove->add(track);
4497 track->invalidate(); // consider it dead.
4498 continue;
4499 }
4500 }
4501
Eric Laurent81784c32012-11-19 14:55:58 -08004502 // make sure that we have enough frames to mix one full buffer.
4503 // enforce this condition only once to enable draining the buffer in case the client
4504 // app does not call stop() and relies on underrun to stop:
4505 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4506 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004507 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004508 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004509 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004510
4511 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004512 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004513 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4514 // add frames already consumed but not yet released by the resampler
4515 // because mAudioTrackServerProxy->framesReady() will include these frames
4516 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4517
Eric Laurent81784c32012-11-19 14:55:58 -08004518 uint32_t minFrames = 1;
4519 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4520 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004521 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004522 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004523
4524 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004525 if (ATRACE_ENABLED()) {
4526 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004527 std::string traceName("nRdy");
4528 traceName += std::to_string(track->name());
4529 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004530 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004531 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004532 !track->isPaused() && !track->isTerminated())
4533 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004534 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004535
4536 mixedTracks++;
4537
Andy Hung69aed5f2014-02-25 17:24:40 -08004538 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4539 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004540 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004541 if (track->mainBuffer() != mSinkBuffer &&
4542 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004543 if (mEffectBufferEnabled) {
4544 mEffectBufferValid = true; // Later can set directly.
4545 }
Eric Laurent81784c32012-11-19 14:55:58 -08004546 chain = getEffectChain_l(track->sessionId());
4547 // Delegate volume control to effect in track effect chain if needed
4548 if (chain != 0) {
4549 tracksWithEffect++;
4550 } else {
4551 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4552 "session %d",
4553 name, track->sessionId());
4554 }
4555 }
4556
4557
4558 int param = AudioMixer::VOLUME;
4559 if (track->mFillingUpStatus == Track::FS_FILLED) {
4560 // no ramp for the first volume setting
4561 track->mFillingUpStatus = Track::FS_ACTIVE;
4562 if (track->mState == TrackBase::RESUMING) {
4563 track->mState = TrackBase::ACTIVE;
4564 param = AudioMixer::RAMP_VOLUME;
4565 }
4566 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004567 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004568 // FIXME should not make a decision based on mServer
4569 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004570 // If the track is stopped before the first frame was mixed,
4571 // do not apply ramp
4572 param = AudioMixer::RAMP_VOLUME;
4573 }
4574
4575 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004576 uint32_t vl, vr; // in U8.24 integer format
4577 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004578 // read original volumes with volume control
4579 float typeVolume = mStreamTypes[track->streamType()].volume;
4580 float v = masterVolume * typeVolume;
4581
Glenn Kastene4756fe2012-11-29 13:38:14 -08004582 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004583 vl = vr = 0;
4584 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004585 if (track->isPausing()) {
4586 track->setPaused();
4587 }
4588 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004589 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004590 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004591 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4592 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004593 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004594 if (vlf > GAIN_FLOAT_UNITY) {
4595 ALOGV("Track left volume out of range: %.3g", vlf);
4596 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004597 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004598 if (vrf > GAIN_FLOAT_UNITY) {
4599 ALOGV("Track right volume out of range: %.3g", vrf);
4600 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004601 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004602 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004603 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004604 // now apply the master volume and stream type volume and shaper volume
4605 vlf *= v * vh;
4606 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004607 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004608 // then derive vl and vr as U8.24 versions for the effect chain
4609 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4610 vl = (uint32_t) (scaleto8_24 * vlf);
4611 vr = (uint32_t) (scaleto8_24 * vrf);
4612 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004613 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004614 // send level comes from shared memory and so may be corrupt
4615 if (sendLevel > MAX_GAIN_INT) {
4616 ALOGV("Track send level out of range: %04X", sendLevel);
4617 sendLevel = MAX_GAIN_INT;
4618 }
Andy Hung6be49402014-05-30 10:42:03 -07004619 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4620 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004621 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004622
Kevin Rocard12381092018-04-11 09:19:59 -07004623 track->setFinalVolume((vrf + vlf) / 2.f);
4624
Eric Laurent81784c32012-11-19 14:55:58 -08004625 // Delegate volume control to effect in track effect chain if needed
4626 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4627 // Do not ramp volume if volume is controlled by effect
4628 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004629 // Update remaining floating point volume levels
4630 vlf = (float)vl / (1 << 24);
4631 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004632 track->mHasVolumeController = true;
4633 } else {
4634 // force no volume ramp when volume controller was just disabled or removed
4635 // from effect chain to avoid volume spike
4636 if (track->mHasVolumeController) {
4637 param = AudioMixer::VOLUME;
4638 }
4639 track->mHasVolumeController = false;
4640 }
4641
Eric Laurent7c29ec92017-09-20 17:54:22 -07004642 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4643 // still applied by the mixer.
4644 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4645 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4646 if (v != mLeftVolFloat) {
4647 status_t result = mOutput->stream->setVolume(v, v);
4648 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4649 if (result == OK) {
4650 mLeftVolFloat = v;
4651 }
4652 }
4653 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4654 // remove stream volume contribution from software volume.
4655 if (v != 0.0f && mLeftVolFloat == v) {
4656 vlf = min(1.0f, vlf / v);
4657 vrf = min(1.0f, vrf / v);
4658 vaf = min(1.0f, vaf / v);
4659 }
4660 }
Eric Laurent81784c32012-11-19 14:55:58 -08004661 // XXX: these things DON'T need to be done each time
4662 mAudioMixer->setBufferProvider(name, track);
4663 mAudioMixer->enable(name);
4664
Andy Hung6be49402014-05-30 10:42:03 -07004665 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4666 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4667 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004668 mAudioMixer->setParameter(
4669 name,
4670 AudioMixer::TRACK,
4671 AudioMixer::FORMAT, (void *)track->format());
4672 mAudioMixer->setParameter(
4673 name,
4674 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004675 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004676 mAudioMixer->setParameter(
4677 name,
4678 AudioMixer::TRACK,
4679 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004680 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004681 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004682 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004683 if (reqSampleRate == 0) {
4684 reqSampleRate = mSampleRate;
4685 } else if (reqSampleRate > maxSampleRate) {
4686 reqSampleRate = maxSampleRate;
4687 }
Eric Laurent81784c32012-11-19 14:55:58 -08004688 mAudioMixer->setParameter(
4689 name,
4690 AudioMixer::RESAMPLE,
4691 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004692 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004693
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004694 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004695 mAudioMixer->setParameter(
4696 name,
4697 AudioMixer::TIMESTRETCH,
4698 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004699 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004700
Andy Hung69aed5f2014-02-25 17:24:40 -08004701 /*
4702 * Select the appropriate output buffer for the track.
4703 *
Andy Hung98ef9782014-03-04 14:46:50 -08004704 * Tracks with effects go into their own effects chain buffer
4705 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004706 *
4707 * Other tracks can use mMixerBuffer for higher precision
4708 * channel accumulation. If this buffer is enabled
4709 * (mMixerBufferEnabled true), then selected tracks will accumulate
4710 * into it.
4711 *
4712 */
4713 if (mMixerBufferEnabled
4714 && (track->mainBuffer() == mSinkBuffer
4715 || track->mainBuffer() == mMixerBuffer)) {
4716 mAudioMixer->setParameter(
4717 name,
4718 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004719 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004720 mAudioMixer->setParameter(
4721 name,
4722 AudioMixer::TRACK,
4723 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4724 // TODO: override track->mainBuffer()?
4725 mMixerBufferValid = true;
4726 } else {
4727 mAudioMixer->setParameter(
4728 name,
4729 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004730 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004731 mAudioMixer->setParameter(
4732 name,
4733 AudioMixer::TRACK,
4734 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4735 }
Eric Laurent81784c32012-11-19 14:55:58 -08004736 mAudioMixer->setParameter(
4737 name,
4738 AudioMixer::TRACK,
4739 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4740
4741 // reset retry count
4742 track->mRetryCount = kMaxTrackRetries;
4743
4744 // If one track is ready, set the mixer ready if:
4745 // - the mixer was not ready during previous round OR
4746 // - no other track is not ready
4747 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4748 mixerStatus != MIXER_TRACKS_ENABLED) {
4749 mixerStatus = MIXER_TRACKS_READY;
4750 }
4751 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004752 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004753 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004754 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4755 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004756 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004757 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004758 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004759
Eric Laurent81784c32012-11-19 14:55:58 -08004760 // clear effect chain input buffer if an active track underruns to avoid sending
4761 // previous audio buffer again to effects
4762 chain = getEffectChain_l(track->sessionId());
4763 if (chain != 0) {
4764 chain->clearInputBuffer();
4765 }
4766
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004767 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004768 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4769 track->isStopped() || track->isPaused()) {
4770 // We have consumed all the buffers of this track.
4771 // Remove it from the list of active tracks.
4772 // TODO: use actual buffer filling status instead of latency when available from
4773 // audio HAL
4774 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004775 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004776 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4777 if (track->isStopped()) {
4778 track->reset();
4779 }
4780 tracksToRemove->add(track);
4781 }
4782 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004783 // No buffers for this track. Give it a few chances to
4784 // fill a buffer, then remove it from active list.
4785 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004786 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004787 tracksToRemove->add(track);
4788 // indicate to client process that the track was disabled because of underrun;
4789 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004790 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004791 // If one track is not ready, mark the mixer also not ready if:
4792 // - the mixer was ready during previous round OR
4793 // - no other track is ready
4794 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4795 mixerStatus != MIXER_TRACKS_READY) {
4796 mixerStatus = MIXER_TRACKS_ENABLED;
4797 }
4798 }
4799 mAudioMixer->disable(name);
4800 }
4801
4802 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004803
4804 }
4805
4806 // Push the new FastMixer state if necessary
4807 bool pauseAudioWatchdog = false;
4808 if (didModify) {
4809 state->mFastTracksGen++;
4810 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4811 if (kUseFastMixer == FastMixer_Dynamic &&
4812 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4813 state->mCommand = FastMixerState::COLD_IDLE;
4814 state->mColdFutexAddr = &mFastMixerFutex;
4815 state->mColdGen++;
4816 mFastMixerFutex = 0;
4817 if (kUseFastMixer == FastMixer_Dynamic) {
4818 mNormalSink = mOutputSink;
4819 }
4820 // If we go into cold idle, need to wait for acknowledgement
4821 // so that fast mixer stops doing I/O.
4822 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4823 pauseAudioWatchdog = true;
4824 }
Eric Laurent81784c32012-11-19 14:55:58 -08004825 }
4826 if (sq != NULL) {
4827 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004828 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4829 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4830 // when bringing the output sink into standby.)
4831 //
4832 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4833 //
4834 // This occurs with BT suspend when we idle the FastMixer with
4835 // active tracks, which may be added or removed.
4836 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004837 }
4838#ifdef AUDIO_WATCHDOG
4839 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4840 mAudioWatchdog->pause();
4841 }
4842#endif
4843
4844 // Now perform the deferred reset on fast tracks that have stopped
4845 while (resetMask != 0) {
4846 size_t i = __builtin_ctz(resetMask);
4847 ALOG_ASSERT(i < count);
4848 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004849 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004850 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4851 track->reset();
4852 }
4853
Andy Hung80d03d22018-04-10 10:32:11 -07004854 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4855 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4856 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4857 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4858 // See also the implementation of destroyTrack_l().
4859 for (const auto &track : *tracksToRemove) {
4860 const int name = track->name();
4861 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4862 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4863 }
4864 }
4865
Eric Laurent81784c32012-11-19 14:55:58 -08004866 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004868
Eric Laurent97d547d2014-09-02 14:45:53 -07004869 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4870 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004871 }
4872
4873 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004874 // as long as there are effects we should clear the effects buffer, to avoid
4875 // passing a non-clean buffer to the effect chain
4876 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004877 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004878 // sink or mix buffer must be cleared if all tracks are connected to an
4879 // effect chain as in this case the mixer will not write to the sink or mix buffer
4880 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4882 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004883 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004884 if (mMixerBufferValid) {
4885 memset(mMixerBuffer, 0, mMixerBufferSize);
4886 // TODO: In testing, mSinkBuffer below need not be cleared because
4887 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4888 // after mixing.
4889 //
4890 // To enforce this guarantee:
4891 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4892 // (mixedTracks == 0 && fastTracks > 0))
4893 // must imply MIXER_TRACKS_READY.
4894 // Later, we may clear buffers regardless, and skip much of this logic.
4895 }
Andy Hung98ef9782014-03-04 14:46:50 -08004896 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004897 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004898 }
4899
4900 // if any fast tracks, then status is ready
4901 mMixerStatusIgnoringFastTracks = mixerStatus;
4902 if (fastTracks > 0) {
4903 mixerStatus = MIXER_TRACKS_READY;
4904 }
4905 return mixerStatus;
4906}
4907
Eric Laurentad7dd962016-09-22 12:38:37 -07004908// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004909uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004910{
4911 uint32_t trackCount = 0;
4912 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004913 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004914 trackCount++;
4915 }
4916 }
4917 return trackCount;
4918}
4919
Andy Hung1bc088a2018-02-09 15:57:31 -08004920// isTrackAllowed_l() must be called with ThreadBase::mLock held
4921bool AudioFlinger::MixerThread::isTrackAllowed_l(
4922 audio_channel_mask_t channelMask, audio_format_t format,
4923 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004924{
Andy Hung1bc088a2018-02-09 15:57:31 -08004925 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4926 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004927 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004928 // Check validity as we don't call AudioMixer::create() here.
4929 if (!AudioMixer::isValidFormat(format)) {
4930 ALOGW("%s: invalid format: %#x", __func__, format);
4931 return false;
4932 }
4933 if (!AudioMixer::isValidChannelMask(channelMask)) {
4934 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4935 return false;
4936 }
4937 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004938}
4939
Eric Laurent10351942014-05-08 18:49:52 -07004940// checkForNewParameter_l() must be called with ThreadBase::mLock held
4941bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4942 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004943{
Eric Laurent81784c32012-11-19 14:55:58 -08004944 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004945 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004946
Eric Laurent10351942014-05-08 18:49:52 -07004947 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004948
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004949 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004950
Eric Laurent10351942014-05-08 18:49:52 -07004951 AudioParameter param = AudioParameter(keyValuePair);
4952 int value;
4953 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4954 reconfig = true;
4955 }
4956 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004957 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004958 status = BAD_VALUE;
4959 } else {
4960 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004961 reconfig = true;
4962 }
Eric Laurent10351942014-05-08 18:49:52 -07004963 }
4964 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004965 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004966 status = BAD_VALUE;
4967 } else {
4968 // no need to save value, since it's constant
4969 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004970 }
Eric Laurent10351942014-05-08 18:49:52 -07004971 }
4972 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4973 // do not accept frame count changes if tracks are open as the track buffer
4974 // size depends on frame count and correct behavior would not be guaranteed
4975 // if frame count is changed after track creation
4976 if (!mTracks.isEmpty()) {
4977 status = INVALID_OPERATION;
4978 } else {
4979 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004980 }
Eric Laurent10351942014-05-08 18:49:52 -07004981 }
4982 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004983#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004984 // when changing the audio output device, call addBatteryData to notify
4985 // the change
4986 if (mOutDevice != value) {
4987 uint32_t params = 0;
4988 // check whether speaker is on
4989 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4990 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004991 }
Eric Laurent10351942014-05-08 18:49:52 -07004992
4993 audio_devices_t deviceWithoutSpeaker
4994 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4995 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004996 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004997 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4998 }
4999
5000 if (params != 0) {
5001 addBatteryData(params);
5002 }
5003 }
Eric Laurent81784c32012-11-19 14:55:58 -08005004#endif
5005
Eric Laurent10351942014-05-08 18:49:52 -07005006 // forward device change to effects that have requested to be
5007 // aware of attached audio device.
5008 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005009 a2dpDeviceChanged =
5010 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005011 mOutDevice = value;
5012 for (size_t i = 0; i < mEffectChains.size(); i++) {
5013 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005014 }
5015 }
Eric Laurent10351942014-05-08 18:49:52 -07005016 }
Eric Laurent81784c32012-11-19 14:55:58 -08005017
Eric Laurent10351942014-05-08 18:49:52 -07005018 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005019 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005020 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005021 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005022 mStandby = true;
5023 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005024 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005025 }
Eric Laurent10351942014-05-08 18:49:52 -07005026 if (status == NO_ERROR && reconfig) {
5027 readOutputParameters_l();
5028 delete mAudioMixer;
5029 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005030 for (const auto &track : mTracks) {
5031 const int name = track->name();
5032 status_t status = mAudioMixer->create(
5033 name,
5034 track->mChannelMask,
5035 track->mFormat,
5036 track->mSessionId);
5037 ALOGW_IF(status != NO_ERROR,
5038 "%s: cannot create track name"
5039 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5040 __func__,
5041 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005042 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005043 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005044 }
Eric Laurent81784c32012-11-19 14:55:58 -08005045 }
5046
Eric Laurent42537be2016-01-08 17:16:42 -08005047 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005048}
5049
5050
5051void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5052{
Eric Laurent81784c32012-11-19 14:55:58 -08005053 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005054 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005055 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005056 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08005057
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005058 if (hasFastMixer()) {
5059 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5060
5061 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5062 // while we are dumping it. It may be inconsistent, but it won't mutate!
5063 // This is a large object so we place it on the heap.
5064 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5065 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
5066 copy->dump(fd);
5067 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08005068
5069#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005070 // Similar for state queue
5071 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5072 observerCopy.dump(fd);
5073 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5074 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005075#endif
5076
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005077#ifdef AUDIO_WATCHDOG
5078 if (mAudioWatchdog != 0) {
5079 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5080 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5081 wdCopy.dump(fd);
5082 }
5083#endif
5084
5085 } else {
5086 dprintf(fd, " No FastMixer\n");
5087 }
Eric Laurent81784c32012-11-19 14:55:58 -08005088}
5089
5090uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5091{
5092 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5093}
5094
5095uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5096{
5097 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5098}
5099
5100void AudioFlinger::MixerThread::cacheParameters_l()
5101{
5102 PlaybackThread::cacheParameters_l();
5103
5104 // FIXME: Relaxed timing because of a certain device that can't meet latency
5105 // Should be reduced to 2x after the vendor fixes the driver issue
5106 // increase threshold again due to low power audio mode. The way this warning
5107 // threshold is calculated and its usefulness should be reconsidered anyway.
5108 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5109}
5110
5111// ----------------------------------------------------------------------------
5112
5113AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005114 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5115 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005116{
5117}
5118
Eric Laurentbfb1b832013-01-07 09:53:42 -08005119AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5120 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005121 ThreadBase::type_t type, bool systemReady)
5122 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005123 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005124{
5125}
5126
Eric Laurent81784c32012-11-19 14:55:58 -08005127AudioFlinger::DirectOutputThread::~DirectOutputThread()
5128{
5129}
5130
Eric Laurent5850c4c2016-11-10 13:04:31 -08005131void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005132{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005133 float left, right;
5134
5135 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5136 left = right = 0;
5137 } else {
5138 float typeVolume = mStreamTypes[track->streamType()].volume;
5139 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005140 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005141
Andy Hung10cbff12017-02-21 17:30:14 -08005142 // Get volumeshaper scaling
5143 std::pair<float /* volume */, bool /* active */>
5144 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005145 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005146 v *= vh.first;
5147 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005148
Glenn Kastenc56f3422014-03-21 17:53:17 -07005149 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5150 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5151 if (left > GAIN_FLOAT_UNITY) {
5152 left = GAIN_FLOAT_UNITY;
5153 }
5154 left *= v;
5155 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5156 if (right > GAIN_FLOAT_UNITY) {
5157 right = GAIN_FLOAT_UNITY;
5158 }
5159 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005160 }
5161
5162 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005163 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005164 if (left != mLeftVolFloat || right != mRightVolFloat) {
5165 mLeftVolFloat = left;
5166 mRightVolFloat = right;
5167
5168 // Convert volumes from float to 8.24
5169 uint32_t vl = (uint32_t)(left * (1 << 24));
5170 uint32_t vr = (uint32_t)(right * (1 << 24));
5171
5172 // Delegate volume control to effect in track effect chain if needed
5173 // only one effect chain can be present on DirectOutputThread, so if
5174 // there is one, the track is connected to it
5175 if (!mEffectChains.isEmpty()) {
5176 mEffectChains[0]->setVolume_l(&vl, &vr);
5177 left = (float)vl / (1 << 24);
5178 right = (float)vr / (1 << 24);
5179 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005180 status_t result = mOutput->stream->setVolume(left, right);
5181 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005182 }
5183 }
5184}
5185
Phil Burk43b4dcc2015-06-09 16:53:44 -07005186void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5187{
5188 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005189 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005190
Eric Laurent0f0631e2015-07-06 18:01:25 -07005191 if (previousTrack != 0 && latestTrack != 0) {
5192 if (mType == DIRECT) {
5193 if (previousTrack.get() != latestTrack.get()) {
5194 mFlushPending = true;
5195 }
5196 } else /* mType == OFFLOAD */ {
5197 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5198 mFlushPending = true;
5199 }
5200 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005201 }
5202 PlaybackThread::onAddNewTrack_l();
5203}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005204
Eric Laurent81784c32012-11-19 14:55:58 -08005205AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5206 Vector< sp<Track> > *tracksToRemove
5207)
5208{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005209 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005210 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005211 bool doHwPause = false;
5212 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005213
5214 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005215 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005216 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005217 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005218 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005219 continue;
5220 }
5221
Eric Laurent5850c4c2016-11-10 13:04:31 -08005222 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005223#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005224 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005225#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005226 // Only consider last track started for volume and mixer state control.
5227 // In theory an older track could underrun and restart after the new one starts
5228 // but as we only care about the transition phase between two tracks on a
5229 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005230 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005231 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005232
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005233 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005234 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005235 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005236 doHwPause = true;
5237 mHwPaused = true;
5238 }
5239 tracksToRemove->add(track);
5240 } else if (track->isFlushPending()) {
5241 track->flushAck();
5242 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005243 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005244 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005245 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005246 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005247 if (last) {
5248 mLeftVolFloat = mRightVolFloat = -1.0;
5249 if (mHwPaused) {
5250 doHwResume = true;
5251 mHwPaused = false;
5252 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005253 }
5254 }
5255
Eric Laurent81784c32012-11-19 14:55:58 -08005256 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005257 // for all its buffers to be filled before processing it.
5258 // Allow draining the buffer in case the client
5259 // app does not call stop() and relies on underrun to stop:
5260 // hence the test on (track->mRetryCount > 1).
5261 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005262 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005263 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005264 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005265 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005266 minFrames = mNormalFrameCount;
5267 } else {
5268 minFrames = 1;
5269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270
Eric Laurentab5cdba2014-06-09 17:22:27 -07005271 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5272 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005273 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005274 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005275
5276 if (track->mFillingUpStatus == Track::FS_FILLED) {
5277 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005278 if (last) {
5279 // make sure processVolume_l() will apply new volume even if 0
5280 mLeftVolFloat = mRightVolFloat = -1.0;
5281 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005282 if (!mHwSupportsPause) {
5283 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005284 }
5285 }
5286
5287 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005288 processVolume_l(track, last);
5289 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005290 sp<Track> previousTrack = mPreviousTrack.promote();
5291 if (previousTrack != 0) {
5292 if (track != previousTrack.get()) {
5293 // Flush any data still being written from last track
5294 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005295 // Invalidate previous track to force a seek when resuming.
5296 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005297 }
5298 }
5299 mPreviousTrack = track;
5300
Eric Laurentd595b7c2013-04-03 17:27:56 -07005301 // reset retry count
5302 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005303 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005304 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005305 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005306 doHwResume = true;
5307 mHwPaused = false;
5308 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005309 }
Eric Laurent81784c32012-11-19 14:55:58 -08005310 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005311 // clear effect chain input buffer if the last active track started underruns
5312 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005313 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005314 mEffectChains[0]->clearInputBuffer();
5315 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005316 if (track->isStopping_1()) {
5317 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005318 if (last && mHwPaused) {
5319 doHwResume = true;
5320 mHwPaused = false;
5321 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005322 }
5323 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5324 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005325 // We have consumed all the buffers of this track.
5326 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005327 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005328 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005329 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5330 } else {
5331 audioHALFrames = 0;
5332 }
5333
Andy Hung818e7a32016-02-16 18:08:07 -08005334 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005335 if (mStandby || !last ||
5336 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005337 if (track->isStopping_2()) {
5338 track->mState = TrackBase::STOPPED;
5339 }
Eric Laurent81784c32012-11-19 14:55:58 -08005340 if (track->isStopped()) {
5341 track->reset();
5342 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005343 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005344 }
5345 } else {
5346 // No buffers for this track. Give it a few chances to
5347 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005348 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005349 if (--(track->mRetryCount) <= 0) {
5350 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005351 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005352 // indicate to client process that the track was disabled because of underrun;
5353 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005354 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005355 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005356 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5357 "minFrames = %u, mFormat = %#x",
5358 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005359 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005360 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005361 doHwPause = true;
5362 mHwPaused = true;
5363 }
Eric Laurent81784c32012-11-19 14:55:58 -08005364 }
5365 }
5366 }
5367 }
5368
Eric Laurentd1f69b02014-12-15 14:33:13 -08005369 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005370 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005371 for (size_t i = 0; i < mTracks.size(); i++) {
5372 if (mTracks[i]->isFlushPending()) {
5373 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005374 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005375 }
5376 }
5377 }
5378
5379 // make sure the pause/flush/resume sequence is executed in the right order.
5380 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5381 // before flush and then resume HW. This can happen in case of pause/flush/resume
5382 // if resume is received before pause is executed.
5383 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005384 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005385 status_t result = mOutput->stream->pause();
5386 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005387 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005388 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005389 flushHw_l();
5390 }
5391 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005392 status_t result = mOutput->stream->resume();
5393 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005394 }
Eric Laurent81784c32012-11-19 14:55:58 -08005395 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005396 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005397
5398 return mixerStatus;
5399}
5400
5401void AudioFlinger::DirectOutputThread::threadLoop_mix()
5402{
Eric Laurent81784c32012-11-19 14:55:58 -08005403 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005404 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005405 // output audio to hardware
5406 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005407 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005408 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005409 status_t status = mActiveTrack->getNextBuffer(&buffer);
5410 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005411 // no need to pad with 0 for compressed audio
5412 if (audio_has_proportional_frames(mFormat)) {
5413 memset(curBuf, 0, frameCount * mFrameSize);
5414 }
Eric Laurent81784c32012-11-19 14:55:58 -08005415 break;
5416 }
5417 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5418 frameCount -= buffer.frameCount;
5419 curBuf += buffer.frameCount * mFrameSize;
5420 mActiveTrack->releaseBuffer(&buffer);
5421 }
Andy Hung2098f272014-02-27 14:00:06 -08005422 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005423 mSleepTimeUs = 0;
5424 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005425 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005426}
5427
5428void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5429{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005430 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005431 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005432 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005433 return;
5434 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005435 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005436 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005437 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005438 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005439 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005440 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005441 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005442 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005443 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005444 }
5445}
5446
Eric Laurentd1f69b02014-12-15 14:33:13 -08005447void AudioFlinger::DirectOutputThread::threadLoop_exit()
5448{
5449 {
5450 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005451 for (size_t i = 0; i < mTracks.size(); i++) {
5452 if (mTracks[i]->isFlushPending()) {
5453 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005454 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005455 }
5456 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005457 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005458 flushHw_l();
5459 }
5460 }
5461 PlaybackThread::threadLoop_exit();
5462}
5463
5464// must be called with thread mutex locked
5465bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5466{
5467 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005468 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005469
vivek mehta9cd7ad12016-03-17 00:18:29 -07005470 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5471 return !mStandby;
5472 }
5473
Eric Laurentd1f69b02014-12-15 14:33:13 -08005474 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5475 // after a timeout and we will enter standby then.
5476 if (mTracks.size() > 0) {
5477 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005478 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5479 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005480 }
5481
Eric Laurent5cff4032015-05-26 13:49:58 -07005482 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005483}
5484
Eric Laurent10351942014-05-08 18:49:52 -07005485// checkForNewParameter_l() must be called with ThreadBase::mLock held
5486bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5487 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005488{
5489 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005490 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005491
Eric Laurent10351942014-05-08 18:49:52 -07005492 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005493
Eric Laurent10351942014-05-08 18:49:52 -07005494 AudioParameter param = AudioParameter(keyValuePair);
5495 int value;
5496 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5497 // forward device change to effects that have requested to be
5498 // aware of attached audio device.
5499 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005500 a2dpDeviceChanged =
5501 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005502 mOutDevice = value;
5503 for (size_t i = 0; i < mEffectChains.size(); i++) {
5504 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005505 }
5506 }
Eric Laurent81784c32012-11-19 14:55:58 -08005507 }
Eric Laurent10351942014-05-08 18:49:52 -07005508 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5509 // do not accept frame count changes if tracks are open as the track buffer
5510 // size depends on frame count and correct behavior would not be garantied
5511 // if frame count is changed after track creation
5512 if (!mTracks.isEmpty()) {
5513 status = INVALID_OPERATION;
5514 } else {
5515 reconfig = true;
5516 }
5517 }
5518 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005519 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005520 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005521 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005522 mStandby = true;
5523 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005524 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005525 }
5526 if (status == NO_ERROR && reconfig) {
5527 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005528 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005529 }
5530 }
5531
Eric Laurent42537be2016-01-08 17:16:42 -08005532 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005533}
5534
5535uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5536{
5537 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005538 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005539 time = PlaybackThread::activeSleepTimeUs();
5540 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005541 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005542 }
5543 return time;
5544}
5545
5546uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5547{
5548 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005549 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005550 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5551 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005552 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005553 }
5554 return time;
5555}
5556
5557uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5558{
5559 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005560 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005561 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5562 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005563 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005564 }
5565 return time;
5566}
5567
5568void AudioFlinger::DirectOutputThread::cacheParameters_l()
5569{
5570 PlaybackThread::cacheParameters_l();
5571
5572 // use shorter standby delay as on normal output to release
5573 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005574 // no delay on outputs with HW A/V sync
5575 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005576 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005577 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005578 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005579 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005580 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005581 }
Eric Laurent81784c32012-11-19 14:55:58 -08005582}
5583
Eric Laurente659ef42014-09-29 13:06:46 -07005584void AudioFlinger::DirectOutputThread::flushHw_l()
5585{
Phil Burk062e67a2015-02-11 13:40:50 -08005586 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005587 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005588 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005589}
5590
Andy Hung10cbff12017-02-21 17:30:14 -08005591int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5592 // If a VolumeShaper is active, we must wake up periodically to update volume.
5593 const int64_t NS_PER_MS = 1000000;
5594 return mVolumeShaperActive ?
5595 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5596}
5597
Eric Laurent81784c32012-11-19 14:55:58 -08005598// ----------------------------------------------------------------------------
5599
Eric Laurentbfb1b832013-01-07 09:53:42 -08005600AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005601 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005602 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005603 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005604 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005605 mDrainSequence(0),
5606 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005607{
5608}
5609
5610AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5611{
5612}
5613
5614void AudioFlinger::AsyncCallbackThread::onFirstRef()
5615{
5616 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5617}
5618
5619bool AudioFlinger::AsyncCallbackThread::threadLoop()
5620{
5621 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005622 uint32_t writeAckSequence;
5623 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005624 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005625
5626 {
5627 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005628 while (!((mWriteAckSequence & 1) ||
5629 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005630 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005631 exitPending())) {
5632 mWaitWorkCV.wait(mLock);
5633 }
5634
Eric Laurentbfb1b832013-01-07 09:53:42 -08005635 if (exitPending()) {
5636 break;
5637 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005638 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5639 mWriteAckSequence, mDrainSequence);
5640 writeAckSequence = mWriteAckSequence;
5641 mWriteAckSequence &= ~1;
5642 drainSequence = mDrainSequence;
5643 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005644 asyncError = mAsyncError;
5645 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005646 }
5647 {
Eric Laurent4de95592013-09-26 15:28:21 -07005648 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5649 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005650 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005651 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005652 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005653 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005654 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005655 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005656 if (asyncError) {
5657 playbackThread->onAsyncError();
5658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005659 }
5660 }
5661 }
5662 return false;
5663}
5664
5665void AudioFlinger::AsyncCallbackThread::exit()
5666{
5667 ALOGV("AsyncCallbackThread::exit");
5668 Mutex::Autolock _l(mLock);
5669 requestExit();
5670 mWaitWorkCV.broadcast();
5671}
5672
Eric Laurent3b4529e2013-09-05 18:09:19 -07005673void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005674{
5675 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005676 // bit 0 is cleared
5677 mWriteAckSequence = sequence << 1;
5678}
5679
5680void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5681{
5682 Mutex::Autolock _l(mLock);
5683 // ignore unexpected callbacks
5684 if (mWriteAckSequence & 2) {
5685 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005686 mWaitWorkCV.signal();
5687 }
5688}
5689
Eric Laurent3b4529e2013-09-05 18:09:19 -07005690void AudioFlinger::AsyncCallbackThread::setDraining(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 mDrainSequence = sequence << 1;
5695}
5696
5697void AudioFlinger::AsyncCallbackThread::resetDraining()
5698{
5699 Mutex::Autolock _l(mLock);
5700 // ignore unexpected callbacks
5701 if (mDrainSequence & 2) {
5702 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703 mWaitWorkCV.signal();
5704 }
5705}
5706
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005707void AudioFlinger::AsyncCallbackThread::setAsyncError()
5708{
5709 Mutex::Autolock _l(mLock);
5710 mAsyncError = true;
5711 mWaitWorkCV.signal();
5712}
5713
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714
5715// ----------------------------------------------------------------------------
5716AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005717 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5718 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005719 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5720 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005721{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005722 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005723 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005724 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005725}
5726
Eric Laurentbfb1b832013-01-07 09:53:42 -08005727void AudioFlinger::OffloadThread::threadLoop_exit()
5728{
5729 if (mFlushPending || mHwPaused) {
5730 // If a flush is pending or track was paused, just discard buffered data
5731 flushHw_l();
5732 } else {
5733 mMixerStatus = MIXER_DRAIN_ALL;
5734 threadLoop_drain();
5735 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005736 if (mUseAsyncWrite) {
5737 ALOG_ASSERT(mCallbackThread != 0);
5738 mCallbackThread->exit();
5739 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005740 PlaybackThread::threadLoop_exit();
5741}
5742
5743AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5744 Vector< sp<Track> > *tracksToRemove
5745)
5746{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005747 size_t count = mActiveTracks.size();
5748
5749 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005750 bool doHwPause = false;
5751 bool doHwResume = false;
5752
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005753 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005754
Eric Laurentbfb1b832013-01-07 09:53:42 -08005755 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005756 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005757 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005758#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005759 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005760#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005761 // Only consider last track started for volume and mixer state control.
5762 // In theory an older track could underrun and restart after the new one starts
5763 // but as we only care about the transition phase between two tracks on a
5764 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005765 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005766 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005767
Haynes Mathew George7844f672014-01-15 12:32:55 -08005768 if (track->isInvalid()) {
5769 ALOGW("An invalidated track shouldn't be in active list");
5770 tracksToRemove->add(track);
5771 continue;
5772 }
5773
5774 if (track->mState == TrackBase::IDLE) {
5775 ALOGW("An idle track shouldn't be in active list");
5776 continue;
5777 }
5778
Eric Laurentbfb1b832013-01-07 09:53:42 -08005779 if (track->isPausing()) {
5780 track->setPaused();
5781 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005782 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005783 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005784 mHwPaused = true;
5785 }
5786 // If we were part way through writing the mixbuffer to
5787 // the HAL we must save this until we resume
5788 // BUG - this will be wrong if a different track is made active,
5789 // in that case we want to discard the pending data in the
5790 // mixbuffer and tell the client to present it again when the
5791 // track is resumed
5792 mPausedWriteLength = mCurrentWriteLength;
5793 mPausedBytesRemaining = mBytesRemaining;
5794 mBytesRemaining = 0; // stop writing
5795 }
5796 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005797 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005798 if (track->isStopping_1()) {
5799 track->mRetryCount = kMaxTrackStopRetriesOffload;
5800 } else {
5801 track->mRetryCount = kMaxTrackRetriesOffload;
5802 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005803 track->flushAck();
5804 if (last) {
5805 mFlushPending = true;
5806 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005807 } else if (track->isResumePending()){
5808 track->resumeAck();
5809 if (last) {
5810 if (mPausedBytesRemaining) {
5811 // Need to continue write that was interrupted
5812 mCurrentWriteLength = mPausedWriteLength;
5813 mBytesRemaining = mPausedBytesRemaining;
5814 mPausedBytesRemaining = 0;
5815 }
5816 if (mHwPaused) {
5817 doHwResume = true;
5818 mHwPaused = false;
5819 // threadLoop_mix() will handle the case that we need to
5820 // resume an interrupted write
5821 }
5822 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005823 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005824
Eric Laurent3df841a2016-07-15 15:15:40 -07005825 mLeftVolFloat = mRightVolFloat = -1.0;
5826
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005827 // Do not handle new data in this iteration even if track->framesReady()
5828 mixerStatus = MIXER_TRACKS_ENABLED;
5829 }
5830 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005831 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005832 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005833 if (track->mFillingUpStatus == Track::FS_FILLED) {
5834 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005835 if (last) {
5836 // make sure processVolume_l() will apply new volume even if 0
5837 mLeftVolFloat = mRightVolFloat = -1.0;
5838 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005839 }
5840
5841 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005842 sp<Track> previousTrack = mPreviousTrack.promote();
5843 if (previousTrack != 0) {
5844 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005845 // Flush any data still being written from last track
5846 mBytesRemaining = 0;
5847 if (mPausedBytesRemaining) {
5848 // Last track was paused so we also need to flush saved
5849 // mixbuffer state and invalidate track so that it will
5850 // re-submit that unwritten data when it is next resumed
5851 mPausedBytesRemaining = 0;
5852 // Invalidate is a bit drastic - would be more efficient
5853 // to have a flag to tell client that some of the
5854 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005855 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005856 }
5857 // flush data already sent to the DSP if changing audio session as audio
5858 // comes from a different source. Also invalidate previous track to force a
5859 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005860 if (previousTrack->sessionId() != track->sessionId()) {
5861 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005862 }
5863 }
5864 }
5865 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005866 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005867 if (track->isStopping_1()) {
5868 track->mRetryCount = kMaxTrackStopRetriesOffload;
5869 } else {
5870 track->mRetryCount = kMaxTrackRetriesOffload;
5871 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005872 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005873 mixerStatus = MIXER_TRACKS_READY;
5874 }
5875 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005876 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005877 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005878 if (--(track->mRetryCount) <= 0) {
5879 // Hardware buffer can hold a large amount of audio so we must
5880 // wait for all current track's data to drain before we say
5881 // that the track is stopped.
5882 if (mBytesRemaining == 0) {
5883 // Only start draining when all data in mixbuffer
5884 // has been written
5885 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5886 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5887 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5888 if (last && !mStandby) {
5889 // do not modify drain sequence if we are already draining. This happens
5890 // when resuming from pause after drain.
5891 if ((mDrainSequence & 1) == 0) {
5892 mSleepTimeUs = 0;
5893 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5894 mixerStatus = MIXER_DRAIN_TRACK;
5895 mDrainSequence += 2;
5896 }
5897 if (mHwPaused) {
5898 // It is possible to move from PAUSED to STOPPING_1 without
5899 // a resume so we must ensure hardware is running
5900 doHwResume = true;
5901 mHwPaused = false;
5902 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005903 }
5904 }
Eric Laurente93cc032016-05-05 10:15:10 -07005905 } else if (last) {
5906 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5907 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005908 }
5909 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005910 // Drain has completed or we are in standby, signal presentation complete
5911 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005912 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005913 uint32_t latency = 0;
5914 status_t result = mOutput->stream->getLatency(&latency);
5915 ALOGE_IF(result != OK,
5916 "Error when retrieving output stream latency: %d", result);
5917 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005918 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005919 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005920 track->presentationComplete(framesWritten, audioHALFrames);
5921 track->reset();
5922 tracksToRemove->add(track);
5923 }
5924 } else {
5925 // No buffers for this track. Give it a few chances to
5926 // fill a buffer, then remove it from active list.
5927 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005928 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005929 uint64_t position = 0;
5930 struct timespec unused;
5931 // The running check restarts the retry counter at least once.
5932 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5933 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5934 running = true;
5935 mOffloadUnderrunPosition = position;
5936 }
5937 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005938 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5939 (long long)position, (long long)mOffloadUnderrunPosition);
5940 }
5941 if (running) { // still running, give us more time.
5942 track->mRetryCount = kMaxTrackRetriesOffload;
5943 } else {
5944 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5945 track->name());
5946 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005947 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005948 // it will then automatically call start() when data is available
5949 track->disable();
5950 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005951 } else if (last){
5952 mixerStatus = MIXER_TRACKS_ENABLED;
5953 }
5954 }
5955 }
5956 // compute volume for this track
5957 processVolume_l(track, last);
5958 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005959
Eric Laurentea0fade2013-10-04 16:23:48 -07005960 // make sure the pause/flush/resume sequence is executed in the right order.
5961 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5962 // before flush and then resume HW. This can happen in case of pause/flush/resume
5963 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005964 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005965 status_t result = mOutput->stream->pause();
5966 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005967 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005968 if (mFlushPending) {
5969 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005970 }
Eric Laurentfd477972013-10-25 18:10:40 -07005971 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005972 status_t result = mOutput->stream->resume();
5973 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005974 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005975
Eric Laurentbfb1b832013-01-07 09:53:42 -08005976 // remove all the tracks that need to be...
5977 removeTracks_l(*tracksToRemove);
5978
5979 return mixerStatus;
5980}
5981
Eric Laurentbfb1b832013-01-07 09:53:42 -08005982// must be called with thread mutex locked
5983bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5984{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005985 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5986 mWriteAckSequence, mDrainSequence);
5987 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005988 return true;
5989 }
5990 return false;
5991}
5992
Eric Laurentbfb1b832013-01-07 09:53:42 -08005993bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5994{
5995 Mutex::Autolock _l(mLock);
5996 return waitingAsyncCallback_l();
5997}
5998
5999void AudioFlinger::OffloadThread::flushHw_l()
6000{
Eric Laurente659ef42014-09-29 13:06:46 -07006001 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006002 // Flush anything still waiting in the mixbuffer
6003 mCurrentWriteLength = 0;
6004 mBytesRemaining = 0;
6005 mPausedWriteLength = 0;
6006 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006007 // reset bytes written count to reflect that DSP buffers are empty after flush.
6008 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006009 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006010
Eric Laurentbfb1b832013-01-07 09:53:42 -08006011 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006012 // discard any pending drain or write ack by incrementing sequence
6013 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6014 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006015 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006016 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6017 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006018 }
6019}
6020
Haynes Mathew George05317d22016-05-03 16:34:26 -07006021void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6022{
6023 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006024 if (PlaybackThread::invalidateTracks_l(streamType)) {
6025 mFlushPending = true;
6026 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006027}
6028
Eric Laurentbfb1b832013-01-07 09:53:42 -08006029// ----------------------------------------------------------------------------
6030
Eric Laurent81784c32012-11-19 14:55:58 -08006031AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006032 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006033 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006034 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006035 mWaitTimeMs(UINT_MAX)
6036{
6037 addOutputTrack(mainThread);
6038}
6039
6040AudioFlinger::DuplicatingThread::~DuplicatingThread()
6041{
6042 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6043 mOutputTracks[i]->destroy();
6044 }
6045}
6046
6047void AudioFlinger::DuplicatingThread::threadLoop_mix()
6048{
6049 // mix buffers...
6050 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006051 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006052 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006053 if (mMixerBufferValid) {
6054 memset(mMixerBuffer, 0, mMixerBufferSize);
6055 } else {
6056 memset(mSinkBuffer, 0, mSinkBufferSize);
6057 }
Eric Laurent81784c32012-11-19 14:55:58 -08006058 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006059 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006060 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006061 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006062 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006063}
6064
6065void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6066{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006067 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006068 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006069 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006070 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006071 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006072 }
6073 } else if (mBytesWritten != 0) {
6074 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6075 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006076 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006077 } else {
6078 // flush remaining overflow buffers in output tracks
6079 writeFrames = 0;
6080 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006081 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006082 }
6083}
6084
Eric Laurentbfb1b832013-01-07 09:53:42 -08006085ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006086{
6087 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08006088 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08006089 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006090 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006091 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006092}
6093
6094void AudioFlinger::DuplicatingThread::threadLoop_standby()
6095{
6096 // DuplicatingThread implements standby by stopping all tracks
6097 for (size_t i = 0; i < outputTracks.size(); i++) {
6098 outputTracks[i]->stop();
6099 }
6100}
6101
Andy Hung1bc088a2018-02-09 15:57:31 -08006102void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6103{
6104 MixerThread::dumpInternals(fd, args);
6105
6106 std::stringstream ss;
6107 const size_t numTracks = mOutputTracks.size();
6108 ss << " " << numTracks << " OutputTracks";
6109 if (numTracks > 0) {
6110 ss << ":";
6111 for (const auto &track : mOutputTracks) {
6112 const sp<ThreadBase> thread = track->thread().promote();
6113 ss << " (" << track->name() << " : ";
6114 if (thread.get() != nullptr) {
6115 ss << thread.get() << ", " << thread->id();
6116 } else {
6117 ss << "null";
6118 }
6119 ss << ")";
6120 }
6121 }
6122 ss << "\n";
6123 std::string result = ss.str();
6124 write(fd, result.c_str(), result.size());
6125}
6126
Eric Laurent81784c32012-11-19 14:55:58 -08006127void AudioFlinger::DuplicatingThread::saveOutputTracks()
6128{
6129 outputTracks = mOutputTracks;
6130}
6131
6132void AudioFlinger::DuplicatingThread::clearOutputTracks()
6133{
6134 outputTracks.clear();
6135}
6136
6137void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6138{
6139 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006140 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6141 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6142 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6143 const size_t frameCount =
6144 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6145 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6146 // from different OutputTracks and their associated MixerThreads (e.g. one may
6147 // nearly empty and the other may be dropping data).
6148
6149 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006150 this,
6151 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006152 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006153 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006154 frameCount,
6155 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006156 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6157 if (status != NO_ERROR) {
6158 ALOGE("addOutputTrack() initCheck failed %d", status);
6159 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006160 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006161 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6162 mOutputTracks.add(outputTrack);
6163 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6164 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006165}
6166
6167void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6168{
6169 Mutex::Autolock _l(mLock);
6170 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6171 if (mOutputTracks[i]->thread() == thread) {
6172 mOutputTracks[i]->destroy();
6173 mOutputTracks.removeAt(i);
6174 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006175 if (thread->getOutput() == mOutput) {
6176 mOutput = NULL;
6177 }
Eric Laurent81784c32012-11-19 14:55:58 -08006178 return;
6179 }
6180 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006181 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006182}
6183
6184// caller must hold mLock
6185void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6186{
6187 mWaitTimeMs = UINT_MAX;
6188 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6189 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6190 if (strong != 0) {
6191 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6192 if (waitTimeMs < mWaitTimeMs) {
6193 mWaitTimeMs = waitTimeMs;
6194 }
6195 }
6196 }
6197}
6198
6199
6200bool AudioFlinger::DuplicatingThread::outputsReady(
6201 const SortedVector< sp<OutputTrack> > &outputTracks)
6202{
6203 for (size_t i = 0; i < outputTracks.size(); i++) {
6204 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6205 if (thread == 0) {
6206 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6207 outputTracks[i].get());
6208 return false;
6209 }
6210 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6211 // see note at standby() declaration
6212 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6213 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6214 thread.get());
6215 return false;
6216 }
6217 }
6218 return true;
6219}
6220
Kevin Rocard12381092018-04-11 09:19:59 -07006221void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6222 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006223{
Kevin Rocard12381092018-04-11 09:19:59 -07006224 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6225 outputTrack->setMetadatas(metadata.tracks);
6226 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006227}
6228
Eric Laurent81784c32012-11-19 14:55:58 -08006229uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6230{
6231 return (mWaitTimeMs * 1000) / 2;
6232}
6233
6234void AudioFlinger::DuplicatingThread::cacheParameters_l()
6235{
6236 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6237 updateWaitTime_l();
6238
6239 MixerThread::cacheParameters_l();
6240}
6241
Eric Laurent6acd1d42017-01-04 14:23:29 -08006242
Eric Laurent81784c32012-11-19 14:55:58 -08006243// ----------------------------------------------------------------------------
6244// Record
6245// ----------------------------------------------------------------------------
6246
6247AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6248 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006249 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006250 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006251 audio_devices_t inDevice,
6252 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006253 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006254 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006255 mInput(input),
6256 mActiveTracks(&this->mLocalLog),
6257 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006258 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006259 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006260 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6261 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006262 // mFastCapture below
6263 , mFastCaptureFutex(0)
6264 // mInputSource
6265 // mPipeSink
6266 // mPipeSource
6267 , mPipeFramesP2(0)
6268 // mPipeMemory
6269 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006270 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006271 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006272{
Glenn Kastend7dca052015-03-05 16:05:54 -08006273 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6274 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006275
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006276 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006277
6278 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006279 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006280 size_t numCounterOffers = 0;
6281 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006282#if !LOG_NDEBUG
6283 ssize_t index =
6284#else
6285 (void)
6286#endif
6287 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006288 ALOG_ASSERT(index == 0);
6289
6290 // initialize fast capture depending on configuration
6291 bool initFastCapture;
6292 switch (kUseFastCapture) {
6293 case FastCapture_Never:
6294 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006295 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006296 break;
6297 case FastCapture_Always:
6298 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006299 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006300 break;
6301 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006302 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006303 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6304 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6305 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006306 break;
6307 // case FastCapture_Dynamic:
6308 }
6309
6310 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006311 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006312 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006313 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6314 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006315 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006316 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006317 const sp<MemoryDealer> roHeap(readOnlyHeap());
6318 sp<IMemory> pipeMemory;
6319 if ((roHeap == 0) ||
6320 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006321 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6322 ALOGE("not enough memory for pipe buffer size=%zu; "
6323 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6324 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6325 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006326 goto failed;
6327 }
6328 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6329 memset(pipeBuffer, 0, pipeSize);
6330 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6331 const NBAIO_Format offers[1] = {format};
6332 size_t numCounterOffers = 0;
6333 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6334 ALOG_ASSERT(index == 0);
6335 mPipeSink = pipe;
6336 PipeReader *pipeReader = new PipeReader(*pipe);
6337 numCounterOffers = 0;
6338 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6339 ALOG_ASSERT(index == 0);
6340 mPipeSource = pipeReader;
6341 mPipeFramesP2 = pipeFramesP2;
6342 mPipeMemory = pipeMemory;
6343
6344 // create fast capture
6345 mFastCapture = new FastCapture();
6346 FastCaptureStateQueue *sq = mFastCapture->sq();
6347#ifdef STATE_QUEUE_DUMP
6348 // FIXME
6349#endif
6350 FastCaptureState *state = sq->begin();
6351 state->mCblk = NULL;
6352 state->mInputSource = mInputSource.get();
6353 state->mInputSourceGen++;
6354 state->mPipeSink = pipe;
6355 state->mPipeSinkGen++;
6356 state->mFrameCount = mFrameCount;
6357 state->mCommand = FastCaptureState::COLD_IDLE;
6358 // already done in constructor initialization list
6359 //mFastCaptureFutex = 0;
6360 state->mColdFutexAddr = &mFastCaptureFutex;
6361 state->mColdGen++;
6362 state->mDumpState = &mFastCaptureDumpState;
6363#ifdef TEE_SINK
6364 // FIXME
6365#endif
6366 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6367 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6368 sq->end();
6369 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6370
6371 // start the fast capture
6372 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6373 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006374 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006375 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006376#ifdef AUDIO_WATCHDOG
6377 // FIXME
6378#endif
6379
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006380 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006381 }
Andy Hung8946a282018-04-19 20:04:56 -07006382#ifdef TEE_SINK
6383 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6384 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6385#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006386failed: ;
6387
6388 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006389}
6390
Eric Laurent81784c32012-11-19 14:55:58 -08006391AudioFlinger::RecordThread::~RecordThread()
6392{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006393 if (mFastCapture != 0) {
6394 FastCaptureStateQueue *sq = mFastCapture->sq();
6395 FastCaptureState *state = sq->begin();
6396 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6397 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6398 if (old == -1) {
6399 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6400 }
6401 }
6402 state->mCommand = FastCaptureState::EXIT;
6403 sq->end();
6404 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6405 mFastCapture->join();
6406 mFastCapture.clear();
6407 }
6408 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006409 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006410 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006411}
6412
6413void AudioFlinger::RecordThread::onFirstRef()
6414{
Glenn Kastend7dca052015-03-05 16:05:54 -08006415 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006416}
6417
Eric Laurent555530a2017-02-07 18:17:24 -08006418void AudioFlinger::RecordThread::preExit()
6419{
6420 ALOGV(" preExit()");
6421 Mutex::Autolock _l(mLock);
6422 for (size_t i = 0; i < mTracks.size(); i++) {
6423 sp<RecordTrack> track = mTracks[i];
6424 track->invalidate();
6425 }
6426 mActiveTracks.clear();
6427 mStartStopCond.broadcast();
6428}
6429
Eric Laurent81784c32012-11-19 14:55:58 -08006430bool AudioFlinger::RecordThread::threadLoop()
6431{
Eric Laurent81784c32012-11-19 14:55:58 -08006432 nsecs_t lastWarning = 0;
6433
6434 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006435
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006436reacquire_wakelock:
6437 sp<RecordTrack> activeTrack;
6438 {
6439 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006440 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006441 }
6442
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006443 // used to request a deferred sleep, to be executed later while mutex is unlocked
6444 uint32_t sleepUs = 0;
6445
6446 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006447 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006448 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006449
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006450 // activeTracks accumulates a copy of a subset of mActiveTracks
6451 Vector< sp<RecordTrack> > activeTracks;
6452
Glenn Kasten735f45f2014-08-18 15:51:59 -07006453 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006454 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006455
Glenn Kasten735f45f2014-08-18 15:51:59 -07006456 // reference to a fast track which is about to be removed
6457 sp<RecordTrack> fastTrackToRemove;
6458
Eric Laurent81784c32012-11-19 14:55:58 -08006459 { // scope for mLock
6460 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006461
Eric Laurent021cf962014-05-13 10:18:14 -07006462 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006463
Eric Laurent000a4192014-01-29 15:17:32 -08006464 // check exitPending here because checkForNewParameters_l() and
6465 // checkForNewParameters_l() can temporarily release mLock
6466 if (exitPending()) {
6467 break;
6468 }
6469
Eric Laurent5c25d562016-07-13 17:17:45 -07006470 // sleep with mutex unlocked
6471 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006472 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006473 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6474 ATRACE_END();
6475 sleepUs = 0;
6476 continue;
6477 }
6478
Glenn Kasten2b806402013-11-20 16:37:38 -08006479 // if no active track(s), then standby and release wakelock
6480 size_t size = mActiveTracks.size();
6481 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006482 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006483 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006484 releaseWakeLock_l();
6485 ALOGV("RecordThread: loop stopping");
6486 // go to sleep
6487 mWaitWorkCV.wait(mLock);
6488 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006489 goto reacquire_wakelock;
6490 }
6491
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006492 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006493 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006494 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006495
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006496 activeTrack = mActiveTracks[i];
6497 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006498 if (activeTrack->isFastTrack()) {
6499 ALOG_ASSERT(fastTrackToRemove == 0);
6500 fastTrackToRemove = activeTrack;
6501 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006502 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006503 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006504 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006505 continue;
6506 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006507
6508 TrackBase::track_state activeTrackState = activeTrack->mState;
6509 switch (activeTrackState) {
6510
6511 case TrackBase::PAUSING:
6512 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006513 doBroadcast = true;
6514 size--;
6515 continue;
6516
6517 case TrackBase::STARTING_1:
6518 sleepUs = 10000;
6519 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006520 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006521 continue;
6522
6523 case TrackBase::STARTING_2:
6524 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006525 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006526 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006527 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006528 break;
6529
6530 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006531 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006532 break;
6533
6534 case TrackBase::IDLE:
6535 i++;
6536 continue;
6537
6538 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006539 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006540 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006541
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006542 activeTracks.add(activeTrack);
6543 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006544
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006545 if (activeTrack->isFastTrack()) {
6546 ALOG_ASSERT(!mFastTrackAvail);
6547 ALOG_ASSERT(fastTrack == 0);
6548 fastTrack = activeTrack;
6549 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006550 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006551
Andy Hungdae27702016-10-31 14:01:16 -07006552 mActiveTracks.updatePowerState(this);
6553
Kevin Rocard069c2712018-03-29 19:09:14 -07006554 updateMetadata_l();
6555
Eric Laurent5c25d562016-07-13 17:17:45 -07006556 if (allStopped) {
6557 standbyIfNotAlreadyInStandby();
6558 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006559 if (doBroadcast) {
6560 mStartStopCond.broadcast();
6561 }
6562
6563 // sleep if there are no active tracks to process
6564 if (activeTracks.size() == 0) {
6565 if (sleepUs == 0) {
6566 sleepUs = kRecordThreadSleepUs;
6567 }
6568 continue;
6569 }
6570 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006571
Eric Laurent81784c32012-11-19 14:55:58 -08006572 lockEffectChains_l(effectChains);
6573 }
6574
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006575 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006576
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006577 size_t size = effectChains.size();
6578 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006579 // thread mutex is not locked, but effect chain is locked
6580 effectChains[i]->process_l();
6581 }
6582
Glenn Kasten735f45f2014-08-18 15:51:59 -07006583 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006584 if (mFastCapture != 0) {
6585 FastCaptureStateQueue *sq = mFastCapture->sq();
6586 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006587 bool didModify = false;
6588 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006589 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6590 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6591 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6592 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6593 if (old == -1) {
6594 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6595 }
6596 }
6597 state->mCommand = FastCaptureState::READ_WRITE;
6598#if 0 // FIXME
6599 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006600 FastThreadDumpState::kSamplingNforLowRamDevice :
6601 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006602#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006603 didModify = true;
6604 }
6605 audio_track_cblk_t *cblkOld = state->mCblk;
6606 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6607 if (cblkNew != cblkOld) {
6608 state->mCblk = cblkNew;
6609 // block until acked if removing a fast track
6610 if (cblkOld != NULL) {
6611 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6612 }
6613 didModify = true;
6614 }
6615 sq->end(didModify);
6616 if (didModify) {
6617 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006618#if 0
6619 if (kUseFastCapture == FastCapture_Dynamic) {
6620 mNormalSource = mPipeSource;
6621 }
6622#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006623 }
6624 }
6625
Glenn Kasten735f45f2014-08-18 15:51:59 -07006626 // now run the fast track destructor with thread mutex unlocked
6627 fastTrackToRemove.clear();
6628
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006629 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6630 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6631 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6632 // If destination is non-contiguous, first read past the nominal end of buffer, then
6633 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006634
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006635 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006636 ssize_t framesRead;
6637
6638 // If an NBAIO source is present, use it to read the normal capture's data
6639 if (mPipeSource != 0) {
6640 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006641 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006642
6643 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6644 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6645 // we immediately retry the read() to get data and prevent another overflow.
6646 for (int retries = 0; retries <= 2; ++retries) {
6647 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6648 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6649 framesToRead);
6650 if (framesRead != OVERRUN) break;
6651 }
6652
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006653 const ssize_t availableToRead = mPipeSource->availableToRead();
6654 if (availableToRead >= 0) {
6655 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6656 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6657 "more frames to read than fifo size, %zd > %zu",
6658 availableToRead, mPipeFramesP2);
6659 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6660 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6661 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6662 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006663 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6664 }
6665 if (framesRead < 0) {
6666 status_t status = (status_t) framesRead;
6667 switch (status) {
6668 case OVERRUN:
6669 ALOGW("overrun on read from pipe");
6670 framesRead = 0;
6671 break;
6672 case NEGOTIATE:
6673 ALOGE("re-negotiation is needed");
6674 framesRead = -1; // Will cause an attempt to recover.
6675 break;
6676 default:
6677 ALOGE("unknown error %d on read from pipe", status);
6678 break;
6679 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006680 }
6681 // otherwise use the HAL / AudioStreamIn directly
6682 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006683 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006684 size_t bytesRead;
6685 status_t result = mInput->stream->read(
6686 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006687 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006688 if (result < 0) {
6689 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006690 } else {
6691 framesRead = bytesRead / mFrameSize;
6692 }
6693 }
6694
Andy Hung3f0c9022016-01-15 17:49:46 -08006695 // Update server timestamp with server stats
6696 // systemTime() is optional if the hardware supports timestamps.
6697 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6698 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6699
6700 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006701 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006702 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006703 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006704 if (ret == NO_ERROR) {
6705 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6706 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6707 // Note: In general record buffers should tend to be empty in
6708 // a properly running pipeline.
6709 //
6710 // Also, it is not advantageous to call get_presentation_position during the read
6711 // as the read obtains a lock, preventing the timestamp call from executing.
6712 }
6713 }
6714 // Use this to track timestamp information
6715 // ALOGD("%s", mTimestamp.toString().c_str());
6716
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006717 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006718 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006719 // Force input into standby so that it tries to recover at next read attempt
6720 inputStandBy();
6721 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006722 }
6723 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006724 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006725 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006726 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006727
Andy Hung8946a282018-04-19 20:04:56 -07006728#ifdef TEE_SINK
6729 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6730#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006731 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006732 {
6733 size_t part1 = mRsmpInFramesP2 - rear;
6734 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006735 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006736 (framesRead - part1) * mFrameSize);
6737 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006738 }
6739 rear = mRsmpInRear += framesRead;
6740
6741 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006742
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006743 // loop over each active track
6744 for (size_t i = 0; i < size; i++) {
6745 activeTrack = activeTracks[i];
6746
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006747 // skip fast tracks, as those are handled directly by FastCapture
6748 if (activeTrack->isFastTrack()) {
6749 continue;
6750 }
6751
Andy Hung73c02e42015-03-29 01:13:58 -07006752 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006753 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6754
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006755 enum {
6756 OVERRUN_UNKNOWN,
6757 OVERRUN_TRUE,
6758 OVERRUN_FALSE
6759 } overrun = OVERRUN_UNKNOWN;
6760
6761 // loop over getNextBuffer to handle circular sink
6762 for (;;) {
6763
6764 activeTrack->mSink.frameCount = ~0;
6765 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6766 size_t framesOut = activeTrack->mSink.frameCount;
6767 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6768
Andy Hung73c02e42015-03-29 01:13:58 -07006769 // check available frames and handle overrun conditions
6770 // if the record track isn't draining fast enough.
6771 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006772 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006773 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6774 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006775 overrun = OVERRUN_TRUE;
6776 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006777 if (framesOut == 0 || framesIn == 0) {
6778 break;
6779 }
6780
Andy Hung6770c6f2015-04-07 13:43:36 -07006781 // Don't allow framesOut to be larger than what is possible with resampling
6782 // from framesIn.
6783 // This isn't strictly necessary but helps limit buffer resizing in
6784 // RecordBufferConverter. TODO: remove when no longer needed.
6785 framesOut = min(framesOut,
6786 destinationFramesPossible(
6787 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006788 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6789 framesOut = activeTrack->mRecordBufferConverter->convert(
6790 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006791
6792 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6793 overrun = OVERRUN_FALSE;
6794 }
6795
6796 if (activeTrack->mFramesToDrop == 0) {
6797 if (framesOut > 0) {
6798 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006799 // Sanitize before releasing if the track has no access to the source data
6800 // An idle UID receives silence from non virtual devices until active
6801 if (activeTrack->isSilenced()) {
6802 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6803 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006804 activeTrack->releaseBuffer(&activeTrack->mSink);
6805 }
6806 } else {
6807 // FIXME could do a partial drop of framesOut
6808 if (activeTrack->mFramesToDrop > 0) {
6809 activeTrack->mFramesToDrop -= framesOut;
6810 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006811 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006812 }
6813 } else {
6814 activeTrack->mFramesToDrop += framesOut;
6815 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6816 activeTrack->mSyncStartEvent->isCancelled()) {
6817 ALOGW("Synced record %s, session %d, trigger session %d",
6818 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6819 activeTrack->sessionId(),
6820 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006821 activeTrack->mSyncStartEvent->triggerSession() :
6822 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006823 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006824 }
6825 }
6826 }
6827
6828 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006829 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006830 }
6831 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006832
6833 switch (overrun) {
6834 case OVERRUN_TRUE:
6835 // client isn't retrieving buffers fast enough
6836 if (!activeTrack->setOverflow()) {
6837 nsecs_t now = systemTime();
6838 // FIXME should lastWarning per track?
6839 if ((now - lastWarning) > kWarningThrottleNs) {
6840 ALOGW("RecordThread: buffer overflow");
6841 lastWarning = now;
6842 }
6843 }
6844 break;
6845 case OVERRUN_FALSE:
6846 activeTrack->clearOverflow();
6847 break;
6848 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006849 break;
6850 }
6851
Andy Hung3f0c9022016-01-15 17:49:46 -08006852 // update frame information and push timestamp out
6853 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006854 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006855 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6856 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006857 }
6858
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006859unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006860 // enable changes in effect chain
6861 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006862 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006863 }
6864
Glenn Kasten93e471f2013-08-19 08:40:07 -07006865 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006866
6867 {
6868 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006869 for (size_t i = 0; i < mTracks.size(); i++) {
6870 sp<RecordTrack> track = mTracks[i];
6871 track->invalidate();
6872 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006873 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006874 mStartStopCond.broadcast();
6875 }
6876
6877 releaseWakeLock();
6878
6879 ALOGV("RecordThread %p exiting", this);
6880 return false;
6881}
6882
Glenn Kasten93e471f2013-08-19 08:40:07 -07006883void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006884{
6885 if (!mStandby) {
6886 inputStandBy();
6887 mStandby = true;
6888 }
6889}
6890
6891void AudioFlinger::RecordThread::inputStandBy()
6892{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006893 // Idle the fast capture if it's currently running
6894 if (mFastCapture != 0) {
6895 FastCaptureStateQueue *sq = mFastCapture->sq();
6896 FastCaptureState *state = sq->begin();
6897 if (!(state->mCommand & FastCaptureState::IDLE)) {
6898 state->mCommand = FastCaptureState::COLD_IDLE;
6899 state->mColdFutexAddr = &mFastCaptureFutex;
6900 state->mColdGen++;
6901 mFastCaptureFutex = 0;
6902 sq->end();
6903 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6904 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6905#if 0
6906 if (kUseFastCapture == FastCapture_Dynamic) {
6907 // FIXME
6908 }
6909#endif
6910#ifdef AUDIO_WATCHDOG
6911 // FIXME
6912#endif
6913 } else {
6914 sq->end(false /*didModify*/);
6915 }
6916 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006917 status_t result = mInput->stream->standby();
6918 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006919
6920 // If going into standby, flush the pipe source.
6921 if (mPipeSource.get() != nullptr) {
6922 const ssize_t flushed = mPipeSource->flush();
6923 if (flushed > 0) {
6924 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6925 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6926 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6927 }
6928 }
Eric Laurent81784c32012-11-19 14:55:58 -08006929}
6930
Glenn Kasten05997e22014-03-13 15:08:33 -07006931// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006932sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006933 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006934 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006935 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006936 audio_format_t format,
6937 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006938 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006939 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006940 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006941 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006942 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006943 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006944 status_t *status,
6945 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006946{
Glenn Kasten74935e42013-12-19 08:56:45 -08006947 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006948 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006949 sp<RecordTrack> track;
6950 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006951 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006952 audio_input_flags_t requestedFlags = *flags;
6953 uint32_t sampleRate;
6954
6955 lStatus = initCheck();
6956 if (lStatus != NO_ERROR) {
6957 ALOGE("createRecordTrack_l() audio driver not initialized");
6958 goto Exit;
6959 }
6960
6961 if (*pSampleRate == 0) {
6962 *pSampleRate = mSampleRate;
6963 }
6964 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006965
6966 // special case for FAST flag considered OK if fast capture is present
6967 if (hasFastCapture()) {
6968 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6969 }
6970
Eric Laurentf14db3c2017-12-08 14:20:36 -08006971 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006972 if ((*flags & inputFlags) != *flags) {
6973 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6974 " input flags (%08x)",
6975 *flags, inputFlags);
6976 *flags = (audio_input_flags_t)(*flags & inputFlags);
6977 }
Eric Laurent81784c32012-11-19 14:55:58 -08006978
Glenn Kasten90e58b12013-07-31 16:16:02 -07006979 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006980 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006981 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006982 // we formerly checked for a callback handler (non-0 tid),
6983 // but that is no longer required for TRANSFER_OBTAIN mode
6984 //
Glenn Kasten74105912014-07-03 12:28:53 -07006985 // frame count is not specified, or is exactly the pipe depth
6986 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006987 // PCM data
6988 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006989 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006990 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006991 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006992 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006993 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006994 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006995 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006996 hasFastCapture() &&
6997 // there are sufficient fast track slots available
6998 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006999 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007000 // check compatibility with audio effects.
7001 Mutex::Autolock _l(mLock);
7002 // Do not accept FAST flag if the session has software effects
7003 sp<EffectChain> chain = getEffectChain_l(sessionId);
7004 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007005 audio_input_flags_t old = *flags;
7006 chain->checkInputFlagCompatibility(flags);
7007 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007008 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7009 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007010 }
7011 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007012 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007013 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7014 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007015 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007016 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7017 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007018 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007019 this, frameCount, mFrameCount, mPipeFramesP2,
7020 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007021 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007022 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007023 }
7024 }
7025
Eric Laurentf14db3c2017-12-08 14:20:36 -08007026 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7027 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7028 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7029 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7030 lStatus = BAD_TYPE;
7031 goto Exit;
7032 }
7033
Glenn Kasten74105912014-07-03 12:28:53 -07007034 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007035 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007036 // fast track: frame count is exactly the pipe depth
7037 frameCount = mPipeFramesP2;
7038 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007039 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007040 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007041 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7042 // or 20 ms if there is a fast capture
7043 // TODO This could be a roundupRatio inline, and const
7044 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7045 * sampleRate + mSampleRate - 1) / mSampleRate;
7046 // minimum number of notification periods is at least kMinNotifications,
7047 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7048 static const size_t kMinNotifications = 3;
7049 static const uint32_t kMinMs = 30;
7050 // TODO This could be a roundupRatio inline
7051 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7052 // TODO This could be a roundupRatio inline
7053 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7054 maxNotificationFrames;
7055 const size_t minFrameCount = maxNotificationFrames *
7056 max(kMinNotifications, minNotificationsByMs);
7057 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007058 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7059 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007060 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007061 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007062 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007063 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007064
7065 { // scope for mLock
7066 Mutex::Autolock _l(mLock);
7067
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007068 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007069 format, channelMask, frameCount,
7070 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007071 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007072
Glenn Kasten03003332013-08-06 15:40:54 -07007073 lStatus = track->initCheck();
7074 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007075 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007076 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007077 goto Exit;
7078 }
7079 mTracks.add(track);
7080
Eric Laurent05067782016-06-01 18:27:28 -07007081 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007082 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7083 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7084 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007085 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007086 }
Eric Laurent81784c32012-11-19 14:55:58 -08007087 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007088
Eric Laurent81784c32012-11-19 14:55:58 -08007089 lStatus = NO_ERROR;
7090
7091Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007092 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007093 return track;
7094}
7095
7096status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7097 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007098 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007099{
7100 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7101 sp<ThreadBase> strongMe = this;
7102 status_t status = NO_ERROR;
7103
7104 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007105 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007106 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007107 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007108 triggerSession,
7109 recordTrack->sessionId(),
7110 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007111 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007112 // Sync event can be cancelled by the trigger session if the track is not in a
7113 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007114 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007115 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007116 } else {
7117 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007118 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007119 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007120 }
7121 }
7122
7123 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007124 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007125 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007126 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7127 if (recordTrack->mState == TrackBase::PAUSING) {
7128 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007129 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007130 } else {
7131 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007132 }
7133 return status;
7134 }
7135
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007136 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7137 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7138 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007139 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007140 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007141 status_t status = NO_ERROR;
7142 if (recordTrack->isExternalTrack()) {
7143 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007144 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007145 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007146 mLock.lock();
7147 // FIXME should verify that recordTrack is still in mActiveTracks
7148 if (status != NO_ERROR) {
7149 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007150 recordTrack->clearSyncStartEvent();
7151 ALOGV("RecordThread::start error %d", status);
7152 return status;
7153 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007154 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007155 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007156 // Catch up with current buffer indices if thread is already running.
7157 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7158 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7159 // see previously buffered data before it called start(), but with greater risk of overrun.
7160
Andy Hung73c02e42015-03-29 01:13:58 -07007161 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07007162 // clear any converter state as new data will be discontinuous
7163 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007164 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007165 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007166 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007167 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007168 ALOGV("Record failed to start");
7169 status = BAD_VALUE;
7170 goto startError;
7171 }
Eric Laurent81784c32012-11-19 14:55:58 -08007172 return status;
7173 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007174
Eric Laurent81784c32012-11-19 14:55:58 -08007175startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007176 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007177 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007178 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007179 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007180 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007181 return status;
7182}
7183
Eric Laurent81784c32012-11-19 14:55:58 -08007184void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7185{
7186 sp<SyncEvent> strongEvent = event.promote();
7187
7188 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007189 sp<RefBase> ptr = strongEvent->cookie().promote();
7190 if (ptr != 0) {
7191 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7192 recordTrack->handleSyncStartEvent(strongEvent);
7193 }
Eric Laurent81784c32012-11-19 14:55:58 -08007194 }
7195}
7196
Glenn Kastena8356f62013-07-25 14:37:52 -07007197bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007198 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007199 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007200 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007201 return false;
7202 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007203 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007204 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007205 // signal thread to stop
7206 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007207 // do not wait for mStartStopCond if exiting
7208 if (exitPending()) {
7209 return true;
7210 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007211 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007212 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007213 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007214 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007215 ALOGV("Record stopped OK");
7216 return true;
7217 }
7218 return false;
7219}
7220
Glenn Kasten0f11b512014-01-31 16:18:54 -08007221bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007222{
7223 return false;
7224}
7225
Glenn Kasten0f11b512014-01-31 16:18:54 -08007226status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007227{
7228#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7229 if (!isValidSyncEvent(event)) {
7230 return BAD_VALUE;
7231 }
7232
Glenn Kastend848eb42016-03-08 13:42:11 -08007233 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007234 status_t ret = NAME_NOT_FOUND;
7235
7236 Mutex::Autolock _l(mLock);
7237
7238 for (size_t i = 0; i < mTracks.size(); i++) {
7239 sp<RecordTrack> track = mTracks[i];
7240 if (eventSession == track->sessionId()) {
7241 (void) track->setSyncEvent(event);
7242 ret = NO_ERROR;
7243 }
7244 }
7245 return ret;
7246#else
7247 return BAD_VALUE;
7248#endif
7249}
7250
jiabin653cc0a2018-01-17 17:54:10 -08007251status_t AudioFlinger::RecordThread::getActiveMicrophones(
7252 std::vector<media::MicrophoneInfo>* activeMicrophones)
7253{
7254 ALOGV("RecordThread::getActiveMicrophones");
7255 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007256 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7257 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007258}
7259
Kevin Rocard069c2712018-03-29 19:09:14 -07007260void AudioFlinger::RecordThread::updateMetadata_l()
7261{
7262 if (mInput == nullptr || mInput->stream == nullptr ||
7263 !mActiveTracks.readAndClearHasChanged()) {
7264 return;
7265 }
7266 StreamInHalInterface::SinkMetadata metadata;
7267 for (const sp<RecordTrack> &track : mActiveTracks) {
7268 // No track is invalid as this is called after prepareTrack_l in the same critical section
7269 metadata.tracks.push_back({
7270 .source = track->attributes().source,
7271 .gain = 1, // capture tracks do not have volumes
7272 });
7273 }
7274 mInput->stream->updateSinkMetadata(metadata);
7275}
7276
Eric Laurent81784c32012-11-19 14:55:58 -08007277// destroyTrack_l() must be called with ThreadBase::mLock held
7278void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7279{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007280 track->terminate();
7281 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007282 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007283 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007284 removeTrack_l(track);
7285 }
7286}
7287
7288void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7289{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007290 String8 result;
7291 track->appendDump(result, false /* active */);
7292 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7293
Eric Laurent81784c32012-11-19 14:55:58 -08007294 mTracks.remove(track);
7295 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007296 if (track->isFastTrack()) {
7297 ALOG_ASSERT(!mFastTrackAvail);
7298 mFastTrackAvail = true;
7299 }
Eric Laurent81784c32012-11-19 14:55:58 -08007300}
7301
7302void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7303{
7304 dumpInternals(fd, args);
7305 dumpTracks(fd, args);
7306 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007307 dprintf(fd, " Local log:\n");
7308 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007309}
7310
7311void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7312{
Glenn Kasten44182c22015-03-05 17:12:23 -08007313 dumpBase(fd, args);
7314
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007315 AudioStreamIn *input = mInput;
7316 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7317 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7318 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007319 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007320 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007321 }
Andy Hungbfa64962017-06-12 14:43:19 -07007322
7323 if (input != nullptr) {
7324 dprintf(fd, " Hal stream dump:\n");
7325 (void)input->stream->dump(fd);
7326 }
7327
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007328 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007329 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007330
Glenn Kasten2f90c512015-12-02 11:40:09 -08007331 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7332 // while we are dumping it. It may be inconsistent, but it won't mutate!
7333 // This is a large object so we place it on the heap.
7334 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7335 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7336 copy->dump(fd);
7337 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007338}
7339
Glenn Kasten0f11b512014-01-31 16:18:54 -08007340void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007341{
Eric Laurent81784c32012-11-19 14:55:58 -08007342 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007343 size_t numtracks = mTracks.size();
7344 size_t numactive = mActiveTracks.size();
7345 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007346 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007347 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007348 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007349 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007350 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007351 RecordTrack::appendDumpHeader(result);
7352 for (size_t i = 0; i < numtracks ; ++i) {
7353 sp<RecordTrack> track = mTracks[i];
7354 if (track != 0) {
7355 bool active = mActiveTracks.indexOf(track) >= 0;
7356 if (active) {
7357 numactiveseen++;
7358 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007359 result.append(prefix);
7360 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007361 }
Eric Laurent81784c32012-11-19 14:55:58 -08007362 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007363 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007364 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007365 }
7366
Marco Nelissenb2208842014-02-07 14:00:50 -08007367 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007368 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007369 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007370 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007371 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007372 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007373 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007374 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007375 result.append(prefix);
7376 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007377 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007378 }
Eric Laurent81784c32012-11-19 14:55:58 -08007379
7380 }
7381 write(fd, result.string(), result.size());
7382}
7383
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007384void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7385{
7386 Mutex::Autolock _l(mLock);
7387 for (size_t i = 0; i < mTracks.size() ; i++) {
7388 sp<RecordTrack> track = mTracks[i];
7389 if (track != 0 && track->uid() == uid) {
7390 track->setSilenced(silenced);
7391 }
7392 }
7393}
Andy Hung73c02e42015-03-29 01:13:58 -07007394
7395void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7396{
7397 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7398 RecordThread *recordThread = (RecordThread *) threadBase.get();
7399 mRsmpInFront = recordThread->mRsmpInRear;
7400 mRsmpInUnrel = 0;
7401}
7402
7403void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7404 size_t *framesAvailable, bool *hasOverrun)
7405{
7406 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7407 RecordThread *recordThread = (RecordThread *) threadBase.get();
7408 const int32_t rear = recordThread->mRsmpInRear;
7409 const int32_t front = mRsmpInFront;
7410 const ssize_t filled = rear - front;
7411
7412 size_t framesIn;
7413 bool overrun = false;
7414 if (filled < 0) {
7415 // should not happen, but treat like a massive overrun and re-sync
7416 framesIn = 0;
7417 mRsmpInFront = rear;
7418 overrun = true;
7419 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7420 framesIn = (size_t) filled;
7421 } else {
7422 // client is not keeping up with server, but give it latest data
7423 framesIn = recordThread->mRsmpInFrames;
7424 mRsmpInFront = /* front = */ rear - framesIn;
7425 overrun = true;
7426 }
7427 if (framesAvailable != NULL) {
7428 *framesAvailable = framesIn;
7429 }
7430 if (hasOverrun != NULL) {
7431 *hasOverrun = overrun;
7432 }
7433}
7434
Eric Laurent81784c32012-11-19 14:55:58 -08007435// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007436status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007437 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007438{
Andy Hung73c02e42015-03-29 01:13:58 -07007439 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007440 if (threadBase == 0) {
7441 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007442 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007443 return NOT_ENOUGH_DATA;
7444 }
7445 RecordThread *recordThread = (RecordThread *) threadBase.get();
7446 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007447 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007448 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007449 // FIXME should not be P2 (don't want to increase latency)
7450 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007451 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007452 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007453 front &= recordThread->mRsmpInFramesP2 - 1;
7454 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007455 if (part1 > (size_t) filled) {
7456 part1 = filled;
7457 }
7458 size_t ask = buffer->frameCount;
7459 ALOG_ASSERT(ask > 0);
7460 if (part1 > ask) {
7461 part1 = ask;
7462 }
7463 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007464 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007465 buffer->raw = NULL;
7466 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007467 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007468 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007469 }
7470
Andy Hung57446612015-04-19 23:56:46 -07007471 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007472 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007473 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007474 return NO_ERROR;
7475}
7476
7477// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007478void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7479 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007480{
Glenn Kasten85948432013-08-19 12:09:05 -07007481 size_t stepCount = buffer->frameCount;
7482 if (stepCount == 0) {
7483 return;
7484 }
Andy Hung73c02e42015-03-29 01:13:58 -07007485 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7486 mRsmpInUnrel -= stepCount;
7487 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007488 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007489 buffer->frameCount = 0;
7490}
7491
Eric Laurentd8365c52017-07-16 15:27:05 -07007492void AudioFlinger::RecordThread::checkBtNrec()
7493{
7494 Mutex::Autolock _l(mLock);
7495 checkBtNrec_l();
7496}
7497
7498void AudioFlinger::RecordThread::checkBtNrec_l()
7499{
7500 // disable AEC and NS if the device is a BT SCO headset supporting those
7501 // pre processings
7502 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7503 mAudioFlinger->btNrecIsOff();
7504 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7505 for (size_t i = 0; i < mEffectChains.size(); i++) {
7506 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7507 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7508 }
7509 }
7510}
7511
Andy Hung97a893e2015-03-29 01:03:07 -07007512
Eric Laurent10351942014-05-08 18:49:52 -07007513bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7514 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007515{
7516 bool reconfig = false;
7517
Eric Laurent10351942014-05-08 18:49:52 -07007518 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007519
Eric Laurent10351942014-05-08 18:49:52 -07007520 audio_format_t reqFormat = mFormat;
7521 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007522 // 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 -07007523 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7524
7525 AudioParameter param = AudioParameter(keyValuePair);
7526 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007527
7528 // scope for AutoPark extends to end of method
7529 AutoPark<FastCapture> park(mFastCapture);
7530
Eric Laurent10351942014-05-08 18:49:52 -07007531 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7532 // channel count change can be requested. Do we mandate the first client defines the
7533 // HAL sampling rate and channel count or do we allow changes on the fly?
7534 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7535 samplingRate = value;
7536 reconfig = true;
7537 }
7538 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007539 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007540 status = BAD_VALUE;
7541 } else {
7542 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007543 reconfig = true;
7544 }
Eric Laurent10351942014-05-08 18:49:52 -07007545 }
7546 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7547 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007548 if (!audio_is_input_channel(mask) ||
7549 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007550 status = BAD_VALUE;
7551 } else {
7552 channelMask = mask;
7553 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007554 }
Eric Laurent10351942014-05-08 18:49:52 -07007555 }
7556 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7557 // do not accept frame count changes if tracks are open as the track buffer
7558 // size depends on frame count and correct behavior would not be guaranteed
7559 // if frame count is changed after track creation
7560 if (mActiveTracks.size() > 0) {
7561 status = INVALID_OPERATION;
7562 } else {
7563 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007564 }
Eric Laurent10351942014-05-08 18:49:52 -07007565 }
7566 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7567 // forward device change to effects that have requested to be
7568 // aware of attached audio device.
7569 for (size_t i = 0; i < mEffectChains.size(); i++) {
7570 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007571 }
Eric Laurent81784c32012-11-19 14:55:58 -08007572
Eric Laurent10351942014-05-08 18:49:52 -07007573 // store input device and output device but do not forward output device to audio HAL.
7574 // Note that status is ignored by the caller for output device
7575 // (see AudioFlinger::setParameters()
7576 if (audio_is_output_devices(value)) {
7577 mOutDevice = value;
7578 status = BAD_VALUE;
7579 } else {
7580 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007581 if (value != AUDIO_DEVICE_NONE) {
7582 mPrevInDevice = value;
7583 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007584 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007585 }
Eric Laurent10351942014-05-08 18:49:52 -07007586 }
7587 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7588 mAudioSource != (audio_source_t)value) {
7589 // forward device change to effects that have requested to be
7590 // aware of attached audio device.
7591 for (size_t i = 0; i < mEffectChains.size(); i++) {
7592 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007593 }
Eric Laurent10351942014-05-08 18:49:52 -07007594 mAudioSource = (audio_source_t)value;
7595 }
Glenn Kastene198c362013-08-13 09:13:36 -07007596
Eric Laurent10351942014-05-08 18:49:52 -07007597 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007598 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007599 if (status == INVALID_OPERATION) {
7600 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007601 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007602 }
7603 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007604 if (status == BAD_VALUE) {
7605 uint32_t sRate;
7606 audio_channel_mask_t channelMask;
7607 audio_format_t format;
7608 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7609 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7610 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7611 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7612 status = NO_ERROR;
7613 }
Eric Laurent81784c32012-11-19 14:55:58 -08007614 }
Eric Laurent10351942014-05-08 18:49:52 -07007615 if (status == NO_ERROR) {
7616 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007617 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007618 }
7619 }
Eric Laurent81784c32012-11-19 14:55:58 -08007620 }
Eric Laurent10351942014-05-08 18:49:52 -07007621
Eric Laurent81784c32012-11-19 14:55:58 -08007622 return reconfig;
7623}
7624
7625String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7626{
Eric Laurent81784c32012-11-19 14:55:58 -08007627 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007628 if (initCheck() == NO_ERROR) {
7629 String8 out_s8;
7630 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7631 return out_s8;
7632 }
Eric Laurent81784c32012-11-19 14:55:58 -08007633 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007634 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007635}
7636
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007637void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007638 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7639
7640 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007641
7642 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007643 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007644 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007645 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007646 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007647 desc->mChannelMask = mChannelMask;
7648 desc->mSamplingRate = mSampleRate;
7649 desc->mFormat = mFormat;
7650 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007651 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007652 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007653 break;
7654
Eric Laurent73e26b62015-04-27 16:55:58 -07007655 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007656 default:
7657 break;
7658 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007659 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007660}
7661
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007662void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007663{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007664 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7665 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007666 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007667 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007668 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007669 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7670 result = mInput->stream->getFrameSize(&mFrameSize);
7671 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7672 result = mInput->stream->getBufferSize(&mBufferSize);
7673 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007674 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007675 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7676 "mBufferSize=%lld, mFrameCount=%lld",
7677 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7678 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007679 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007680 // 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 -07007681 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007682 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007683 // A larger value should allow more old data to be read after a track calls start(),
7684 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007685 //
7686 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007687 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007688 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007689 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007690 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007691
7692 // TODO optimize audio capture buffer sizes ...
7693 // Here we calculate the size of the sliding buffer used as a source
7694 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7695 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7696 // be better to have it derived from the pipe depth in the long term.
7697 // The current value is higher than necessary. However it should not add to latency.
7698
Glenn Kasten85948432013-08-19 12:09:05 -07007699 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007700 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7701 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007702 // if posix_memalign fails, will segv here.
7703 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007704
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007705 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7706 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007707}
7708
Glenn Kasten5f972c02014-01-13 09:59:31 -08007709uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007710{
7711 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007712 uint32_t result;
7713 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7714 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007715 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007716 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007717}
7718
Eric Laurent4c415062016-06-17 16:14:16 -07007719// hasAudioSession_l() must be called with ThreadBase::mLock held
7720uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007721{
Eric Laurent81784c32012-11-19 14:55:58 -08007722 uint32_t result = 0;
7723 if (getEffectChain_l(sessionId) != 0) {
7724 result = EFFECT_SESSION;
7725 }
7726
7727 for (size_t i = 0; i < mTracks.size(); ++i) {
7728 if (sessionId == mTracks[i]->sessionId()) {
7729 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007730 if (mTracks[i]->isFastTrack()) {
7731 result |= FAST_SESSION;
7732 }
Eric Laurent81784c32012-11-19 14:55:58 -08007733 break;
7734 }
7735 }
7736
7737 return result;
7738}
7739
Glenn Kastend848eb42016-03-08 13:42:11 -08007740KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007741{
Glenn Kastend848eb42016-03-08 13:42:11 -08007742 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007743 Mutex::Autolock _l(mLock);
7744 for (size_t j = 0; j < mTracks.size(); ++j) {
7745 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007746 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007747 if (ids.indexOfKey(sessionId) < 0) {
7748 ids.add(sessionId, true);
7749 }
7750 }
7751 return ids;
7752}
7753
7754AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7755{
7756 Mutex::Autolock _l(mLock);
7757 AudioStreamIn *input = mInput;
7758 mInput = NULL;
7759 return input;
7760}
7761
7762// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007763sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007764{
7765 if (mInput == NULL) {
7766 return NULL;
7767 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007768 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007769}
7770
7771status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7772{
7773 // only one chain per input thread
7774 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007775 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007776 return INVALID_OPERATION;
7777 }
7778 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007779 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007780 chain->setInBuffer(NULL);
7781 chain->setOutBuffer(NULL);
7782
7783 checkSuspendOnAddEffectChain_l(chain);
7784
Eric Laurent1b928682014-10-02 19:41:47 -07007785 // make sure enabled pre processing effects state is communicated to the HAL as we
7786 // just moved them to a new input stream.
7787 chain->syncHalEffectsState();
7788
Eric Laurent81784c32012-11-19 14:55:58 -08007789 mEffectChains.add(chain);
7790
7791 return NO_ERROR;
7792}
7793
7794size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7795{
7796 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7797 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007798 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007799 chain.get(), mEffectChains.size(), this);
7800 if (mEffectChains.size() == 1) {
7801 mEffectChains.removeAt(0);
7802 }
7803 return 0;
7804}
7805
Eric Laurent1c333e22014-05-20 10:48:17 -07007806status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7807 audio_patch_handle_t *handle)
7808{
7809 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007810
7811 // store new device and send to effects
7812 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007813 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007814 for (size_t i = 0; i < mEffectChains.size(); i++) {
7815 mEffectChains[i]->setDevice_l(mInDevice);
7816 }
7817
Eric Laurentd8365c52017-07-16 15:27:05 -07007818 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007819
7820 // store new source and send to effects
7821 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7822 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007823 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007824 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007825 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007826 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007827
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007828 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007829 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7830 status = hwDevice->createAudioPatch(patch->num_sources,
7831 patch->sources,
7832 patch->num_sinks,
7833 patch->sinks,
7834 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007835 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007836 char *address;
7837 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7838 address = audio_device_address_to_parameter(
7839 patch->sources[0].ext.device.type,
7840 patch->sources[0].ext.device.address);
7841 } else {
7842 address = (char *)calloc(1, 1);
7843 }
7844 AudioParameter param = AudioParameter(String8(address));
7845 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007846 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007847 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007848 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007849 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007850 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007851 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007852 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007853
Eric Laurente8726fe2015-06-26 09:39:24 -07007854 if (mInDevice != mPrevInDevice) {
7855 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7856 mPrevInDevice = mInDevice;
7857 }
Eric Laurent296fb132015-05-01 11:38:42 -07007858
Eric Laurent1c333e22014-05-20 10:48:17 -07007859 return status;
7860}
7861
7862status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7863{
7864 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007865
7866 mInDevice = AUDIO_DEVICE_NONE;
7867
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007868 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007869 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7870 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007871 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007872 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007873 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007874 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007875 }
7876 return status;
7877}
7878
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007879void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007880{
7881 Mutex::Autolock _l(mLock);
7882 mTracks.add(record);
7883}
7884
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007885void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007886{
7887 Mutex::Autolock _l(mLock);
7888 destroyTrack_l(record);
7889}
7890
Mikhail Naganovdc769682018-05-04 15:34:08 -07007891void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07007892{
Mikhail Naganovdc769682018-05-04 15:34:08 -07007893 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07007894 config->role = AUDIO_PORT_ROLE_SINK;
7895 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7896 config->ext.mix.usecase.source = mAudioSource;
7897}
Eric Laurent1c333e22014-05-20 10:48:17 -07007898
Eric Laurent6acd1d42017-01-04 14:23:29 -08007899// ----------------------------------------------------------------------------
7900// Mmap
7901// ----------------------------------------------------------------------------
7902
7903AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7904 : mThread(thread)
7905{
Phil Burk9fabbf82017-08-03 12:02:00 -07007906 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007907}
7908
7909AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7910{
Phil Burk9fabbf82017-08-03 12:02:00 -07007911 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007912}
7913
7914status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7915 struct audio_mmap_buffer_info *info)
7916{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007917 return mThread->createMmapBuffer(minSizeFrames, info);
7918}
7919
7920status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7921{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007922 return mThread->getMmapPosition(position);
7923}
7924
Eric Laurenta54f1282017-07-01 19:39:32 -07007925status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007926 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007927
7928{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007929 return mThread->start(client, handle);
7930}
7931
7932status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7933{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007934 return mThread->stop(handle);
7935}
7936
Eric Laurent18b57012017-02-13 16:23:52 -08007937status_t AudioFlinger::MmapThreadHandle::standby()
7938{
Eric Laurent18b57012017-02-13 16:23:52 -08007939 return mThread->standby();
7940}
7941
Eric Laurent6acd1d42017-01-04 14:23:29 -08007942
7943AudioFlinger::MmapThread::MmapThread(
7944 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7945 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7946 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7947 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007948 mSessionId(AUDIO_SESSION_NONE),
7949 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007950 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07007951 mActiveTracks(&this->mLocalLog),
7952 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
7953 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007954{
Eric Laurent18b57012017-02-13 16:23:52 -08007955 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007956 readHalParameters_l();
7957}
7958
7959AudioFlinger::MmapThread::~MmapThread()
7960{
Eric Laurent18b57012017-02-13 16:23:52 -08007961 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007962}
7963
7964void AudioFlinger::MmapThread::onFirstRef()
7965{
7966 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7967}
7968
7969void AudioFlinger::MmapThread::disconnect()
7970{
Eric Laurent331679c2018-04-16 17:03:16 -07007971 ActiveTracks<MmapTrack> activeTracks;
7972 {
7973 Mutex::Autolock _l(mLock);
7974 for (const sp<MmapTrack> &t : mActiveTracks) {
7975 activeTracks.add(t);
7976 }
7977 }
7978 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007979 stop(t->portId());
7980 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007981 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007982 if (isOutput()) {
7983 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7984 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08007985 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007986 }
7987}
7988
7989
7990void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7991 audio_stream_type_t streamType __unused,
7992 audio_session_t sessionId,
7993 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007994 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007995 audio_port_handle_t portId)
7996{
7997 mAttr = *attr;
7998 mSessionId = sessionId;
7999 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008000 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008001 mPortId = portId;
8002}
8003
8004status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8005 struct audio_mmap_buffer_info *info)
8006{
8007 if (mHalStream == 0) {
8008 return NO_INIT;
8009 }
Eric Laurent18b57012017-02-13 16:23:52 -08008010 mStandby = true;
8011 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008012 return mHalStream->createMmapBuffer(minSizeFrames, info);
8013}
8014
8015status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8016{
8017 if (mHalStream == 0) {
8018 return NO_INIT;
8019 }
8020 return mHalStream->getMmapPosition(position);
8021}
8022
Eric Laurent331679c2018-04-16 17:03:16 -07008023status_t AudioFlinger::MmapThread::exitStandby()
8024{
8025 status_t ret = mHalStream->start();
8026 if (ret != NO_ERROR) {
8027 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8028 return ret;
8029 }
8030 mStandby = false;
8031 return NO_ERROR;
8032}
8033
Eric Laurenta54f1282017-07-01 19:39:32 -07008034status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008035 audio_port_handle_t *handle)
8036{
Eric Laurenta54f1282017-07-01 19:39:32 -07008037 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8038 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008039 if (mHalStream == 0) {
8040 return NO_INIT;
8041 }
8042
8043 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008044
Eric Laurenta54f1282017-07-01 19:39:32 -07008045 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008046 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008047 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008048 }
8049
8050 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8051
8052 audio_io_handle_t io = mId;
8053 if (isOutput()) {
8054 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8055 config.sample_rate = mSampleRate;
8056 config.channel_mask = mChannelMask;
8057 config.format = mFormat;
8058 audio_stream_type_t stream = streamType();
8059 audio_output_flags_t flags =
8060 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008061 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008062 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8063 mSessionId,
8064 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008065 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008066 client.clientUid,
8067 &config,
8068 flags,
8069 &deviceId,
8070 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008071 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008072 audio_config_base_t config;
8073 config.sample_rate = mSampleRate;
8074 config.channel_mask = mChannelMask;
8075 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008076 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008077 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8078 mSessionId,
8079 client.clientPid,
8080 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008081 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008082 &config,
8083 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8084 &deviceId,
8085 &portId);
8086 }
8087 // APM should not chose a different input or output stream for the same set of attributes
8088 // and audo configuration
8089 if (ret != NO_ERROR || io != mId) {
8090 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8091 __FUNCTION__, ret, io, mId);
8092 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008093 }
8094
Eric Laurent331679c2018-04-16 17:03:16 -07008095 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008096 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008097 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008098 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008099 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008100 }
8101
Eric Laurent331679c2018-04-16 17:03:16 -07008102 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008103 // abort if start is rejected by audio policy manager
8104 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008105 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008106 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008107 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008108 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008109 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008110 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008111 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008112 }
Eric Laurent331679c2018-04-16 17:03:16 -07008113 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008114 } else {
8115 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008116 }
8117 return PERMISSION_DENIED;
8118 }
8119
Eric Laurent67f97292018-04-20 18:05:41 -07008120 if (isOutput()) {
8121 // force volume update when a new track is added
8122 mHalVolFloat = -1.0f;
8123 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008124 for (const sp<MmapTrack> &track : mActiveTracks) {
8125 if (track->isSilenced_l() && track->uid() != client.clientUid)
8126 track->invalidate();
8127 }
8128 }
8129
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008130 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8131 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -07008132 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008133
Eric Laurent331679c2018-04-16 17:03:16 -07008134 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008135 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008136 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008137 if (chain != 0) {
8138 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8139 chain->incTrackCnt();
8140 chain->incActiveTrackCnt();
8141 }
8142
8143 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008144 broadcast_l();
8145
Eric Laurenta54f1282017-07-01 19:39:32 -07008146 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008147
8148 return NO_ERROR;
8149}
8150
8151status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8152{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008153 ALOGV("%s handle %d", __FUNCTION__, handle);
8154
8155 if (mHalStream == 0) {
8156 return NO_INIT;
8157 }
8158
Eric Laurenta54f1282017-07-01 19:39:32 -07008159 if (handle == mPortId) {
8160 mHalStream->stop();
8161 return NO_ERROR;
8162 }
8163
Eric Laurent331679c2018-04-16 17:03:16 -07008164 Mutex::Autolock _l(mLock);
8165
Eric Laurent6acd1d42017-01-04 14:23:29 -08008166 sp<MmapTrack> track;
8167 for (const sp<MmapTrack> &t : mActiveTracks) {
8168 if (handle == t->portId()) {
8169 track = t;
8170 break;
8171 }
8172 }
8173 if (track == 0) {
8174 return BAD_VALUE;
8175 }
8176
8177 mActiveTracks.remove(track);
8178
Eric Laurent331679c2018-04-16 17:03:16 -07008179 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008180 if (isOutput()) {
8181 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008182 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008183 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008184 AudioSystem::stopInput(track->portId());
8185 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008186 }
Eric Laurent331679c2018-04-16 17:03:16 -07008187 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008188
8189 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8190 if (chain != 0) {
8191 chain->decActiveTrackCnt();
8192 chain->decTrackCnt();
8193 }
8194
8195 broadcast_l();
8196
Eric Laurent6acd1d42017-01-04 14:23:29 -08008197 return NO_ERROR;
8198}
8199
Eric Laurent18b57012017-02-13 16:23:52 -08008200status_t AudioFlinger::MmapThread::standby()
8201{
8202 ALOGV("%s", __FUNCTION__);
8203
8204 if (mHalStream == 0) {
8205 return NO_INIT;
8206 }
8207 if (mActiveTracks.size() != 0) {
8208 return INVALID_OPERATION;
8209 }
8210 mHalStream->standby();
8211 mStandby = true;
8212 releaseWakeLock();
8213 return NO_ERROR;
8214}
8215
Eric Laurent6acd1d42017-01-04 14:23:29 -08008216
8217void AudioFlinger::MmapThread::readHalParameters_l()
8218{
8219 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8220 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8221 mFormat = mHALFormat;
8222 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8223 result = mHalStream->getFrameSize(&mFrameSize);
8224 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8225 result = mHalStream->getBufferSize(&mBufferSize);
8226 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8227 mFrameCount = mBufferSize / mFrameSize;
8228}
8229
8230bool AudioFlinger::MmapThread::threadLoop()
8231{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008232 checkSilentMode_l();
8233
8234 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8235
8236 while (!exitPending())
8237 {
8238 Mutex::Autolock _l(mLock);
8239 Vector< sp<EffectChain> > effectChains;
8240
8241 if (mSignalPending) {
8242 // A signal was raised while we were unlocked
8243 mSignalPending = false;
8244 } else {
8245 if (mConfigEvents.isEmpty()) {
8246 // we're about to wait, flush the binder command buffer
8247 IPCThreadState::self()->flushCommands();
8248
8249 if (exitPending()) {
8250 break;
8251 }
8252
Eric Laurent6acd1d42017-01-04 14:23:29 -08008253 // wait until we have something to do...
8254 ALOGV("%s going to sleep", myName.string());
8255 mWaitWorkCV.wait(mLock);
8256 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008257
8258 checkSilentMode_l();
8259
8260 continue;
8261 }
8262 }
8263
8264 processConfigEvents_l();
8265
8266 processVolume_l();
8267
8268 checkInvalidTracks_l();
8269
8270 mActiveTracks.updatePowerState(this);
8271
Kevin Rocard069c2712018-03-29 19:09:14 -07008272 updateMetadata_l();
8273
Eric Laurent6acd1d42017-01-04 14:23:29 -08008274 lockEffectChains_l(effectChains);
8275 for (size_t i = 0; i < effectChains.size(); i ++) {
8276 effectChains[i]->process_l();
8277 }
8278 // enable changes in effect chain
8279 unlockEffectChains(effectChains);
8280 // Effect chains will be actually deleted here if they were removed from
8281 // mEffectChains list during mixing or effects processing
8282 }
8283
8284 threadLoop_exit();
8285
8286 if (!mStandby) {
8287 threadLoop_standby();
8288 mStandby = true;
8289 }
8290
Eric Laurent6acd1d42017-01-04 14:23:29 -08008291 ALOGV("Thread %p type %d exiting", this, mType);
8292 return false;
8293}
8294
8295// checkForNewParameter_l() must be called with ThreadBase::mLock held
8296bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8297 status_t& status)
8298{
8299 AudioParameter param = AudioParameter(keyValuePair);
8300 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008301 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008302 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008303 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008304 // forward device change to effects that have requested to be
8305 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008306 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008307 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008308 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008309 }
8310 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008311 if (audio_is_output_devices(device)) {
8312 mOutDevice = device;
8313 if (!isOutput()) {
8314 sendToHal = false;
8315 }
8316 } else {
8317 mInDevice = device;
8318 if (device != AUDIO_DEVICE_NONE) {
8319 mPrevInDevice = value;
8320 }
8321 // TODO: implement and call checkBtNrec_l();
8322 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008323 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008324 if (sendToHal) {
8325 status = mHalStream->setParameters(keyValuePair);
8326 } else {
8327 status = NO_ERROR;
8328 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008329
8330 return false;
8331}
8332
8333String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8334{
8335 Mutex::Autolock _l(mLock);
8336 String8 out_s8;
8337 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8338 return out_s8;
8339 }
8340 return String8();
8341}
8342
8343void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8344 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8345
8346 desc->mIoHandle = mId;
8347
8348 switch (event) {
8349 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008350 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008351 case AUDIO_INPUT_CONFIG_CHANGED:
8352 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008353 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008354 case AUDIO_OUTPUT_CONFIG_CHANGED:
8355 desc->mPatch = mPatch;
8356 desc->mChannelMask = mChannelMask;
8357 desc->mSamplingRate = mSampleRate;
8358 desc->mFormat = mFormat;
8359 desc->mFrameCount = mFrameCount;
8360 desc->mFrameCountHAL = mFrameCount;
8361 desc->mLatency = 0;
8362 break;
8363
8364 case AUDIO_INPUT_CLOSED:
8365 case AUDIO_OUTPUT_CLOSED:
8366 default:
8367 break;
8368 }
8369 mAudioFlinger->ioConfigChanged(event, desc, pid);
8370}
8371
8372status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8373 audio_patch_handle_t *handle)
8374{
8375 status_t status = NO_ERROR;
8376
8377 // store new device and send to effects
8378 audio_devices_t type = AUDIO_DEVICE_NONE;
8379 audio_port_handle_t deviceId;
8380 if (isOutput()) {
8381 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8382 type |= patch->sinks[i].ext.device.type;
8383 }
8384 deviceId = patch->sinks[0].id;
8385 } else {
8386 type = patch->sources[0].ext.device.type;
8387 deviceId = patch->sources[0].id;
8388 }
8389
8390 for (size_t i = 0; i < mEffectChains.size(); i++) {
8391 mEffectChains[i]->setDevice_l(type);
8392 }
8393
8394 if (isOutput()) {
8395 mOutDevice = type;
8396 } else {
8397 mInDevice = type;
8398 // store new source and send to effects
8399 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8400 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8401 for (size_t i = 0; i < mEffectChains.size(); i++) {
8402 mEffectChains[i]->setAudioSource_l(mAudioSource);
8403 }
8404 }
8405 }
8406
8407 if (mAudioHwDev->supportsAudioPatches()) {
8408 status = mHalDevice->createAudioPatch(patch->num_sources,
8409 patch->sources,
8410 patch->num_sinks,
8411 patch->sinks,
8412 handle);
8413 } else {
8414 char *address;
8415 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8416 //FIXME: we only support address on first sink with HAL version < 3.0
8417 address = audio_device_address_to_parameter(
8418 patch->sinks[0].ext.device.type,
8419 patch->sinks[0].ext.device.address);
8420 } else {
8421 address = (char *)calloc(1, 1);
8422 }
8423 AudioParameter param = AudioParameter(String8(address));
8424 free(address);
8425 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8426 if (!isOutput()) {
8427 param.addInt(String8(AudioParameter::keyInputSource),
8428 (int)patch->sinks[0].ext.mix.usecase.source);
8429 }
8430 status = mHalStream->setParameters(param.toString());
8431 *handle = AUDIO_PATCH_HANDLE_NONE;
8432 }
8433
8434 if (isOutput() && mPrevOutDevice != mOutDevice) {
8435 mPrevOutDevice = type;
8436 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008437 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008438 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008439 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008440 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008441 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008442 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008443 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008444 }
8445 if (!isOutput() && mPrevInDevice != mInDevice) {
8446 mPrevInDevice = type;
8447 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008448 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008449 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008450 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008451 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008452 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008453 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008454 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008455 }
8456 return status;
8457}
8458
8459status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8460{
8461 status_t status = NO_ERROR;
8462
8463 mInDevice = AUDIO_DEVICE_NONE;
8464
8465 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8466 supportsAudioPatches : false;
8467
8468 if (supportsAudioPatches) {
8469 status = mHalDevice->releaseAudioPatch(handle);
8470 } else {
8471 AudioParameter param;
8472 param.addInt(String8(AudioParameter::keyRouting), 0);
8473 status = mHalStream->setParameters(param.toString());
8474 }
8475 return status;
8476}
8477
Mikhail Naganovdc769682018-05-04 15:34:08 -07008478void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008479{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008480 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008481 if (isOutput()) {
8482 config->role = AUDIO_PORT_ROLE_SOURCE;
8483 config->ext.mix.hw_module = mAudioHwDev->handle();
8484 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8485 } else {
8486 config->role = AUDIO_PORT_ROLE_SINK;
8487 config->ext.mix.hw_module = mAudioHwDev->handle();
8488 config->ext.mix.usecase.source = mAudioSource;
8489 }
8490}
8491
8492status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8493{
8494 audio_session_t session = chain->sessionId();
8495
8496 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8497 // Attach all tracks with same session ID to this chain.
8498 // indicate all active tracks in the chain
8499 for (const sp<MmapTrack> &track : mActiveTracks) {
8500 if (session == track->sessionId()) {
8501 chain->incTrackCnt();
8502 chain->incActiveTrackCnt();
8503 }
8504 }
8505
8506 chain->setThread(this);
8507 chain->setInBuffer(nullptr);
8508 chain->setOutBuffer(nullptr);
8509 chain->syncHalEffectsState();
8510
8511 mEffectChains.add(chain);
8512 checkSuspendOnAddEffectChain_l(chain);
8513 return NO_ERROR;
8514}
8515
8516size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8517{
8518 audio_session_t session = chain->sessionId();
8519
8520 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8521
8522 for (size_t i = 0; i < mEffectChains.size(); i++) {
8523 if (chain == mEffectChains[i]) {
8524 mEffectChains.removeAt(i);
8525 // detach all active tracks from the chain
8526 // detach all tracks with same session ID from this chain
8527 for (const sp<MmapTrack> &track : mActiveTracks) {
8528 if (session == track->sessionId()) {
8529 chain->decActiveTrackCnt();
8530 chain->decTrackCnt();
8531 }
8532 }
8533 break;
8534 }
8535 }
8536 return mEffectChains.size();
8537}
8538
8539// hasAudioSession_l() must be called with ThreadBase::mLock held
8540uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8541{
8542 uint32_t result = 0;
8543 if (getEffectChain_l(sessionId) != 0) {
8544 result = EFFECT_SESSION;
8545 }
8546
8547 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8548 sp<MmapTrack> track = mActiveTracks[i];
8549 if (sessionId == track->sessionId()) {
8550 result |= TRACK_SESSION;
8551 if (track->isFastTrack()) {
8552 result |= FAST_SESSION;
8553 }
8554 break;
8555 }
8556 }
8557
8558 return result;
8559}
8560
8561void AudioFlinger::MmapThread::threadLoop_standby()
8562{
8563 mHalStream->standby();
8564}
8565
8566void AudioFlinger::MmapThread::threadLoop_exit()
8567{
Phil Burk7dce7282017-09-27 13:51:41 -07008568 // Do not call callback->onTearDown() because it is redundant for thread exit
8569 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008570}
8571
8572status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8573{
8574 return BAD_VALUE;
8575}
8576
8577bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8578{
8579 return false;
8580}
8581
8582status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8583 const effect_descriptor_t *desc, audio_session_t sessionId)
8584{
8585 // No global effect sessions on mmap threads
8586 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8587 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8588 desc->name, mThreadName);
8589 return BAD_VALUE;
8590 }
8591
8592 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8593 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8594 desc->name);
8595 return BAD_VALUE;
8596 }
8597 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008598 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8599 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008600 return BAD_VALUE;
8601 }
8602
8603 // Only allow effects without processing load or latency
8604 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8605 return BAD_VALUE;
8606 }
8607
8608 return NO_ERROR;
8609
8610}
8611
8612void AudioFlinger::MmapThread::checkInvalidTracks_l()
8613{
8614 for (const sp<MmapTrack> &track : mActiveTracks) {
8615 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008616 sp<MmapStreamCallback> callback = mCallback.promote();
8617 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008618 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008619 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008620 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008621 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8622 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8623 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008624 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008625 }
8626 }
8627}
8628
8629void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8630{
8631 dumpInternals(fd, args);
8632 dumpTracks(fd, args);
8633 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008634 dprintf(fd, " Local log:\n");
8635 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008636}
8637
8638void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8639{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008640 dumpBase(fd, args);
8641
8642 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8643 mAttr.content_type, mAttr.usage, mAttr.source);
8644 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8645 if (mActiveTracks.size() == 0) {
8646 dprintf(fd, " No active clients\n");
8647 }
8648}
8649
8650void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8651{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008652 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008653 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008654 dprintf(fd, " %zu Tracks\n", numtracks);
8655 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008656 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008657 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008658 MmapTrack::appendDumpHeader(result);
8659 for (size_t i = 0; i < numtracks ; ++i) {
8660 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008661 result.append(prefix);
8662 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008663 }
8664 } else {
8665 dprintf(fd, "\n");
8666 }
8667 write(fd, result.string(), result.size());
8668}
8669
8670AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8671 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8672 AudioHwDevice *hwDev, AudioStreamOut *output,
8673 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8674 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8675 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008676 mStreamVolume(1.0),
8677 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008678 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008679{
8680 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8681 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8682 mMasterVolume = audioFlinger->masterVolume_l();
8683 mMasterMute = audioFlinger->masterMute_l();
8684 if (mAudioHwDev) {
8685 if (mAudioHwDev->canSetMasterVolume()) {
8686 mMasterVolume = 1.0;
8687 }
8688
8689 if (mAudioHwDev->canSetMasterMute()) {
8690 mMasterMute = false;
8691 }
8692 }
8693}
8694
8695void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8696 audio_stream_type_t streamType,
8697 audio_session_t sessionId,
8698 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008699 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008700 audio_port_handle_t portId)
8701{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008702 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008703 mStreamType = streamType;
8704}
8705
8706AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8707{
8708 Mutex::Autolock _l(mLock);
8709 AudioStreamOut *output = mOutput;
8710 mOutput = NULL;
8711 return output;
8712}
8713
8714void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8715{
8716 Mutex::Autolock _l(mLock);
8717 // Don't apply master volume in SW if our HAL can do it for us.
8718 if (mAudioHwDev &&
8719 mAudioHwDev->canSetMasterVolume()) {
8720 mMasterVolume = 1.0;
8721 } else {
8722 mMasterVolume = value;
8723 }
8724}
8725
8726void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8727{
8728 Mutex::Autolock _l(mLock);
8729 // Don't apply master mute in SW if our HAL can do it for us.
8730 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8731 mMasterMute = false;
8732 } else {
8733 mMasterMute = muted;
8734 }
8735}
8736
8737void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8738{
8739 Mutex::Autolock _l(mLock);
8740 if (stream == mStreamType) {
8741 mStreamVolume = value;
8742 broadcast_l();
8743 }
8744}
8745
8746float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8747{
8748 Mutex::Autolock _l(mLock);
8749 if (stream == mStreamType) {
8750 return mStreamVolume;
8751 }
8752 return 0.0f;
8753}
8754
8755void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8756{
8757 Mutex::Autolock _l(mLock);
8758 if (stream == mStreamType) {
8759 mStreamMute= muted;
8760 broadcast_l();
8761 }
8762}
8763
8764void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8765{
8766 Mutex::Autolock _l(mLock);
8767 if (streamType == mStreamType) {
8768 for (const sp<MmapTrack> &track : mActiveTracks) {
8769 track->invalidate();
8770 }
8771 broadcast_l();
8772 }
8773}
8774
8775void AudioFlinger::MmapPlaybackThread::processVolume_l()
8776{
8777 float volume;
8778
8779 if (mMasterMute || mStreamMute) {
8780 volume = 0;
8781 } else {
8782 volume = mMasterVolume * mStreamVolume;
8783 }
8784
8785 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008786
8787 // Convert volumes from float to 8.24
8788 uint32_t vol = (uint32_t)(volume * (1 << 24));
8789
8790 // Delegate volume control to effect in track effect chain if needed
8791 // only one effect chain can be present on DirectOutputThread, so if
8792 // there is one, the track is connected to it
8793 if (!mEffectChains.isEmpty()) {
8794 mEffectChains[0]->setVolume_l(&vol, &vol);
8795 volume = (float)vol / (1 << 24);
8796 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008797 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008798 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8799 mHalVolFloat = volume; // HW volume control worked, so update value.
8800 mNoCallbackWarningCount = 0;
8801 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008802 sp<MmapStreamCallback> callback = mCallback.promote();
8803 if (callback != 0) {
8804 int channelCount;
8805 if (isOutput()) {
8806 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8807 } else {
8808 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8809 }
8810 Vector<float> values;
8811 for (int i = 0; i < channelCount; i++) {
8812 values.add(volume);
8813 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008814 mHalVolFloat = volume; // SW volume control worked, so update value.
8815 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008816 mLock.unlock();
8817 callback->onVolumeChanged(mChannelMask, values);
8818 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008819 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008820 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8821 ALOGW("Could not set MMAP stream volume: no volume callback!");
8822 mNoCallbackWarningCount++;
8823 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008824 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008825 }
8826 }
8827}
8828
Kevin Rocard069c2712018-03-29 19:09:14 -07008829void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8830{
8831 if (mOutput == nullptr || mOutput->stream == nullptr ||
8832 !mActiveTracks.readAndClearHasChanged()) {
8833 return;
8834 }
8835 StreamOutHalInterface::SourceMetadata metadata;
8836 for (const sp<MmapTrack> &track : mActiveTracks) {
8837 // No track is invalid as this is called after prepareTrack_l in the same critical section
8838 metadata.tracks.push_back({
8839 .usage = track->attributes().usage,
8840 .content_type = track->attributes().content_type,
8841 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8842 });
8843 }
8844 mOutput->stream->updateSourceMetadata(metadata);
8845}
8846
Eric Laurent6acd1d42017-01-04 14:23:29 -08008847void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8848{
8849 if (!mMasterMute) {
8850 char value[PROPERTY_VALUE_MAX];
8851 if (property_get("ro.audio.silent", value, "0") > 0) {
8852 char *endptr;
8853 unsigned long ul = strtoul(value, &endptr, 0);
8854 if (*endptr == '\0' && ul != 0) {
8855 ALOGD("Silence is golden");
8856 // The setprop command will not allow a property to be changed after
8857 // the first time it is set, so we don't have to worry about un-muting.
8858 setMasterMute_l(true);
8859 }
8860 }
8861 }
8862}
8863
8864void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8865{
8866 MmapThread::dumpInternals(fd, args);
8867
Glenn Kastend3bb6452016-12-05 18:14:37 -08008868 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8869 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008870 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8871}
8872
8873AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8874 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8875 AudioHwDevice *hwDev, AudioStreamIn *input,
8876 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8877 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8878 mInput(input)
8879{
8880 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8881 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8882}
8883
Eric Laurent331679c2018-04-16 17:03:16 -07008884status_t AudioFlinger::MmapCaptureThread::exitStandby()
8885{
8886 mInput->stream->setGain(1.0f);
8887 return MmapThread::exitStandby();
8888}
8889
Eric Laurent6acd1d42017-01-04 14:23:29 -08008890AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8891{
8892 Mutex::Autolock _l(mLock);
8893 AudioStreamIn *input = mInput;
8894 mInput = NULL;
8895 return input;
8896}
Kevin Rocard069c2712018-03-29 19:09:14 -07008897
Eric Laurent331679c2018-04-16 17:03:16 -07008898
8899void AudioFlinger::MmapCaptureThread::processVolume_l()
8900{
8901 bool changed = false;
8902 bool silenced = false;
8903
8904 sp<MmapStreamCallback> callback = mCallback.promote();
8905 if (callback == 0) {
8906 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8907 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
8908 mNoCallbackWarningCount++;
8909 }
8910 }
8911
8912 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
8913 // track is silenced and unmute otherwise
8914 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
8915 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
8916 changed = true;
8917 silenced = mActiveTracks[i]->isSilenced_l();
8918 }
8919 }
8920
8921 if (changed) {
8922 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
8923 }
8924}
8925
Kevin Rocard069c2712018-03-29 19:09:14 -07008926void AudioFlinger::MmapCaptureThread::updateMetadata_l()
8927{
8928 if (mInput == nullptr || mInput->stream == nullptr ||
8929 !mActiveTracks.readAndClearHasChanged()) {
8930 return;
8931 }
8932 StreamInHalInterface::SinkMetadata metadata;
8933 for (const sp<MmapTrack> &track : mActiveTracks) {
8934 // No track is invalid as this is called after prepareTrack_l in the same critical section
8935 metadata.tracks.push_back({
8936 .source = track->attributes().source,
8937 .gain = 1, // capture tracks do not have volumes
8938 });
8939 }
8940 mInput->stream->updateSinkMetadata(metadata);
8941}
8942
Eric Laurent331679c2018-04-16 17:03:16 -07008943void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
8944{
8945 Mutex::Autolock _l(mLock);
8946 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
8947 if (mActiveTracks[i]->uid() == uid) {
8948 mActiveTracks[i]->setSilenced_l(silenced);
8949 broadcast_l();
8950 }
8951 }
8952}
8953
Glenn Kasten63238ef2015-03-02 15:50:29 -08008954} // namespace android