blob: c2320bc0ec7a71a28697783c79e85cd2acd9f7a8 [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"
Eric Laurent81784c32012-11-19 14:55:58 -080065#include "ServiceUtilities.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070066#include "mediautils/SchedulingPolicyService.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, " );
772 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
773 } else {
774 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
775 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
776 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
777 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
778 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
783 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
784 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
785 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
786 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
787 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
788 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
789 }
790 const int len = s.length();
791 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700792 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700793 s.unlockBuffer(len - 2); // remove trailing ", "
794 }
795 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800796 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
798 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
799 return s;
800 default:
801 s.appendFormat("unknown mask, representation:%d bits:%#x",
802 representation, audio_channel_mask_get_bits(mask));
803 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800804 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800805}
806
Glenn Kasten0f11b512014-01-31 16:18:54 -0800807void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800808{
809 const size_t SIZE = 256;
810 char buffer[SIZE];
811 String8 result;
812
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800813 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
814 this, mThreadName, getTid(), type(), threadTypeToString(type()));
815
Eric Laurent81784c32012-11-19 14:55:58 -0800816 bool locked = AudioFlinger::dumpTryLock(mLock);
817 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800818 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800819 }
820
Elliott Hughes87cebad2014-05-22 10:14:43 -0700821 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700822 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700823 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700824 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700825 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700826 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700827 dprintf(fd, " Channel count: %u\n", mChannelCount);
828 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800829 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700830 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700831 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800833 size_t numConfig = mConfigEvents.size();
834 if (numConfig) {
835 for (size_t i = 0; i < numConfig; i++) {
836 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800838 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800840 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700841 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800842 }
Andy Hung293558a2017-03-21 12:19:20 -0700843 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700844 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
845 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800846 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800847
848 if (locked) {
849 mLock.unlock();
850 }
851}
852
853void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
854{
855 const size_t SIZE = 256;
856 char buffer[SIZE];
857 String8 result;
858
Marco Nelissenb2208842014-02-07 14:00:50 -0800859 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000860 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800861 write(fd, buffer, strlen(buffer));
862
Marco Nelissenb2208842014-02-07 14:00:50 -0800863 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800864 sp<EffectChain> chain = mEffectChains[i];
865 if (chain != 0) {
866 chain->dump(fd, args);
867 }
868 }
869}
870
Andy Hungdae27702016-10-31 14:01:16 -0700871void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800872{
873 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700874 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800875}
876
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100877String16 AudioFlinger::ThreadBase::getWakeLockTag()
878{
879 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800880 case MIXER:
881 return String16("AudioMix");
882 case DIRECT:
883 return String16("AudioDirectOut");
884 case DUPLICATING:
885 return String16("AudioDup");
886 case RECORD:
887 return String16("AudioIn");
888 case OFFLOAD:
889 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800890 case MMAP:
891 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800892 default:
893 ALOG_ASSERT(false);
894 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100895 }
896}
897
Andy Hungdae27702016-10-31 14:01:16 -0700898void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800899{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800900 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800901 if (mPowerManager != 0) {
902 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700903 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
904 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700905 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100906 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700907 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700908 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800909 if (status == NO_ERROR) {
910 mWakeLockToken = binder;
911 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800912 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800913 }
Wei Jia3f273d12015-11-24 09:06:49 -0800914
Andy Hung3f0c9022016-01-15 17:49:46 -0800915 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800916 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
917 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800918}
919
920void AudioFlinger::ThreadBase::releaseWakeLock()
921{
922 Mutex::Autolock _l(mLock);
923 releaseWakeLock_l();
924}
925
926void AudioFlinger::ThreadBase::releaseWakeLock_l()
927{
Andy Hung3f0c9022016-01-15 17:49:46 -0800928 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800930 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800931 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700932 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
933 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800934 }
935 mWakeLockToken.clear();
936 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800937}
938
939void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700940 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800941 // use checkService() to avoid blocking if power service is not up yet
942 sp<IBinder> binder =
943 defaultServiceManager()->checkService(String16("power"));
944 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800945 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 } else {
947 mPowerManager = interface_cast<IPowerManager>(binder);
948 binder->linkToDeath(mDeathRecipient);
949 }
950 }
951}
952
Andy Hungd01b0f12016-11-07 16:10:30 -0800953void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800954 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700955
956#if !LOG_NDEBUG
957 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800958 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700959 s << uid << " ";
960 }
961 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
962#endif
963
Andy Hung438e7572015-12-14 15:51:17 -0800964 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
965 if (mSystemReady) {
966 ALOGE("no wake lock to update, but system ready!");
967 } else {
968 ALOGW("no wake lock to update, system not ready yet");
969 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 return;
971 }
972 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800973 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
974 status_t status = mPowerManager->updateWakeLockUids(
975 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
976 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800977 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800978 }
979}
980
Eric Laurent81784c32012-11-19 14:55:58 -0800981void AudioFlinger::ThreadBase::clearPowerManager()
982{
983 Mutex::Autolock _l(mLock);
984 releaseWakeLock_l();
985 mPowerManager.clear();
986}
987
Glenn Kasten0f11b512014-01-31 16:18:54 -0800988void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800989{
990 sp<ThreadBase> thread = mThread.promote();
991 if (thread != 0) {
992 thread->clearPowerManager();
993 }
994 ALOGW("power manager service died !!!");
995}
996
Eric Laurent81784c32012-11-19 14:55:58 -0800997void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -0800998 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -0800999{
1000 sp<EffectChain> chain = getEffectChain_l(sessionId);
1001 if (chain != 0) {
1002 if (type != NULL) {
1003 chain->setEffectSuspended_l(type, suspend);
1004 } else {
1005 chain->setEffectSuspendedAll_l(suspend);
1006 }
1007 }
1008
1009 updateSuspendedSessions_l(type, suspend, sessionId);
1010}
1011
1012void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1013{
1014 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1015 if (index < 0) {
1016 return;
1017 }
1018
1019 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1020 mSuspendedSessions.valueAt(index);
1021
1022 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001023 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001024 for (int j = 0; j < desc->mRefCount; j++) {
1025 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1026 chain->setEffectSuspendedAll_l(true);
1027 } else {
1028 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1029 desc->mType.timeLow);
1030 chain->setEffectSuspended_l(&desc->mType, true);
1031 }
1032 }
1033 }
1034}
1035
1036void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1037 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001038 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001039{
1040 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1041
1042 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1043
1044 if (suspend) {
1045 if (index >= 0) {
1046 sessionEffects = mSuspendedSessions.valueAt(index);
1047 } else {
1048 mSuspendedSessions.add(sessionId, sessionEffects);
1049 }
1050 } else {
1051 if (index < 0) {
1052 return;
1053 }
1054 sessionEffects = mSuspendedSessions.valueAt(index);
1055 }
1056
1057
1058 int key = EffectChain::kKeyForSuspendAll;
1059 if (type != NULL) {
1060 key = type->timeLow;
1061 }
1062 index = sessionEffects.indexOfKey(key);
1063
1064 sp<SuspendedSessionDesc> desc;
1065 if (suspend) {
1066 if (index >= 0) {
1067 desc = sessionEffects.valueAt(index);
1068 } else {
1069 desc = new SuspendedSessionDesc();
1070 if (type != NULL) {
1071 desc->mType = *type;
1072 }
1073 sessionEffects.add(key, desc);
1074 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1075 }
1076 desc->mRefCount++;
1077 } else {
1078 if (index < 0) {
1079 return;
1080 }
1081 desc = sessionEffects.valueAt(index);
1082 if (--desc->mRefCount == 0) {
1083 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1084 sessionEffects.removeItemsAt(index);
1085 if (sessionEffects.isEmpty()) {
1086 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1087 sessionId);
1088 mSuspendedSessions.removeItem(sessionId);
1089 }
1090 }
1091 }
1092 if (!sessionEffects.isEmpty()) {
1093 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1094 }
1095}
1096
1097void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1098 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001099 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001100{
1101 Mutex::Autolock _l(mLock);
1102 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1103}
1104
1105void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(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 if (mType != RECORD) {
1110 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1111 // another session. This gives the priority to well behaved effect control panels
1112 // and applications not using global effects.
1113 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1114 // global effects
1115 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1116 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1117 }
1118 }
1119
1120 sp<EffectChain> chain = getEffectChain_l(sessionId);
1121 if (chain != 0) {
1122 chain->checkSuspendOnEffectEnabled(effect, enabled);
1123 }
1124}
1125
Eric Laurent4c415062016-06-17 16:14:16 -07001126// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1127status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1128 const effect_descriptor_t *desc, audio_session_t sessionId)
1129{
1130 // No global effect sessions on record threads
1131 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1132 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1133 desc->name, mThreadName);
1134 return BAD_VALUE;
1135 }
1136 // only pre processing effects on record thread
1137 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1138 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1139 desc->name, mThreadName);
1140 return BAD_VALUE;
1141 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001142
1143 // always allow effects without processing load or latency
1144 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1145 return NO_ERROR;
1146 }
1147
Eric Laurent4c415062016-06-17 16:14:16 -07001148 audio_input_flags_t flags = mInput->flags;
1149 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1150 if (flags & AUDIO_INPUT_FLAG_RAW) {
1151 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1152 desc->name, mThreadName);
1153 return BAD_VALUE;
1154 }
1155 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1156 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1157 desc->name, mThreadName);
1158 return BAD_VALUE;
1159 }
1160 }
1161 return NO_ERROR;
1162}
1163
1164// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1165status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1166 const effect_descriptor_t *desc, audio_session_t sessionId)
1167{
1168 // no preprocessing on playback threads
1169 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1170 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1171 " thread %s", desc->name, mThreadName);
1172 return BAD_VALUE;
1173 }
1174
Eric Laurent3e4de772017-07-16 16:55:08 -07001175 // always allow effects without processing load or latency
1176 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1177 return NO_ERROR;
1178 }
1179
Eric Laurent4c415062016-06-17 16:14:16 -07001180 switch (mType) {
1181 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001182#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001183 // Reject any effect on mixer multichannel sinks.
1184 // TODO: fix both format and multichannel issues with effects.
1185 if (mChannelCount != FCC_2) {
1186 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1187 " thread %s", desc->name, mChannelCount, mThreadName);
1188 return BAD_VALUE;
1189 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001190#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001191 audio_output_flags_t flags = mOutput->flags;
1192 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1193 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1194 // global effects are applied only to non fast tracks if they are SW
1195 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1196 break;
1197 }
1198 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1199 // only post processing on output stage session
1200 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1201 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1202 " on output stage session", desc->name);
1203 return BAD_VALUE;
1204 }
1205 } else {
1206 // no restriction on effects applied on non fast tracks
1207 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1208 break;
1209 }
1210 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001211
Eric Laurent4c415062016-06-17 16:14:16 -07001212 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1213 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1214 desc->name);
1215 return BAD_VALUE;
1216 }
1217 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1218 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1219 " in fast mode", desc->name);
1220 return BAD_VALUE;
1221 }
1222 }
1223 } break;
1224 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001225 // nothing actionable on offload threads, if the effect:
1226 // - is offloadable: the effect can be created
1227 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1228 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001229 break;
1230 case DIRECT:
1231 // Reject any effect on Direct output threads for now, since the format of
1232 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1233 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1234 desc->name, mThreadName);
1235 return BAD_VALUE;
1236 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001237#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001238 // Reject any effect on mixer multichannel sinks.
1239 // TODO: fix both format and multichannel issues with effects.
1240 if (mChannelCount != FCC_2) {
1241 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1242 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1243 return BAD_VALUE;
1244 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001245#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001246 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1247 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1248 " thread %s", desc->name, mThreadName);
1249 return BAD_VALUE;
1250 }
1251 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1252 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1253 " DUPLICATING thread %s", desc->name, mThreadName);
1254 return BAD_VALUE;
1255 }
1256 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1257 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1258 " DUPLICATING thread %s", desc->name, mThreadName);
1259 return BAD_VALUE;
1260 }
1261 break;
1262 default:
1263 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1264 }
1265
1266 return NO_ERROR;
1267}
1268
Eric Laurent81784c32012-11-19 14:55:58 -08001269// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1270sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1271 const sp<AudioFlinger::Client>& client,
1272 const sp<IEffectClient>& effectClient,
1273 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001274 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001275 effect_descriptor_t *desc,
1276 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001277 status_t *status,
1278 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001279{
1280 sp<EffectModule> effect;
1281 sp<EffectHandle> handle;
1282 status_t lStatus;
1283 sp<EffectChain> chain;
1284 bool chainCreated = false;
1285 bool effectCreated = false;
1286 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001287 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001288
1289 lStatus = initCheck();
1290 if (lStatus != NO_ERROR) {
1291 ALOGW("createEffect_l() Audio driver not initialized.");
1292 goto Exit;
1293 }
1294
Eric Laurent81784c32012-11-19 14:55:58 -08001295 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1296
1297 { // scope for mLock
1298 Mutex::Autolock _l(mLock);
1299
Eric Laurent4c415062016-06-17 16:14:16 -07001300 lStatus = checkEffectCompatibility_l(desc, sessionId);
1301 if (lStatus != NO_ERROR) {
1302 goto Exit;
1303 }
1304
Eric Laurent81784c32012-11-19 14:55:58 -08001305 // check for existing effect chain with the requested audio session
1306 chain = getEffectChain_l(sessionId);
1307 if (chain == 0) {
1308 // create a new chain for this session
1309 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1310 chain = new EffectChain(this, sessionId);
1311 addEffectChain_l(chain);
1312 chain->setStrategy(getStrategyForSession_l(sessionId));
1313 chainCreated = true;
1314 } else {
1315 effect = chain->getEffectFromDesc_l(desc);
1316 }
1317
1318 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1319
1320 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001321 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001322 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001323 lStatus = AudioSystem::registerEffect(
1324 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001325 if (lStatus != NO_ERROR) {
1326 goto Exit;
1327 }
1328 effectRegistered = true;
1329 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001330 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001331 if (lStatus != NO_ERROR) {
1332 goto Exit;
1333 }
1334 effectCreated = true;
1335
1336 effect->setDevice(mOutDevice);
1337 effect->setDevice(mInDevice);
1338 effect->setMode(mAudioFlinger->getMode());
1339 effect->setAudioSource(mAudioSource);
1340 }
1341 // create effect handle and connect it to effect module
1342 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001343 lStatus = handle->initCheck();
1344 if (lStatus == OK) {
1345 lStatus = effect->addHandle(handle.get());
1346 }
Eric Laurent81784c32012-11-19 14:55:58 -08001347 if (enabled != NULL) {
1348 *enabled = (int)effect->isEnabled();
1349 }
1350 }
1351
1352Exit:
1353 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1354 Mutex::Autolock _l(mLock);
1355 if (effectCreated) {
1356 chain->removeEffect_l(effect);
1357 }
1358 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001359 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001360 }
1361 if (chainCreated) {
1362 removeEffectChain_l(chain);
1363 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001364 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001365 }
1366
Glenn Kasten9156ef32013-08-06 15:39:08 -07001367 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001368 return handle;
1369}
1370
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001371void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1372 bool unpinIfLast)
1373{
1374 bool remove = false;
1375 sp<EffectModule> effect;
1376 {
1377 Mutex::Autolock _l(mLock);
1378
1379 effect = handle->effect().promote();
1380 if (effect == 0) {
1381 return;
1382 }
1383 // restore suspended effects if the disconnected handle was enabled and the last one.
1384 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1385 if (remove) {
1386 removeEffect_l(effect, true);
1387 }
1388 }
1389 if (remove) {
1390 mAudioFlinger->updateOrphanEffectChains(effect);
1391 AudioSystem::unregisterEffect(effect->id());
1392 if (handle->enabled()) {
1393 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1394 }
1395 }
1396}
1397
Glenn Kastend848eb42016-03-08 13:42:11 -08001398sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1399 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001400{
1401 Mutex::Autolock _l(mLock);
1402 return getEffect_l(sessionId, effectId);
1403}
1404
Glenn Kastend848eb42016-03-08 13:42:11 -08001405sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1406 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001407{
1408 sp<EffectChain> chain = getEffectChain_l(sessionId);
1409 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1410}
1411
1412// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1413// PlaybackThread::mLock held
1414status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1415{
1416 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001417 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001418 sp<EffectChain> chain = getEffectChain_l(sessionId);
1419 bool chainCreated = false;
1420
Eric Laurent5baf2af2013-09-12 17:37:00 -07001421 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001422 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001423 this, effect->desc().name, effect->desc().flags);
1424
Eric Laurent81784c32012-11-19 14:55:58 -08001425 if (chain == 0) {
1426 // create a new chain for this session
1427 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1428 chain = new EffectChain(this, sessionId);
1429 addEffectChain_l(chain);
1430 chain->setStrategy(getStrategyForSession_l(sessionId));
1431 chainCreated = true;
1432 }
1433 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1434
1435 if (chain->getEffectFromId_l(effect->id()) != 0) {
1436 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1437 this, effect->desc().name, chain.get());
1438 return BAD_VALUE;
1439 }
1440
Eric Laurent5baf2af2013-09-12 17:37:00 -07001441 effect->setOffloaded(mType == OFFLOAD, mId);
1442
Eric Laurent81784c32012-11-19 14:55:58 -08001443 status_t status = chain->addEffect_l(effect);
1444 if (status != NO_ERROR) {
1445 if (chainCreated) {
1446 removeEffectChain_l(chain);
1447 }
1448 return status;
1449 }
1450
1451 effect->setDevice(mOutDevice);
1452 effect->setDevice(mInDevice);
1453 effect->setMode(mAudioFlinger->getMode());
1454 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001455
Eric Laurent81784c32012-11-19 14:55:58 -08001456 return NO_ERROR;
1457}
1458
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001459void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001460
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001461 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001462 effect_descriptor_t desc = effect->desc();
1463 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1464 detachAuxEffect_l(effect->id());
1465 }
1466
1467 sp<EffectChain> chain = effect->chain().promote();
1468 if (chain != 0) {
1469 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001470 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001471 removeEffectChain_l(chain);
1472 }
1473 } else {
1474 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1475 }
1476}
1477
1478void AudioFlinger::ThreadBase::lockEffectChains_l(
1479 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1480{
1481 effectChains = mEffectChains;
1482 for (size_t i = 0; i < mEffectChains.size(); i++) {
1483 mEffectChains[i]->lock();
1484 }
1485}
1486
1487void AudioFlinger::ThreadBase::unlockEffectChains(
1488 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1489{
1490 for (size_t i = 0; i < effectChains.size(); i++) {
1491 effectChains[i]->unlock();
1492 }
1493}
1494
Glenn Kastend848eb42016-03-08 13:42:11 -08001495sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001496{
1497 Mutex::Autolock _l(mLock);
1498 return getEffectChain_l(sessionId);
1499}
1500
Glenn Kastend848eb42016-03-08 13:42:11 -08001501sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1502 const
Eric Laurent81784c32012-11-19 14:55:58 -08001503{
1504 size_t size = mEffectChains.size();
1505 for (size_t i = 0; i < size; i++) {
1506 if (mEffectChains[i]->sessionId() == sessionId) {
1507 return mEffectChains[i];
1508 }
1509 }
1510 return 0;
1511}
1512
1513void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1514{
1515 Mutex::Autolock _l(mLock);
1516 size_t size = mEffectChains.size();
1517 for (size_t i = 0; i < size; i++) {
1518 mEffectChains[i]->setMode_l(mode);
1519 }
1520}
1521
Eric Laurent83b88082014-06-20 18:31:16 -07001522void AudioFlinger::ThreadBase::getAudioPortConfig(struct audio_port_config *config)
1523{
1524 config->type = AUDIO_PORT_TYPE_MIX;
1525 config->ext.mix.handle = mId;
1526 config->sample_rate = mSampleRate;
1527 config->format = mFormat;
1528 config->channel_mask = mChannelMask;
1529 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1530 AUDIO_PORT_CONFIG_FORMAT;
1531}
1532
Eric Laurent72e3f392015-05-20 14:43:50 -07001533void AudioFlinger::ThreadBase::systemReady()
1534{
1535 Mutex::Autolock _l(mLock);
1536 if (mSystemReady) {
1537 return;
1538 }
1539 mSystemReady = true;
1540
1541 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1542 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1543 }
1544 mPendingConfigEvents.clear();
1545}
1546
Andy Hungdae27702016-10-31 14:01:16 -07001547template <typename T>
1548ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1549 ssize_t index = mActiveTracks.indexOf(track);
1550 if (index >= 0) {
1551 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1552 return index;
1553 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001554 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001555 mActiveTracksGeneration++;
1556 mLatestActiveTrack = track;
1557 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001558 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001559 return mActiveTracks.add(track);
1560}
1561
1562template <typename T>
1563ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1564 ssize_t index = mActiveTracks.remove(track);
1565 if (index < 0) {
1566 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1567 return index;
1568 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001569 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001570 mActiveTracksGeneration++;
1571 --mBatteryCounter[track->uid()].second;
1572 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001573 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001574 return index;
1575}
1576
1577template <typename T>
1578void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1579 for (const sp<T> &track : mActiveTracks) {
1580 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001581 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001582 }
1583 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001584 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001585 mActiveTracks.clear();
1586 mLatestActiveTrack.clear();
1587 mBatteryCounter.clear();
1588}
1589
1590template <typename T>
1591void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1592 sp<ThreadBase> thread, bool force) {
1593 // Updates ActiveTracks client uids to the thread wakelock.
1594 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1595 thread->updateWakeLockUids_l(getWakeLockUids());
1596 mLastActiveTracksGeneration = mActiveTracksGeneration;
1597 }
1598
1599 // Updates BatteryNotifier uids
1600 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1601 const uid_t uid = it->first;
1602 ssize_t &previous = it->second.first;
1603 ssize_t &current = it->second.second;
1604 if (current > 0) {
1605 if (previous == 0) {
1606 BatteryNotifier::getInstance().noteStartAudio(uid);
1607 }
1608 previous = current;
1609 ++it;
1610 } else if (current == 0) {
1611 if (previous > 0) {
1612 BatteryNotifier::getInstance().noteStopAudio(uid);
1613 }
1614 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1615 } else /* (current < 0) */ {
1616 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1617 }
1618 }
1619}
Eric Laurent83b88082014-06-20 18:31:16 -07001620
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001621template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001622bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1623 const bool hasChanged = mHasChanged;
1624 mHasChanged = false;
1625 return hasChanged;
1626}
1627
1628template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001629void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1630 const char *funcName, const sp<T> &track) const {
1631 if (mLocalLog != nullptr) {
1632 String8 result;
1633 track->appendDump(result, false /* active */);
1634 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1635 }
1636}
1637
Eric Laurent6acd1d42017-01-04 14:23:29 -08001638void AudioFlinger::ThreadBase::broadcast_l()
1639{
1640 // Thread could be blocked waiting for async
1641 // so signal it to handle state changes immediately
1642 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1643 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1644 mSignalPending = true;
1645 mWaitWorkCV.broadcast();
1646}
1647
Eric Laurent81784c32012-11-19 14:55:58 -08001648// ----------------------------------------------------------------------------
1649// Playback
1650// ----------------------------------------------------------------------------
1651
1652AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1653 AudioStreamOut* output,
1654 audio_io_handle_t id,
1655 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001656 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001657 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001658 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001659 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001660 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001661 mMixerBuffer(NULL),
1662 mMixerBufferSize(0),
1663 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1664 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001665 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001666 mEffectBuffer(NULL),
1667 mEffectBufferSize(0),
1668 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1669 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001670 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001671 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001672 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001673 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001674 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001675 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001676 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001677 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001678 mMixerStatus(MIXER_IDLE),
1679 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001680 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001681 mBytesRemaining(0),
1682 mCurrentWriteLength(0),
1683 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001684 mWriteAckSequence(0),
1685 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001686 mScreenState(AudioFlinger::mScreenState),
1687 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001688 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001689 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1690 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001691{
Glenn Kastend7dca052015-03-05 16:05:54 -08001692 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1693 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001694
1695 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1696 // it would be safer to explicitly pass initial masterVolume/masterMute as
1697 // parameter.
1698 //
1699 // If the HAL we are using has support for master volume or master mute,
1700 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1701 // and the mute set to false).
1702 mMasterVolume = audioFlinger->masterVolume_l();
1703 mMasterMute = audioFlinger->masterMute_l();
1704 if (mOutput && mOutput->audioHwDev) {
1705 if (mOutput->audioHwDev->canSetMasterVolume()) {
1706 mMasterVolume = 1.0;
1707 }
1708
1709 if (mOutput->audioHwDev->canSetMasterMute()) {
1710 mMasterMute = false;
1711 }
1712 }
1713
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001714 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001715
Eric Laurent223fd5c2014-11-11 13:43:36 -08001716 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001717 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001718 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001719 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001720 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1721 }
Eric Laurent98e38192018-02-15 18:31:53 -08001722 // Audio patch volume is always max
1723 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1724 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001725}
1726
1727AudioFlinger::PlaybackThread::~PlaybackThread()
1728{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001729 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001730 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001731 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001732 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001733}
1734
1735void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1736{
1737 dumpInternals(fd, args);
1738 dumpTracks(fd, args);
1739 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001740 dprintf(fd, " Local log:\n");
1741 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001742}
1743
Glenn Kasten0f11b512014-01-31 16:18:54 -08001744void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001745{
Eric Laurent81784c32012-11-19 14:55:58 -08001746 String8 result;
1747
Marco Nelissenb2208842014-02-07 14:00:50 -08001748 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001749 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1750 const stream_type_t *st = &mStreamTypes[i];
1751 if (i > 0) {
1752 result.appendFormat(", ");
1753 }
1754 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1755 if (st->mute) {
1756 result.append("M");
1757 }
1758 }
1759 result.append("\n");
1760 write(fd, result.string(), result.length());
1761 result.clear();
1762
Eric Laurent81784c32012-11-19 14:55:58 -08001763 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1764 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001765 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001766 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001767
1768 size_t numtracks = mTracks.size();
1769 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001770 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001771 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001772 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001773 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001774 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001775 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001776 Track::appendDumpHeader(result);
1777 for (size_t i = 0; i < numtracks; ++i) {
1778 sp<Track> track = mTracks[i];
1779 if (track != 0) {
1780 bool active = mActiveTracks.indexOf(track) >= 0;
1781 if (active) {
1782 numactiveseen++;
1783 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001784 result.append(prefix);
1785 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001786 }
1787 }
1788 } else {
1789 result.append("\n");
1790 }
1791 if (numactiveseen != numactive) {
1792 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001793 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001794 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001795 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08001796 Track::appendDumpHeader(result);
1797 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001798 sp<Track> track = mActiveTracks[i];
1799 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001800 result.append(prefix);
1801 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001802 }
1803 }
1804 }
1805
1806 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001807}
1808
1809void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1810{
Glenn Kasten44182c22015-03-05 17:12:23 -08001811 dumpBase(fd, args);
1812
Elliott Hughes87cebad2014-05-22 10:14:43 -07001813 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001814 dprintf(fd, " Last write occurred (msecs): %llu\n",
1815 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001816 dprintf(fd, " Total writes: %d\n", mNumWrites);
1817 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1818 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1819 dprintf(fd, " Suspend count: %d\n", mSuspended);
1820 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1821 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1822 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1823 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001824 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001825 AudioStreamOut *output = mOutput;
1826 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001827 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1828 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001829 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1830 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1831 if (mPipeSink.get() != nullptr) {
1832 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1833 }
1834 if (output != nullptr) {
1835 dprintf(fd, " Hal stream dump:\n");
1836 (void)output->stream->dump(fd);
1837 }
Eric Laurent81784c32012-11-19 14:55:58 -08001838}
1839
1840// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001841
1842void AudioFlinger::PlaybackThread::onFirstRef()
1843{
Glenn Kastend7dca052015-03-05 16:05:54 -08001844 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001845}
1846
1847// ThreadBase virtuals
1848void AudioFlinger::PlaybackThread::preExit()
1849{
1850 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001851 // FIXME this is using hard-coded strings but in the future, this functionality will be
1852 // converted to use audio HAL extensions required to support tunneling
1853 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1854 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001855}
1856
1857// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1858sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1859 const sp<AudioFlinger::Client>& client,
1860 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001861 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001862 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001863 audio_format_t format,
1864 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001865 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001866 size_t *pNotificationFrameCount,
1867 uint32_t notificationsPerBuffer,
1868 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001869 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001870 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001871 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001872 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001873 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001874 status_t *status,
1875 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
Glenn Kasten74935e42013-12-19 08:56:45 -08001877 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001878 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001879 sp<Track> track;
1880 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001881 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001882 audio_output_flags_t requestedFlags = *flags;
1883
1884 if (*pSampleRate == 0) {
1885 *pSampleRate = mSampleRate;
1886 }
1887 uint32_t sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001888
1889 // special case for FAST flag considered OK if fast mixer is present
1890 if (hasFastMixer()) {
1891 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1892 }
1893
1894 // Check if requested flags are compatible with output stream flags
1895 if ((*flags & outputFlags) != *flags) {
1896 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1897 *flags, outputFlags);
1898 *flags = (audio_output_flags_t)(*flags & outputFlags);
1899 }
Eric Laurent81784c32012-11-19 14:55:58 -08001900
Eric Laurent81784c32012-11-19 14:55:58 -08001901 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001902 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001903 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001904 // PCM data
1905 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001906 // TODO: extract as a data library function that checks that a computationally
1907 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001908 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001909 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1910 (channelMask == AUDIO_CHANNEL_OUT_MONO
1911 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001912 // hardware sample rate
1913 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001914 // normal mixer has an associated fast mixer
1915 hasFastMixer() &&
1916 // there are sufficient fast track slots available
1917 (mFastTrackAvailMask != 0)
1918 // FIXME test that MixerThread for this fast track has a capable output HAL
1919 // FIXME add a permission test also?
1920 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001921 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1922 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001923 // read the fast track multiplier property the first time it is needed
1924 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1925 if (ok != 0) {
1926 ALOGE("%s pthread_once failed: %d", __func__, ok);
1927 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001928 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001929 }
Eric Laurent4c415062016-06-17 16:14:16 -07001930
1931 // check compatibility with audio effects.
1932 { // scope for mLock
1933 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001934 for (audio_session_t session : {
1935 AUDIO_SESSION_OUTPUT_STAGE,
1936 AUDIO_SESSION_OUTPUT_MIX,
1937 sessionId,
1938 }) {
1939 sp<EffectChain> chain = getEffectChain_l(session);
1940 if (chain.get() != nullptr) {
1941 audio_output_flags_t old = *flags;
1942 chain->checkOutputFlagCompatibility(flags);
1943 if (old != *flags) {
1944 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1945 (int)session, (int)old, (int)*flags);
1946 }
Eric Laurent4c415062016-06-17 16:14:16 -07001947 }
1948 }
1949 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001950 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001951 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1952 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001953 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001954 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1955 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001956 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001957 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001958 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001959 audio_is_linear_pcm(format),
1960 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001961 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001962 }
1963 }
Eric Laurent21da6472017-11-09 16:29:26 -08001964
1965 if (!audio_has_proportional_frames(format)) {
1966 if (sharedBuffer != 0) {
1967 // Same comment as below about ignoring frameCount parameter for set()
1968 frameCount = sharedBuffer->size();
1969 } else if (frameCount == 0) {
1970 frameCount = mNormalFrameCount;
1971 }
1972 if (notificationFrameCount != frameCount) {
1973 notificationFrameCount = frameCount;
1974 }
1975 } else if (sharedBuffer != 0) {
1976 // FIXME: Ensure client side memory buffers need
1977 // not have additional alignment beyond sample
1978 // (e.g. 16 bit stereo accessed as 32 bit frame).
1979 size_t alignment = audio_bytes_per_sample(format);
1980 if (alignment & 1) {
1981 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1982 alignment = 1;
1983 }
1984 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1985 size_t frameSize = channelCount * audio_bytes_per_sample(format);
1986 if (channelCount > 1) {
1987 // More than 2 channels does not require stronger alignment than stereo
1988 alignment <<= 1;
1989 }
1990 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
1991 ALOGE("Invalid buffer alignment: address %p, channel count %u",
1992 sharedBuffer->pointer(), channelCount);
1993 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07001994 goto Exit;
1995 }
Eric Laurent21da6472017-11-09 16:29:26 -08001996
1997 // When initializing a shared buffer AudioTrack via constructors,
1998 // there's no frameCount parameter.
1999 // But when initializing a shared buffer AudioTrack via set(),
2000 // there _is_ a frameCount parameter. We silently ignore it.
2001 frameCount = sharedBuffer->size() / frameSize;
2002 } else {
2003 size_t minFrameCount = 0;
2004 // For fast tracks we try to respect the application's request for notifications per buffer.
2005 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2006 if (notificationsPerBuffer > 0) {
2007 // Avoid possible arithmetic overflow during multiplication.
2008 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2009 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2010 notificationsPerBuffer, mFrameCount);
2011 } else {
2012 minFrameCount = mFrameCount * notificationsPerBuffer;
2013 }
2014 }
2015 } else {
2016 // For normal PCM streaming tracks, update minimum frame count.
2017 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2018 // cover audio hardware latency.
2019 // This is probably too conservative, but legacy application code may depend on it.
2020 // If you change this calculation, also review the start threshold which is related.
2021 uint32_t latencyMs = latency_l();
2022 if (latencyMs == 0) {
2023 ALOGE("Error when retrieving output stream latency");
2024 lStatus = UNKNOWN_ERROR;
2025 goto Exit;
2026 }
2027
2028 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2029 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2030
Eric Laurent81784c32012-11-19 14:55:58 -08002031 }
Eric Laurent21da6472017-11-09 16:29:26 -08002032 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002033 frameCount = minFrameCount;
2034 }
Eric Laurent81784c32012-11-19 14:55:58 -08002035 }
Eric Laurent21da6472017-11-09 16:29:26 -08002036
2037 // Make sure that application is notified with sufficient margin before underrun.
2038 // The client can divide the AudioTrack buffer into sub-buffers,
2039 // and expresses its desire to server as the notification frame count.
2040 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2041 size_t maxNotificationFrames;
2042 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2043 // notify every HAL buffer, regardless of the size of the track buffer
2044 maxNotificationFrames = mFrameCount;
2045 } else {
2046 // For normal tracks, use at least double-buffering if no sample rate conversion,
2047 // or at least triple-buffering if there is sample rate conversion
2048 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2049 maxNotificationFrames = frameCount / nBuffering;
2050 // If client requested a fast track but this was denied, then use the smaller maximum.
2051 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2052 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2053 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2054 maxNotificationFrames = maxNotificationFramesFastDenied;
2055 }
2056 }
2057 }
2058 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2059 if (notificationFrameCount == 0) {
2060 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2061 maxNotificationFrames, frameCount);
2062 } else {
2063 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2064 notificationFrameCount, maxNotificationFrames, frameCount);
2065 }
2066 notificationFrameCount = maxNotificationFrames;
2067 }
2068 }
2069
Glenn Kasten74935e42013-12-19 08:56:45 -08002070 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002071 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002072
Glenn Kastenc3df8382014-03-13 15:05:25 -07002073 switch (mType) {
2074
2075 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002076 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002077 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002078 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2079 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002080 sampleRate, format, channelMask, mOutput, mFormat);
2081 lStatus = BAD_VALUE;
2082 goto Exit;
2083 }
2084 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002085 break;
2086
2087 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002088 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002089 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2090 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002091 sampleRate, format, channelMask, mOutput, mFormat);
2092 lStatus = BAD_VALUE;
2093 goto Exit;
2094 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002095 break;
2096
2097 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002098 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002099 ALOGE("createTrack_l() Bad parameter: format %#x \""
2100 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002101 format, mOutput, mFormat);
2102 lStatus = BAD_VALUE;
2103 goto Exit;
2104 }
Andy Hungcd044842014-08-07 11:04:34 -07002105 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002106 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2107 lStatus = BAD_VALUE;
2108 goto Exit;
2109 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002110 break;
2111
Eric Laurent81784c32012-11-19 14:55:58 -08002112 }
2113
2114 lStatus = initCheck();
2115 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002116 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002117 goto Exit;
2118 }
2119
2120 { // scope for mLock
2121 Mutex::Autolock _l(mLock);
2122
2123 // all tracks in same audio session must share the same routing strategy otherwise
2124 // conflicts will happen when tracks are moved from one output to another by audio policy
2125 // manager
2126 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2127 for (size_t i = 0; i < mTracks.size(); ++i) {
2128 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002129 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002130 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2131 if (sessionId == t->sessionId() && strategy != actual) {
2132 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2133 strategy, actual);
2134 lStatus = BAD_VALUE;
2135 goto Exit;
2136 }
2137 }
2138 }
2139
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002140 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002141 channelMask, frameCount,
2142 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002143 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002144
Glenn Kasten03003332013-08-06 15:40:54 -07002145 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2146 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002147 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002148 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002149 goto Exit;
2150 }
2151 mTracks.add(track);
2152
2153 sp<EffectChain> chain = getEffectChain_l(sessionId);
2154 if (chain != 0) {
2155 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2156 track->setMainBuffer(chain->inBuffer());
2157 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2158 chain->incTrackCnt();
2159 }
2160
Eric Laurent05067782016-06-01 18:27:28 -07002161 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002162 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2163 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2164 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002165 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002166 }
2167 }
2168
2169 lStatus = NO_ERROR;
2170
2171Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002172 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002173 return track;
2174}
2175
Andy Hung1bc088a2018-02-09 15:57:31 -08002176template<typename T>
2177ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2178{
2179 const ssize_t index = mTracks.add(track);
2180 if (index >= 0) {
2181 // set name for track when adding.
2182 int name;
2183 if (mUnusedTrackNames.empty()) {
2184 name = mTracks.size() - 1; // new name {0 ... size-1}.
2185 } else {
2186 // reuse smallest name for deleted track.
2187 auto it = mUnusedTrackNames.begin();
2188 name = *it;
2189 (void)mUnusedTrackNames.erase(it);
2190 }
2191 track->setName(name);
2192 } else {
2193 LOG_ALWAYS_FATAL("cannot add track");
2194 }
2195 return index;
2196}
2197
2198template<typename T>
2199ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2200{
2201 const int name = track->name();
2202 const ssize_t index = mTracks.remove(track);
2203 if (index >= 0) {
2204 // invalidate name when removing from mTracks.
2205 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2206
2207 if (mSaveDeletedTrackNames) {
2208 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2209 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2210 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2211 mDeletedTrackNames.emplace(name);
2212 }
2213
2214 mUnusedTrackNames.emplace(name);
2215 track->setName(T::TRACK_NAME_PENDING);
2216 } else {
2217 LOG_ALWAYS_FATAL_IF(name >= 0,
2218 "valid name %d for track not in mTracks (returned %zd)", name, index);
2219 }
2220 return index;
2221}
2222
Eric Laurent81784c32012-11-19 14:55:58 -08002223uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2224{
2225 return latency;
2226}
2227
2228uint32_t AudioFlinger::PlaybackThread::latency() const
2229{
2230 Mutex::Autolock _l(mLock);
2231 return latency_l();
2232}
2233uint32_t AudioFlinger::PlaybackThread::latency_l() const
2234{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002235 uint32_t latency;
2236 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2237 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002238 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002239 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002240}
2241
2242void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2243{
2244 Mutex::Autolock _l(mLock);
2245 // Don't apply master volume in SW if our HAL can do it for us.
2246 if (mOutput && mOutput->audioHwDev &&
2247 mOutput->audioHwDev->canSetMasterVolume()) {
2248 mMasterVolume = 1.0;
2249 } else {
2250 mMasterVolume = value;
2251 }
2252}
2253
2254void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2255{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002256 if (isDuplicating()) {
2257 return;
2258 }
Eric Laurent81784c32012-11-19 14:55:58 -08002259 Mutex::Autolock _l(mLock);
2260 // Don't apply master mute in SW if our HAL can do it for us.
2261 if (mOutput && mOutput->audioHwDev &&
2262 mOutput->audioHwDev->canSetMasterMute()) {
2263 mMasterMute = false;
2264 } else {
2265 mMasterMute = muted;
2266 }
2267}
2268
2269void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2270{
2271 Mutex::Autolock _l(mLock);
2272 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002273 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002274}
2275
2276void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2277{
2278 Mutex::Autolock _l(mLock);
2279 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002280 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002281}
2282
2283float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2284{
2285 Mutex::Autolock _l(mLock);
2286 return mStreamTypes[stream].volume;
2287}
2288
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002289void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2290{
2291 mOutput->stream->setVolume(left, right);
2292}
2293
Eric Laurent81784c32012-11-19 14:55:58 -08002294// addTrack_l() must be called with ThreadBase::mLock held
2295status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2296{
2297 status_t status = ALREADY_EXISTS;
2298
Eric Laurent81784c32012-11-19 14:55:58 -08002299 if (mActiveTracks.indexOf(track) < 0) {
2300 // the track is newly added, make sure it fills up all its
2301 // buffers before playing. This is to ensure the client will
2302 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002303 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002304 TrackBase::track_state state = track->mState;
2305 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002306 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002307 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002308 mLock.lock();
2309 // abort track was stopped/paused while we released the lock
2310 if (state != track->mState) {
2311 if (status == NO_ERROR) {
2312 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002313 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002314 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002315 mLock.lock();
2316 }
2317 return INVALID_OPERATION;
2318 }
2319 // abort if start is rejected by audio policy manager
2320 if (status != NO_ERROR) {
2321 return PERMISSION_DENIED;
2322 }
2323#ifdef ADD_BATTERY_DATA
2324 // to track the speaker usage
2325 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2326#endif
2327 }
2328
Eric Laurent51716182016-02-29 18:00:56 -08002329 // set retry count for buffer fill
2330 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002331 if (track->isStopping_1()) {
2332 track->mRetryCount = kMaxTrackStopRetriesOffload;
2333 } else {
2334 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2335 }
2336 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002337 } else {
2338 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002339 track->mFillingUpStatus =
2340 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002341 }
2342
Eric Laurent81784c32012-11-19 14:55:58 -08002343 track->mResetDone = false;
2344 track->mPresentationCompleteFrames = 0;
2345 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002346 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2347 if (chain != 0) {
2348 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2349 track->sessionId());
2350 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002351 }
2352
2353 status = NO_ERROR;
2354 }
2355
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002356 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002357 return status;
2358}
2359
Eric Laurentbfb1b832013-01-07 09:53:42 -08002360bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002361{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002362 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002363 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2365 track->mState = TrackBase::STOPPED;
2366 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002367 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002368 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002369 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002370 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002371
2372 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002373}
2374
2375void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2376{
2377 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002378
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002379 String8 result;
2380 track->appendDump(result, false /* active */);
2381 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002382
Eric Laurent81784c32012-11-19 14:55:58 -08002383 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002384 if (track->isFastTrack()) {
2385 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002386 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002387 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2388 mFastTrackAvailMask |= 1 << index;
2389 // redundant as track is about to be destroyed, for dumpsys only
2390 track->mFastIndex = -1;
2391 }
2392 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2393 if (chain != 0) {
2394 chain->decTrackCnt();
2395 }
2396}
2397
2398String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2399{
Eric Laurent81784c32012-11-19 14:55:58 -08002400 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002401 String8 out_s8;
2402 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2403 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002404 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002405 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002406}
2407
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002408void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002409 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2410 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002411
Eric Laurent73e26b62015-04-27 16:55:58 -07002412 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002413
2414 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002415 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002416 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002417 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002418 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002419 desc->mChannelMask = mChannelMask;
2420 desc->mSamplingRate = mSampleRate;
2421 desc->mFormat = mFormat;
2422 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002423 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002424 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002425 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002426 break;
2427
Eric Laurent73e26b62015-04-27 16:55:58 -07002428 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002429 default:
2430 break;
2431 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002432 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002433}
2434
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002435void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002437 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002438}
2439
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002440void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002441{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002442 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002443}
2444
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002445void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002446{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002447 mCallbackThread->setAsyncError();
2448}
2449
Eric Laurent3b4529e2013-09-05 18:09:19 -07002450void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451{
2452 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002453 // reject out of sequence requests
2454 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2455 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456 mWaitWorkCV.signal();
2457 }
2458}
2459
Eric Laurent3b4529e2013-09-05 18:09:19 -07002460void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461{
2462 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002463 // reject out of sequence requests
2464 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2465 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002466 mWaitWorkCV.signal();
2467 }
2468}
2469
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002470void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002471{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002472 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002473 mSampleRate = mOutput->getSampleRate();
2474 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002475 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002476 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002477 }
Andy Hung9a592762014-07-21 21:56:01 -07002478 if ((mType == MIXER || mType == DUPLICATING)
2479 && !isValidPcmSinkChannelMask(mChannelMask)) {
2480 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2481 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002482 }
Andy Hunge5412692014-05-16 11:25:07 -07002483 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002484
2485 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002486 status_t result = mOutput->stream->getFormat(&mHALFormat);
2487 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002488 // Get format from the shim, which will be different than the HAL format
2489 // if playing compressed audio over HDMI passthrough.
2490 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002491 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002492 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002493 }
Andy Hung6146c082014-03-18 11:56:15 -07002494 if ((mType == MIXER || mType == DUPLICATING)
2495 && !isValidPcmSinkFormat(mFormat)) {
2496 LOG_FATAL("HAL format %#x not supported for mixed output",
2497 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002498 }
Phil Burk062e67a2015-02-11 13:40:50 -08002499 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002500 result = mOutput->stream->getBufferSize(&mBufferSize);
2501 LOG_ALWAYS_FATAL_IF(result != OK,
2502 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002503 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002504 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002505 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002506 mFrameCount);
2507 }
2508
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002509 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2510 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002511 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002512 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002513 }
2514 }
2515
Eric Laurentd1f69b02014-12-15 14:33:13 -08002516 mHwSupportsPause = false;
2517 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002518 bool supportsPause = false, supportsResume = false;
2519 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2520 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002521 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002522 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002523 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002524 } else if (supportsResume) {
2525 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002526 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002527 }
2528 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002529 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2530 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2531 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002532
Andy Hungfbfc3952015-01-15 13:33:51 -08002533 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2534 // For best precision, we use float instead of the associated output
2535 // device format (typically PCM 16 bit).
2536
2537 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2538 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2539 mBufferSize = mFrameSize * mFrameCount;
2540
2541 // TODO: We currently use the associated output device channel mask and sample rate.
2542 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2543 // (if a valid mask) to avoid premature downmix.
2544 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2545 // instead of the output device sample rate to avoid loss of high frequency information.
2546 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2547 }
2548
Andy Hung09a50072014-02-27 14:30:47 -08002549 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002550 double multiplier = 1.0;
2551 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2552 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002553 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2554 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002555
Eric Laurent81784c32012-11-19 14:55:58 -08002556 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2557 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2558 maxNormalFrameCount = maxNormalFrameCount & ~15;
2559 if (maxNormalFrameCount < minNormalFrameCount) {
2560 maxNormalFrameCount = minNormalFrameCount;
2561 }
2562 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2563 if (multiplier <= 1.0) {
2564 multiplier = 1.0;
2565 } else if (multiplier <= 2.0) {
2566 if (2 * mFrameCount <= maxNormalFrameCount) {
2567 multiplier = 2.0;
2568 } else {
2569 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2570 }
2571 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002572 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002573 }
2574 }
2575 mNormalFrameCount = multiplier * mFrameCount;
2576 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002577 if (mType == MIXER || mType == DUPLICATING) {
2578 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2579 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002580 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002581 mNormalFrameCount);
2582
Andy Hung08fb1742015-05-31 23:22:10 -07002583 // Check if we want to throttle the processing to no more than 2x normal rate
2584 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002585 mThreadThrottleTimeMs = 0;
2586 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002587 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2588
Andy Hung010a1a12014-03-13 13:57:33 -07002589 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2590 // Originally this was int16_t[] array, need to remove legacy implications.
2591 free(mSinkBuffer);
2592 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002593 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2594 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2595 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002596 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002597
Andy Hung69aed5f2014-02-25 17:24:40 -08002598 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2599 // drives the output.
2600 free(mMixerBuffer);
2601 mMixerBuffer = NULL;
2602 if (mMixerBufferEnabled) {
2603 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2604 mMixerBufferSize = mNormalFrameCount * mChannelCount
2605 * audio_bytes_per_sample(mMixerBufferFormat);
2606 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2607 }
Andy Hung98ef9782014-03-04 14:46:50 -08002608 free(mEffectBuffer);
2609 mEffectBuffer = NULL;
2610 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002611 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002612 mEffectBufferSize = mNormalFrameCount * mChannelCount
2613 * audio_bytes_per_sample(mEffectBufferFormat);
2614 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2615 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002616
Eric Laurent81784c32012-11-19 14:55:58 -08002617 // force reconfiguration of effect chains and engines to take new buffer size and audio
2618 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002619 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002620 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2621 // matter.
2622 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2623 Vector< sp<EffectChain> > effectChains = mEffectChains;
2624 for (size_t i = 0; i < effectChains.size(); i ++) {
2625 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2626 }
2627}
2628
Kevin Rocard069c2712018-03-29 19:09:14 -07002629void AudioFlinger::PlaybackThread::updateMetadata_l()
2630{
Kevin Rocard12381092018-04-11 09:19:59 -07002631 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2632 return; // That should not happen
2633 }
2634 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2635 for (const sp<Track> &track : mActiveTracks) {
2636 // Do not short-circuit as all hasChanged states must be reset
2637 // as all the metadata are going to be sent
2638 hasChanged |= track->readAndClearHasChanged();
2639 }
2640 if (!hasChanged) {
2641 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002642 }
2643 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002644 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002645 for (const sp<Track> &track : mActiveTracks) {
2646 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002647 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002648 }
Kevin Rocard12381092018-04-11 09:19:59 -07002649 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002650}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002651
Kevin Rocard12381092018-04-11 09:19:59 -07002652void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2653 const StreamOutHalInterface::SourceMetadata& metadata)
2654{
2655 mOutput->stream->updateSourceMetadata(metadata);
2656};
2657
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002658status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002659{
2660 if (halFrames == NULL || dspFrames == NULL) {
2661 return BAD_VALUE;
2662 }
2663 Mutex::Autolock _l(mLock);
2664 if (initCheck() != NO_ERROR) {
2665 return INVALID_OPERATION;
2666 }
Andy Hung818e7a32016-02-16 18:08:07 -08002667 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002668 *halFrames = framesWritten;
2669
2670 if (isSuspended()) {
2671 // return an estimation of rendered frames when the output is suspended
2672 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002673 *dspFrames = (uint32_t)
2674 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002675 return NO_ERROR;
2676 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002677 status_t status;
2678 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002679 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002680 *dspFrames = (size_t)frames;
2681 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002682 }
2683}
2684
Eric Laurent4c415062016-06-17 16:14:16 -07002685// hasAudioSession_l() must be called with ThreadBase::mLock held
2686uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002687{
Eric Laurent81784c32012-11-19 14:55:58 -08002688 uint32_t result = 0;
2689 if (getEffectChain_l(sessionId) != 0) {
2690 result = EFFECT_SESSION;
2691 }
2692
2693 for (size_t i = 0; i < mTracks.size(); ++i) {
2694 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002695 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002696 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002697 if (track->isFastTrack()) {
2698 result |= FAST_SESSION;
2699 }
Eric Laurent81784c32012-11-19 14:55:58 -08002700 break;
2701 }
2702 }
2703
2704 return result;
2705}
2706
Glenn Kastend848eb42016-03-08 13:42:11 -08002707uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002708{
2709 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2710 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2711 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2712 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2713 }
2714 for (size_t i = 0; i < mTracks.size(); i++) {
2715 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002716 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002717 return AudioSystem::getStrategyForStream(track->streamType());
2718 }
2719 }
2720 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2721}
2722
2723
Phil Burk062e67a2015-02-11 13:40:50 -08002724AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002725{
2726 Mutex::Autolock _l(mLock);
2727 return mOutput;
2728}
2729
Phil Burk062e67a2015-02-11 13:40:50 -08002730AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002731{
2732 Mutex::Autolock _l(mLock);
2733 AudioStreamOut *output = mOutput;
2734 mOutput = NULL;
2735 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2736 // must push a NULL and wait for ack
2737 mOutputSink.clear();
2738 mPipeSink.clear();
2739 mNormalSink.clear();
2740 return output;
2741}
2742
2743// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002744sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002745{
2746 if (mOutput == NULL) {
2747 return NULL;
2748 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002749 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002750}
2751
2752uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2753{
2754 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2755}
2756
2757status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2758{
2759 if (!isValidSyncEvent(event)) {
2760 return BAD_VALUE;
2761 }
2762
2763 Mutex::Autolock _l(mLock);
2764
2765 for (size_t i = 0; i < mTracks.size(); ++i) {
2766 sp<Track> track = mTracks[i];
2767 if (event->triggerSession() == track->sessionId()) {
2768 (void) track->setSyncEvent(event);
2769 return NO_ERROR;
2770 }
2771 }
2772
2773 return NAME_NOT_FOUND;
2774}
2775
2776bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2777{
2778 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2779}
2780
2781void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2782 const Vector< sp<Track> >& tracksToRemove)
2783{
2784 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002785 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002786 for (size_t i = 0 ; i < count ; i++) {
2787 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002788 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002789 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002790 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002791#ifdef ADD_BATTERY_DATA
2792 // to track the speaker usage
2793 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2794#endif
2795 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002796 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002797 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002798 }
Eric Laurent81784c32012-11-19 14:55:58 -08002799 }
2800 }
2801 }
Eric Laurent81784c32012-11-19 14:55:58 -08002802}
2803
2804void AudioFlinger::PlaybackThread::checkSilentMode_l()
2805{
2806 if (!mMasterMute) {
2807 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002808 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2809 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2810 return;
2811 }
Eric Laurent81784c32012-11-19 14:55:58 -08002812 if (property_get("ro.audio.silent", value, "0") > 0) {
2813 char *endptr;
2814 unsigned long ul = strtoul(value, &endptr, 0);
2815 if (*endptr == '\0' && ul != 0) {
2816 ALOGD("Silence is golden");
2817 // The setprop command will not allow a property to be changed after
2818 // the first time it is set, so we don't have to worry about un-muting.
2819 setMasterMute_l(true);
2820 }
2821 }
2822 }
2823}
2824
2825// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002826ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002827{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002828 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002829 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002831 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002832
2833 // If an NBAIO sink is present, use it to write the normal mixer's submix
2834 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002835
Andy Hung010a1a12014-03-13 13:57:33 -07002836 const size_t count = mBytesRemaining / mFrameSize;
2837
Simon Wilson2d590962012-11-29 15:18:50 -08002838 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002839 // update the setpoint when AudioFlinger::mScreenState changes
2840 uint32_t screenState = AudioFlinger::mScreenState;
2841 if (screenState != mScreenState) {
2842 mScreenState = screenState;
2843 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2844 if (pipe != NULL) {
2845 pipe->setAvgFrames((mScreenState & 1) ?
2846 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2847 }
2848 }
Andy Hung010a1a12014-03-13 13:57:33 -07002849 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002850 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002851 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002852 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002853 } else {
2854 bytesWritten = framesWritten;
2855 }
2856 // otherwise use the HAL / AudioStreamOut directly
2857 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002858 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002859
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002861 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2862 mWriteAckSequence += 2;
2863 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002864 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002865 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002867 // FIXME We should have an implementation of timestamps for direct output threads.
2868 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002869 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002870
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 if (mUseAsyncWrite &&
2872 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2873 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002874 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002876 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 }
Eric Laurent81784c32012-11-19 14:55:58 -08002878 }
2879
Eric Laurent81784c32012-11-19 14:55:58 -08002880 mNumWrites++;
2881 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002882 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 return bytesWritten;
2884}
2885
2886void AudioFlinger::PlaybackThread::threadLoop_drain()
2887{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002888 bool supportsDrain = false;
2889 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2891 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002892 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2893 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002895 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002896 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002897 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002898 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 }
2900}
2901
2902void AudioFlinger::PlaybackThread::threadLoop_exit()
2903{
Eric Laurent275e8e92014-11-30 15:14:47 -08002904 {
2905 Mutex::Autolock _l(mLock);
2906 for (size_t i = 0; i < mTracks.size(); i++) {
2907 sp<Track> track = mTracks[i];
2908 track->invalidate();
2909 }
Andy Hungdae27702016-10-31 14:01:16 -07002910 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2911 // After we exit there are no more track changes sent to BatteryNotifier
2912 // because that requires an active threadLoop.
2913 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2914 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002915 }
Eric Laurent81784c32012-11-19 14:55:58 -08002916}
2917
2918/*
2919The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002920 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002921 - mActiveSleepTimeUs from activeSleepTimeUs()
2922 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002923 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2924 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002925 - maxPeriod from frame count and sample rate (MIXER only)
2926
2927The parameters that affect these derived values are:
2928 - frame count
2929 - frame size
2930 - sample rate
2931 - device type: A2DP or not
2932 - device latency
2933 - format: PCM or not
2934 - active sleep time
2935 - idle sleep time
2936*/
2937
2938void AudioFlinger::PlaybackThread::cacheParameters_l()
2939{
Andy Hung25c2dac2014-02-27 14:56:00 -08002940 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002941 mActiveSleepTimeUs = activeSleepTimeUs();
2942 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002943
2944 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2945 // truncating audio when going to standby.
2946 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2947 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2948 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2949 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2950 }
2951 }
Eric Laurent81784c32012-11-19 14:55:58 -08002952}
2953
Eric Laurent13084622016-05-17 10:51:49 -07002954bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002955{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002956 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002957 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002958 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002959 size_t size = mTracks.size();
2960 for (size_t i = 0; i < size; i++) {
2961 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002962 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002963 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002964 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002965 }
2966 }
Eric Laurent13084622016-05-17 10:51:49 -07002967 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002968}
2969
Haynes Mathew George05317d22016-05-03 16:34:26 -07002970void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2971{
2972 Mutex::Autolock _l(mLock);
2973 invalidateTracks_l(streamType);
2974}
2975
Eric Laurent81784c32012-11-19 14:55:58 -08002976status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2977{
Glenn Kastend848eb42016-03-08 13:42:11 -08002978 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002979 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002980 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002981 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2982 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2983 &halInBuffer);
2984 if (result != OK) return result;
2985 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002986 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002987 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002988 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002989 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002990 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002991 if (mType != DIRECT) {
2992 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002993 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07002994 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002995 &halInBuffer);
2996 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002997#ifdef FLOAT_EFFECT_CHAIN
2998 buffer = halInBuffer->audioBuffer()->f32;
2999#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003000 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003001#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003002 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3003 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003004 }
3005
3006 // Attach all tracks with same session ID to this chain.
3007 for (size_t i = 0; i < mTracks.size(); ++i) {
3008 sp<Track> track = mTracks[i];
3009 if (session == track->sessionId()) {
3010 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3011 buffer);
3012 track->setMainBuffer(buffer);
3013 chain->incTrackCnt();
3014 }
3015 }
3016
3017 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003018 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003019 if (session == track->sessionId()) {
3020 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3021 chain->incActiveTrackCnt();
3022 }
3023 }
3024 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003025 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003026 chain->setInBuffer(halInBuffer);
3027 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003028 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003029 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003030 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3031 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003032 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003033 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003034 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003035 // Effect chain for other sessions are inserted at beginning of effect
3036 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003037 // sessions is not important.
3038 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3039 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3040 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003041 size_t size = mEffectChains.size();
3042 size_t i = 0;
3043 for (i = 0; i < size; i++) {
3044 if (mEffectChains[i]->sessionId() < session) {
3045 break;
3046 }
3047 }
3048 mEffectChains.insertAt(chain, i);
3049 checkSuspendOnAddEffectChain_l(chain);
3050
3051 return NO_ERROR;
3052}
3053
3054size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3055{
Glenn Kastend848eb42016-03-08 13:42:11 -08003056 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003057
3058 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3059
3060 for (size_t i = 0; i < mEffectChains.size(); i++) {
3061 if (chain == mEffectChains[i]) {
3062 mEffectChains.removeAt(i);
3063 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003064 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003065 if (session == track->sessionId()) {
3066 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3067 chain.get(), session);
3068 chain->decActiveTrackCnt();
3069 }
3070 }
3071
3072 // detach all tracks with same session ID from this chain
3073 for (size_t i = 0; i < mTracks.size(); ++i) {
3074 sp<Track> track = mTracks[i];
3075 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003076 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003077 chain->decTrackCnt();
3078 }
3079 }
3080 break;
3081 }
3082 }
3083 return mEffectChains.size();
3084}
3085
3086status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003087 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003088{
3089 Mutex::Autolock _l(mLock);
3090 return attachAuxEffect_l(track, EffectId);
3091}
3092
3093status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003094 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003095{
3096 status_t status = NO_ERROR;
3097
3098 if (EffectId == 0) {
3099 track->setAuxBuffer(0, NULL);
3100 } else {
3101 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3102 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3103 if (effect != 0) {
3104 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3105 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3106 } else {
3107 status = INVALID_OPERATION;
3108 }
3109 } else {
3110 status = BAD_VALUE;
3111 }
3112 }
3113 return status;
3114}
3115
3116void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3117{
3118 for (size_t i = 0; i < mTracks.size(); ++i) {
3119 sp<Track> track = mTracks[i];
3120 if (track->auxEffectId() == effectId) {
3121 attachAuxEffect_l(track, 0);
3122 }
3123 }
3124}
3125
3126bool AudioFlinger::PlaybackThread::threadLoop()
3127{
Glenn Kasten388d5712017-04-07 14:38:41 -07003128 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003129
Eric Laurent81784c32012-11-19 14:55:58 -08003130 Vector< sp<Track> > tracksToRemove;
3131
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003132 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003133 nsecs_t lastWriteFinished = -1; // time last server write completed
3134 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003135
3136 // MIXER
3137 nsecs_t lastWarning = 0;
3138
3139 // DUPLICATING
3140 // FIXME could this be made local to while loop?
3141 writeFrames = 0;
3142
3143 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003144 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003145
3146 if (mType == MIXER) {
3147 sleepTimeShift = 0;
3148 }
3149
3150 CpuStats cpuStats;
3151 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3152
3153 acquireWakeLock();
3154
Glenn Kasteneef598c2017-04-03 14:41:13 -07003155 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3156 // thread associated with this PlaybackThread.
3157 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3158 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003159 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3160 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003161 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003162 const char *logString = NULL;
3163
rago1bb90822017-05-02 18:31:48 -07003164 // Estimated time for next buffer to be written to hal. This is used only on
3165 // suspended mode (for now) to help schedule the wait time until next iteration.
3166 nsecs_t timeLoopNextNs = 0;
3167
Eric Laurent664539d2013-09-23 18:24:31 -07003168 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003169
Eric Laurent81784c32012-11-19 14:55:58 -08003170 while (!exitPending())
3171 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003172 // Log merge requests are performed during AudioFlinger binder transactions, but
3173 // that does not cover audio playback. It's requested here for that reason.
3174 mAudioFlinger->requestLogMerge();
3175
Eric Laurent81784c32012-11-19 14:55:58 -08003176 cpuStats.sample(myName);
3177
3178 Vector< sp<EffectChain> > effectChains;
3179
Eric Laurent81784c32012-11-19 14:55:58 -08003180 { // scope for mLock
3181
3182 Mutex::Autolock _l(mLock);
3183
Eric Laurent021cf962014-05-13 10:18:14 -07003184 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003185
Glenn Kasteneef598c2017-04-03 14:41:13 -07003186 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003187 if (logString != NULL) {
3188 mNBLogWriter->logTimestamp();
3189 mNBLogWriter->log(logString);
3190 logString = NULL;
3191 }
3192
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003193 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003194 // and associate with the sink frames written out. We need
3195 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003196 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003197 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003198 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003199 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003200 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003201 ExtendedTimestamp timestamp; // use private copy to fetch
3202 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003203
3204 // We keep track of the last valid kernel position in case we are in underrun
3205 // and the normal mixer period is the same as the fast mixer period, or there
3206 // is some error from the HAL.
3207 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3208 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3209 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3210 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3211 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3212
3213 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3214 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3215 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3216 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003217 }
3218
3219 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3220 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003221 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003222 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003223 }
3224
Andy Hung818e7a32016-02-16 18:08:07 -08003225 // copy over kernel info
3226 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003227 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3228 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003229 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3230 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003231 }
3232 // mFramesWritten for non-offloaded tracks are contiguous
3233 // even after standby() is called. This is useful for the track frame
3234 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003235 bool serverLocationUpdate = false;
3236 if (mFramesWritten != lastFramesWritten) {
3237 serverLocationUpdate = true;
3238 lastFramesWritten = mFramesWritten;
3239 }
3240 // Only update timestamps if there is a meaningful change.
3241 // Either the kernel timestamp must be valid or we have written something.
3242 if (kernelLocationUpdate || serverLocationUpdate) {
3243 if (serverLocationUpdate) {
3244 // use the time before we called the HAL write - it is a bit more accurate
3245 // to when the server last read data than the current time here.
3246 //
3247 // If we haven't written anything, mLastWriteTime will be -1
3248 // and we use systemTime().
3249 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3250 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3251 ? systemTime() : mLastWriteTime;
3252 }
Andy Hungdae27702016-10-31 14:01:16 -07003253
3254 for (const sp<Track> &t : mActiveTracks) {
3255 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003256 t->updateTrackFrameInfo(
3257 t->mAudioTrackServerProxy->framesReleased(),
3258 mFramesWritten,
3259 mTimestamp);
3260 }
Andy Hunge10393e2015-06-12 13:59:33 -07003261 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003262 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003263#if 0
3264 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003265 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003266 timespec ts;
3267 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003268 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003269 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003270 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003271 }
3272 ++z;
3273#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003274 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 if (mSignalPending) {
3276 // A signal was raised while we were unlocked
3277 mSignalPending = false;
3278 } else if (waitingAsyncCallback_l()) {
3279 if (exitPending()) {
3280 break;
3281 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003282 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003283 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003284 releaseWakeLock_l();
3285 released = true;
3286 }
Andy Hung10cbff12017-02-21 17:30:14 -08003287
3288 const int64_t waitNs = computeWaitTimeNs_l();
3289 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3290 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3291 if (status == TIMED_OUT) {
3292 mSignalPending = true; // if timeout recheck everything
3293 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003294 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003295 if (released) {
3296 acquireWakeLock_l();
3297 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003298 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3299 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003300
3301 continue;
3302 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003303 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003304 isSuspended()) {
3305 // put audio hardware into standby after short delay
3306 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003307
3308 threadLoop_standby();
3309
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003310 // This is where we go into standby
3311 if (!mStandby) {
3312 LOG_AUDIO_STATE();
3313 }
Eric Laurent81784c32012-11-19 14:55:58 -08003314 mStandby = true;
3315 }
3316
3317 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3318 // we're about to wait, flush the binder command buffer
3319 IPCThreadState::self()->flushCommands();
3320
3321 clearOutputTracks();
3322
3323 if (exitPending()) {
3324 break;
3325 }
3326
3327 releaseWakeLock_l();
3328 // wait until we have something to do...
3329 ALOGV("%s going to sleep", myName.string());
3330 mWaitWorkCV.wait(mLock);
3331 ALOGV("%s waking up", myName.string());
3332 acquireWakeLock_l();
3333
3334 mMixerStatus = MIXER_IDLE;
3335 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3336 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003337 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003338 checkSilentMode_l();
3339
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003340 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3341 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003342 if (mType == MIXER) {
3343 sleepTimeShift = 0;
3344 }
3345
3346 continue;
3347 }
3348 }
Eric Laurent81784c32012-11-19 14:55:58 -08003349 // mMixerStatusIgnoringFastTracks is also updated internally
3350 mMixerStatus = prepareTracks_l(&tracksToRemove);
3351
Andy Hungdae27702016-10-31 14:01:16 -07003352 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003353
Kevin Rocard069c2712018-03-29 19:09:14 -07003354 updateMetadata_l();
3355
Eric Laurent81784c32012-11-19 14:55:58 -08003356 // prevent any changes in effect chain list and in each effect chain
3357 // during mixing and effect process as the audio buffers could be deleted
3358 // or modified if an effect is created or deleted
3359 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003360 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003361
Eric Laurentbfb1b832013-01-07 09:53:42 -08003362 if (mBytesRemaining == 0) {
3363 mCurrentWriteLength = 0;
3364 if (mMixerStatus == MIXER_TRACKS_READY) {
3365 // threadLoop_mix() sets mCurrentWriteLength
3366 threadLoop_mix();
3367 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3368 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003369 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003370 // must be written to HAL
3371 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003372 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003373 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003374 }
3375 }
Andy Hung98ef9782014-03-04 14:46:50 -08003376 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003377 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003378 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3379 // or mSinkBuffer (if there are no effects).
3380 //
3381 // This is done pre-effects computation; if effects change to
3382 // support higher precision, this needs to move.
3383 //
3384 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003385 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003386 if (mMixerBufferValid) {
3387 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3388 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3389
Andy Hung2ddee192015-12-18 17:34:44 -08003390 // mono blend occurs for mixer threads only (not direct or offloaded)
3391 // and is handled here if we're going directly to the sink.
3392 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003393 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3394 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003395 }
3396
Andy Hung98ef9782014-03-04 14:46:50 -08003397 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3398 mNormalFrameCount * mChannelCount);
3399 }
3400
Eric Laurentbfb1b832013-01-07 09:53:42 -08003401 mBytesRemaining = mCurrentWriteLength;
3402 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003403 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3404 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3405 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3406 mBytesWritten += mBytesRemaining;
3407 mFramesWritten += framesRemaining;
3408 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 mBytesRemaining = 0;
3410 }
Eric Laurent81784c32012-11-19 14:55:58 -08003411
Eric Laurentbfb1b832013-01-07 09:53:42 -08003412 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003413 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003414 for (size_t i = 0; i < effectChains.size(); i ++) {
3415 effectChains[i]->process_l();
3416 }
Eric Laurent81784c32012-11-19 14:55:58 -08003417 }
3418 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003419 // Process effect chains for offloaded thread even if no audio
3420 // was read from audio track: process only updates effect state
3421 // and thus does have to be synchronized with audio writes but may have
3422 // to be called while waiting for async write callback
3423 if (mType == OFFLOAD) {
3424 for (size_t i = 0; i < effectChains.size(); i ++) {
3425 effectChains[i]->process_l();
3426 }
3427 }
Eric Laurent81784c32012-11-19 14:55:58 -08003428
Andy Hung98ef9782014-03-04 14:46:50 -08003429 // Only if the Effects buffer is enabled and there is data in the
3430 // Effects buffer (buffer valid), we need to
3431 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003432 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003433 if (mEffectBufferValid) {
3434 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003435
3436 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003437 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3438 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003439 }
3440
Andy Hung98ef9782014-03-04 14:46:50 -08003441 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3442 mNormalFrameCount * mChannelCount);
3443 }
3444
Eric Laurent81784c32012-11-19 14:55:58 -08003445 // enable changes in effect chain
3446 unlockEffectChains(effectChains);
3447
Eric Laurentbfb1b832013-01-07 09:53:42 -08003448 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003449 // mSleepTimeUs == 0 means we must write to audio hardware
3450 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003451 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003452 // We save lastWriteFinished here, as previousLastWriteFinished,
3453 // for throttling. On thread start, previousLastWriteFinished will be
3454 // set to -1, which properly results in no throttling after the first write.
3455 nsecs_t previousLastWriteFinished = lastWriteFinished;
3456 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003457 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003458 // FIXME rewrite to reduce number of system calls
3459 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003460 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003461 lastWriteFinished = systemTime();
3462 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003463 if (ret < 0) {
3464 mBytesRemaining = 0;
3465 } else {
3466 mBytesWritten += ret;
3467 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003468 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003469 }
3470 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3471 (mMixerStatus == MIXER_DRAIN_ALL)) {
3472 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003473 }
Andy Hung08fb1742015-05-31 23:22:10 -07003474 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003475 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003476 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003477 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003478 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003479 ATRACE_NAME("underrun");
3480 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003481 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003482 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003483 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003484 }
Andy Hung08fb1742015-05-31 23:22:10 -07003485
3486 if (mThreadThrottle
3487 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3488 && ret > 0) { // we wrote something
3489 // Limit MixerThread data processing to no more than twice the
3490 // expected processing rate.
3491 //
3492 // This helps prevent underruns with NuPlayer and other applications
3493 // which may set up buffers that are close to the minimum size, or use
3494 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3495 //
3496 // The throttle smooths out sudden large data drains from the device,
3497 // e.g. when it comes out of standby, which often causes problems with
3498 // (1) mixer threads without a fast mixer (which has its own warm-up)
3499 // (2) minimum buffer sized tracks (even if the track is full,
3500 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003501 //
3502 // Total time spent in last processing cycle equals time spent in
3503 // 1. threadLoop_write, as well as time spent in
3504 // 2. threadLoop_mix (significant for heavy mixing, especially
3505 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003506
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003507 // it's OK if deltaMs (and deltaNs) is an overestimate.
3508 nsecs_t deltaNs;
3509 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3510 __builtin_sub_overflow(
3511 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3512 const int32_t deltaMs = deltaNs / 1000000;
3513
Ivan Lozanoea04d392017-11-07 14:37:07 -08003514 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003515 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3516 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003517 // notify of throttle start on verbose log
3518 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3519 "mixer(%p) throttle begin:"
3520 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003521 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003522 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003523 // Throttle must be attributed to the previous mixer loop's write time
3524 // to allow back-to-back throttling.
3525 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003526 } else {
3527 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3528 if (diff > 0) {
3529 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003530 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003531 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3532 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003533 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003534 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3535 }
Andy Hung08fb1742015-05-31 23:22:10 -07003536 }
3537 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538 }
Eric Laurent81784c32012-11-19 14:55:58 -08003539
Eric Laurentbfb1b832013-01-07 09:53:42 -08003540 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003541 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003542 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003543 // suspended requires accurate metering of sleep time.
3544 if (isSuspended()) {
3545 // advance by expected sleepTime
3546 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3547 const nsecs_t nowNs = systemTime();
3548
3549 // compute expected next time vs current time.
3550 // (negative deltas are treated as delays).
3551 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3552 if (deltaNs < -kMaxNextBufferDelayNs) {
3553 // Delays longer than the max allowed trigger a reset.
3554 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3555 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3556 timeLoopNextNs = nowNs + deltaNs;
3557 } else if (deltaNs < 0) {
3558 // Delays within the max delay allowed: zero the delta/sleepTime
3559 // to help the system catch up in the next iteration(s)
3560 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3561 deltaNs = 0;
3562 }
3563 // update sleep time (which is >= 0)
3564 mSleepTimeUs = deltaNs / 1000;
3565 }
Eric Laurente93cc032016-05-05 10:15:10 -07003566 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3567 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003568 }
Glenn Kastene7754022014-10-31 12:11:26 -07003569 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003570 }
Eric Laurent81784c32012-11-19 14:55:58 -08003571 }
3572
3573 // Finally let go of removed track(s), without the lock held
3574 // since we can't guarantee the destructors won't acquire that
3575 // same lock. This will also mutate and push a new fast mixer state.
3576 threadLoop_removeTracks(tracksToRemove);
3577 tracksToRemove.clear();
3578
3579 // FIXME I don't understand the need for this here;
3580 // it was in the original code but maybe the
3581 // assignment in saveOutputTracks() makes this unnecessary?
3582 clearOutputTracks();
3583
3584 // Effect chains will be actually deleted here if they were removed from
3585 // mEffectChains list during mixing or effects processing
3586 effectChains.clear();
3587
3588 // FIXME Note that the above .clear() is no longer necessary since effectChains
3589 // is now local to this block, but will keep it for now (at least until merge done).
3590 }
3591
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592 threadLoop_exit();
3593
Eric Laurentcf817a22014-08-04 20:36:31 -07003594 if (!mStandby) {
3595 threadLoop_standby();
3596 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003597 }
3598
3599 releaseWakeLock();
3600
3601 ALOGV("Thread %p type %d exiting", this, mType);
3602 return false;
3603}
3604
Eric Laurentbfb1b832013-01-07 09:53:42 -08003605// removeTracks_l() must be called with ThreadBase::mLock held
3606void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3607{
3608 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003609 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 for (size_t i=0 ; i<count ; i++) {
3611 const sp<Track>& track = tracksToRemove.itemAt(i);
3612 mActiveTracks.remove(track);
3613 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3614 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3615 if (chain != 0) {
3616 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3617 track->sessionId());
3618 chain->decActiveTrackCnt();
3619 }
3620 if (track->isTerminated()) {
3621 removeTrack_l(track);
3622 }
3623 }
3624 }
3625
3626}
Eric Laurent81784c32012-11-19 14:55:58 -08003627
Eric Laurentaccc1472013-09-20 09:36:34 -07003628status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3629{
3630 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003631 ExtendedTimestamp ets;
3632 status_t status = mNormalSink->getTimestamp(ets);
3633 if (status == NO_ERROR) {
3634 status = ets.getBestTimestamp(&timestamp);
3635 }
3636 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003637 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003638 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003639 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003640 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003641 timestamp.mPosition = (uint32_t)position64;
3642 return NO_ERROR;
3643 }
3644 }
3645 return INVALID_OPERATION;
3646}
Eric Laurent1c333e22014-05-20 10:48:17 -07003647
Eric Laurent054d9d32015-04-24 08:48:48 -07003648status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3649 audio_patch_handle_t *handle)
3650{
Andy Hungf60abce2016-08-26 11:37:54 -07003651 status_t status;
3652 if (property_get_bool("af.patch_park", false /* default_value */)) {
3653 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3654 // or if HAL does not properly lock against access.
3655 AutoPark<FastMixer> park(mFastMixer);
3656 status = PlaybackThread::createAudioPatch_l(patch, handle);
3657 } else {
3658 status = PlaybackThread::createAudioPatch_l(patch, handle);
3659 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003660 return status;
3661}
3662
Eric Laurent1c333e22014-05-20 10:48:17 -07003663status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3664 audio_patch_handle_t *handle)
3665{
3666 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003667
3668 // store new device and send to effects
3669 audio_devices_t type = AUDIO_DEVICE_NONE;
3670 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3671 type |= patch->sinks[i].ext.device.type;
3672 }
3673
3674#ifdef ADD_BATTERY_DATA
3675 // when changing the audio output device, call addBatteryData to notify
3676 // the change
3677 if (mOutDevice != type) {
3678 uint32_t params = 0;
3679 // check whether speaker is on
3680 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3681 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003682 }
3683
Eric Laurent054d9d32015-04-24 08:48:48 -07003684 audio_devices_t deviceWithoutSpeaker
3685 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3686 // check if any other device (except speaker) is on
3687 if (type & deviceWithoutSpeaker) {
3688 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3689 }
3690
3691 if (params != 0) {
3692 addBatteryData(params);
3693 }
3694 }
3695#endif
3696
3697 for (size_t i = 0; i < mEffectChains.size(); i++) {
3698 mEffectChains[i]->setDevice_l(type);
3699 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003700
3701 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3702 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3703 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003704 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003705 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003706
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003707 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003708 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3709 status = hwDevice->createAudioPatch(patch->num_sources,
3710 patch->sources,
3711 patch->num_sinks,
3712 patch->sinks,
3713 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003714 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003715 char *address;
3716 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3717 //FIXME: we only support address on first sink with HAL version < 3.0
3718 address = audio_device_address_to_parameter(
3719 patch->sinks[0].ext.device.type,
3720 patch->sinks[0].ext.device.address);
3721 } else {
3722 address = (char *)calloc(1, 1);
3723 }
3724 AudioParameter param = AudioParameter(String8(address));
3725 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003726 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003727 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003728 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003729 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003730 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003731 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003732 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3733 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003734 return status;
3735}
3736
Eric Laurent054d9d32015-04-24 08:48:48 -07003737status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3738{
Andy Hungf60abce2016-08-26 11:37:54 -07003739 status_t status;
3740 if (property_get_bool("af.patch_park", false /* default_value */)) {
3741 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3742 // or if HAL does not properly lock against access.
3743 AutoPark<FastMixer> park(mFastMixer);
3744 status = PlaybackThread::releaseAudioPatch_l(handle);
3745 } else {
3746 status = PlaybackThread::releaseAudioPatch_l(handle);
3747 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003748 return status;
3749}
3750
Eric Laurent1c333e22014-05-20 10:48:17 -07003751status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3752{
3753 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003754
3755 mOutDevice = AUDIO_DEVICE_NONE;
3756
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003757 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003758 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3759 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003760 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003761 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003762 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003763 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 }
3765 return status;
3766}
3767
Eric Laurent83b88082014-06-20 18:31:16 -07003768void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3769{
3770 Mutex::Autolock _l(mLock);
3771 mTracks.add(track);
3772}
3773
3774void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3775{
3776 Mutex::Autolock _l(mLock);
3777 destroyTrack_l(track);
3778}
3779
3780void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3781{
3782 ThreadBase::getAudioPortConfig(config);
3783 config->role = AUDIO_PORT_ROLE_SOURCE;
3784 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3785 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3786}
3787
Eric Laurent81784c32012-11-19 14:55:58 -08003788// ----------------------------------------------------------------------------
3789
3790AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003791 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3792 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003793 // mAudioMixer below
3794 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003795 mFastMixerFutex(0),
3796 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003797 // mOutputSink below
3798 // mPipeSink below
3799 // mNormalSink below
3800{
3801 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003802 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003803 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003804 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3805 mNormalFrameCount);
3806 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3807
Andy Hungfbfc3952015-01-15 13:33:51 -08003808 if (type == DUPLICATING) {
3809 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3810 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3811 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3812 return;
3813 }
Eric Laurent81784c32012-11-19 14:55:58 -08003814 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003815 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003816 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003817 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003818#if !LOG_NDEBUG
3819 ssize_t index =
3820#else
3821 (void)
3822#endif
3823 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003824 ALOG_ASSERT(index == 0);
3825
3826 // initialize fast mixer depending on configuration
3827 bool initFastMixer;
3828 switch (kUseFastMixer) {
3829 case FastMixer_Never:
3830 initFastMixer = false;
3831 break;
3832 case FastMixer_Always:
3833 initFastMixer = true;
3834 break;
3835 case FastMixer_Static:
3836 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003837 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3838 // where the period is less than an experimentally determined threshold that can be
3839 // scheduled reliably with CFS. However, the BT A2DP HAL is
3840 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3841 initFastMixer = mFrameCount < mNormalFrameCount
3842 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003843 break;
3844 }
Andy Hungfda69402017-02-15 14:33:12 -08003845 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3846 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3847 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003848 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003849 audio_format_t fastMixerFormat;
3850 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3851 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3852 } else {
3853 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3854 }
3855 if (mFormat != fastMixerFormat) {
3856 // change our Sink format to accept our intermediate precision
3857 mFormat = fastMixerFormat;
3858 free(mSinkBuffer);
3859 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3860 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3861 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3862 }
Eric Laurent81784c32012-11-19 14:55:58 -08003863
3864 // create a MonoPipe to connect our submix to FastMixer
3865 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003866#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003867 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003868#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003869 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003870 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003871 format.mFormat = fastMixerFormat;
3872 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3873
Eric Laurent81784c32012-11-19 14:55:58 -08003874 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3875 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3876 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3877 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3878 const NBAIO_Format offers[1] = {format};
3879 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003880#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003881 ssize_t index =
3882#else
3883 (void)
3884#endif
3885 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003886 ALOG_ASSERT(index == 0);
3887 monoPipe->setAvgFrames((mScreenState & 1) ?
3888 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3889 mPipeSink = monoPipe;
3890
Glenn Kasten46909e72013-02-26 09:20:22 -08003891#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003892 if (mTeeSinkOutputEnabled) {
3893 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003894 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3895 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003896 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003897 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003898 ALOG_ASSERT(index == 0);
3899 mTeeSink = teeSink;
3900 PipeReader *teeSource = new PipeReader(*teeSink);
3901 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003902 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003903 ALOG_ASSERT(index == 0);
3904 mTeeSource = teeSource;
3905 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003906#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003907
3908 // create fast mixer and configure it initially with just one fast track for our submix
3909 mFastMixer = new FastMixer();
3910 FastMixerStateQueue *sq = mFastMixer->sq();
3911#ifdef STATE_QUEUE_DUMP
3912 sq->setObserverDump(&mStateQueueObserverDump);
3913 sq->setMutatorDump(&mStateQueueMutatorDump);
3914#endif
3915 FastMixerState *state = sq->begin();
3916 FastTrack *fastTrack = &state->mFastTracks[0];
3917 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3918 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3919 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003920 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3921 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003922 fastTrack->mGeneration++;
3923 state->mFastTracksGen++;
3924 state->mTrackMask = 1;
3925 // fast mixer will use the HAL output sink
3926 state->mOutputSink = mOutputSink.get();
3927 state->mOutputSinkGen++;
3928 state->mFrameCount = mFrameCount;
3929 state->mCommand = FastMixerState::COLD_IDLE;
3930 // already done in constructor initialization list
3931 //mFastMixerFutex = 0;
3932 state->mColdFutexAddr = &mFastMixerFutex;
3933 state->mColdGen++;
3934 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003935#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003936 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003937#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003938 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3939 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003940 sq->end();
3941 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3942
3943 // start the fast mixer
3944 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3945 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003946 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003947 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003948
3949#ifdef AUDIO_WATCHDOG
3950 // create and start the watchdog
3951 mAudioWatchdog = new AudioWatchdog();
3952 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3953 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3954 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003955 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003956#endif
3957
Eric Laurent81784c32012-11-19 14:55:58 -08003958 }
3959
3960 switch (kUseFastMixer) {
3961 case FastMixer_Never:
3962 case FastMixer_Dynamic:
3963 mNormalSink = mOutputSink;
3964 break;
3965 case FastMixer_Always:
3966 mNormalSink = mPipeSink;
3967 break;
3968 case FastMixer_Static:
3969 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3970 break;
3971 }
3972}
3973
3974AudioFlinger::MixerThread::~MixerThread()
3975{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003976 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003977 FastMixerStateQueue *sq = mFastMixer->sq();
3978 FastMixerState *state = sq->begin();
3979 if (state->mCommand == FastMixerState::COLD_IDLE) {
3980 int32_t old = android_atomic_inc(&mFastMixerFutex);
3981 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003982 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003983 }
3984 }
3985 state->mCommand = FastMixerState::EXIT;
3986 sq->end();
3987 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3988 mFastMixer->join();
3989 // Though the fast mixer thread has exited, it's state queue is still valid.
3990 // We'll use that extract the final state which contains one remaining fast track
3991 // corresponding to our sub-mix.
3992 state = sq->begin();
3993 ALOG_ASSERT(state->mTrackMask == 1);
3994 FastTrack *fastTrack = &state->mFastTracks[0];
3995 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3996 delete fastTrack->mBufferProvider;
3997 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003998 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003999#ifdef AUDIO_WATCHDOG
4000 if (mAudioWatchdog != 0) {
4001 mAudioWatchdog->requestExit();
4002 mAudioWatchdog->requestExitAndWait();
4003 mAudioWatchdog.clear();
4004 }
4005#endif
4006 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004007 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004008 delete mAudioMixer;
4009}
4010
4011
4012uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4013{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004014 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004015 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4016 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4017 }
4018 return latency;
4019}
4020
4021
4022void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4023{
4024 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4025}
4026
Eric Laurentbfb1b832013-01-07 09:53:42 -08004027ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004028{
4029 // FIXME we should only do one push per cycle; confirm this is true
4030 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004031 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004032 FastMixerStateQueue *sq = mFastMixer->sq();
4033 FastMixerState *state = sq->begin();
4034 if (state->mCommand != FastMixerState::MIX_WRITE &&
4035 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4036 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004037
4038 // FIXME workaround for first HAL write being CPU bound on some devices
4039 ATRACE_BEGIN("write");
4040 mOutput->write((char *)mSinkBuffer, 0);
4041 ATRACE_END();
4042
Eric Laurent81784c32012-11-19 14:55:58 -08004043 int32_t old = android_atomic_inc(&mFastMixerFutex);
4044 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004045 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004046 }
4047#ifdef AUDIO_WATCHDOG
4048 if (mAudioWatchdog != 0) {
4049 mAudioWatchdog->resume();
4050 }
4051#endif
4052 }
4053 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004054#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004055 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004056 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004057#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004058 sq->end();
4059 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4060 if (kUseFastMixer == FastMixer_Dynamic) {
4061 mNormalSink = mPipeSink;
4062 }
4063 } else {
4064 sq->end(false /*didModify*/);
4065 }
4066 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004067 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004068}
4069
4070void AudioFlinger::MixerThread::threadLoop_standby()
4071{
4072 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004073 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004074 FastMixerStateQueue *sq = mFastMixer->sq();
4075 FastMixerState *state = sq->begin();
4076 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004077 // Report any frames trapped in the Monopipe
4078 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4079 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4080 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4081 "monoPipeWritten:%lld monoPipeLeft:%lld",
4082 (long long)mFramesWritten, (long long)mSuspendedFrames,
4083 (long long)mPipeSink->framesWritten(), pipeFrames);
4084 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4085
Eric Laurent81784c32012-11-19 14:55:58 -08004086 state->mCommand = FastMixerState::COLD_IDLE;
4087 state->mColdFutexAddr = &mFastMixerFutex;
4088 state->mColdGen++;
4089 mFastMixerFutex = 0;
4090 sq->end();
4091 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4092 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4093 if (kUseFastMixer == FastMixer_Dynamic) {
4094 mNormalSink = mOutputSink;
4095 }
4096#ifdef AUDIO_WATCHDOG
4097 if (mAudioWatchdog != 0) {
4098 mAudioWatchdog->pause();
4099 }
4100#endif
4101 } else {
4102 sq->end(false /*didModify*/);
4103 }
4104 }
4105 PlaybackThread::threadLoop_standby();
4106}
4107
Eric Laurentbfb1b832013-01-07 09:53:42 -08004108bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4109{
4110 return false;
4111}
4112
4113bool AudioFlinger::PlaybackThread::shouldStandby_l()
4114{
4115 return !mStandby;
4116}
4117
4118bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4119{
4120 Mutex::Autolock _l(mLock);
4121 return waitingAsyncCallback_l();
4122}
4123
Eric Laurent81784c32012-11-19 14:55:58 -08004124// shared by MIXER and DIRECT, overridden by DUPLICATING
4125void AudioFlinger::PlaybackThread::threadLoop_standby()
4126{
4127 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004128 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004129 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004130 // discard any pending drain or write ack by incrementing sequence
4131 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4132 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004133 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004134 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4135 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004136 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004137 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004138}
4139
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004140void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4141{
4142 ALOGV("signal playback thread");
4143 broadcast_l();
4144}
4145
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004146void AudioFlinger::PlaybackThread::onAsyncError()
4147{
4148 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4149 invalidateTracks((audio_stream_type_t)i);
4150 }
4151}
4152
Eric Laurent81784c32012-11-19 14:55:58 -08004153void AudioFlinger::MixerThread::threadLoop_mix()
4154{
Eric Laurent81784c32012-11-19 14:55:58 -08004155 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004156 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004157 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004158 // increase sleep time progressively when application underrun condition clears.
4159 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4160 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4161 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004162 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004163 sleepTimeShift--;
4164 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004165 mSleepTimeUs = 0;
4166 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004167 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004168
Eric Laurent81784c32012-11-19 14:55:58 -08004169}
4170
4171void AudioFlinger::MixerThread::threadLoop_sleepTime()
4172{
4173 // If no tracks are ready, sleep once for the duration of an output
4174 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004175 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004176 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004177 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4178 // Using the Monopipe availableToWrite, we estimate the
4179 // sleep time to retry for more data (before we underrun).
4180 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4181 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4182 const size_t pipeFrames = monoPipe->maxFrames();
4183 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4184 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4185 const size_t framesDelay = std::min(
4186 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4187 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4188 pipeFrames, framesLeft, framesDelay);
4189 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4190 } else {
4191 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4192 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4193 mSleepTimeUs = kMinThreadSleepTimeUs;
4194 }
4195 // reduce sleep time in case of consecutive application underruns to avoid
4196 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4197 // duration we would end up writing less data than needed by the audio HAL if
4198 // the condition persists.
4199 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4200 sleepTimeShift++;
4201 }
Eric Laurent81784c32012-11-19 14:55:58 -08004202 }
4203 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004204 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004205 }
4206 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004207 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4208 // before effects processing or output.
4209 if (mMixerBufferValid) {
4210 memset(mMixerBuffer, 0, mMixerBufferSize);
4211 } else {
4212 memset(mSinkBuffer, 0, mSinkBufferSize);
4213 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004214 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004215 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4216 "anticipated start");
4217 }
4218 // TODO add standby time extension fct of effect tail
4219}
4220
4221// prepareTracks_l() must be called with ThreadBase::mLock held
4222AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4223 Vector< sp<Track> > *tracksToRemove)
4224{
Andy Hung1bc088a2018-02-09 15:57:31 -08004225 // clean up deleted track names in AudioMixer before allocating new tracks
4226 (void)mTracks.processDeletedTrackNames([this](int name) {
4227 // for each name, destroy it in the AudioMixer
4228 if (mAudioMixer->exists(name)) {
4229 mAudioMixer->destroy(name);
4230 }
4231 });
4232 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004233
4234 mixer_state mixerStatus = MIXER_IDLE;
4235 // find out which tracks need to be processed
4236 size_t count = mActiveTracks.size();
4237 size_t mixedTracks = 0;
4238 size_t tracksWithEffect = 0;
4239 // counts only _active_ fast tracks
4240 size_t fastTracks = 0;
4241 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4242
4243 float masterVolume = mMasterVolume;
4244 bool masterMute = mMasterMute;
4245
4246 if (masterMute) {
4247 masterVolume = 0;
4248 }
4249 // Delegate master volume control to effect in output mix effect chain if needed
4250 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4251 if (chain != 0) {
4252 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4253 chain->setVolume_l(&v, &v);
4254 masterVolume = (float)((v + (1 << 23)) >> 24);
4255 chain.clear();
4256 }
4257
4258 // prepare a new state to push
4259 FastMixerStateQueue *sq = NULL;
4260 FastMixerState *state = NULL;
4261 bool didModify = false;
4262 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004263 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004264 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004265 sq = mFastMixer->sq();
4266 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004267 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004268 }
4269
Andy Hung69aed5f2014-02-25 17:24:40 -08004270 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004271 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004272
Eric Laurent81784c32012-11-19 14:55:58 -08004273 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004274 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004275
4276 // this const just means the local variable doesn't change
4277 Track* const track = t.get();
4278
4279 // process fast tracks
4280 if (track->isFastTrack()) {
4281
4282 // It's theoretically possible (though unlikely) for a fast track to be created
4283 // and then removed within the same normal mix cycle. This is not a problem, as
4284 // the track never becomes active so it's fast mixer slot is never touched.
4285 // The converse, of removing an (active) track and then creating a new track
4286 // at the identical fast mixer slot within the same normal mix cycle,
4287 // is impossible because the slot isn't marked available until the end of each cycle.
4288 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004289 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004290 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4291 FastTrack *fastTrack = &state->mFastTracks[j];
4292
4293 // Determine whether the track is currently in underrun condition,
4294 // and whether it had a recent underrun.
4295 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4296 FastTrackUnderruns underruns = ftDump->mUnderruns;
4297 uint32_t recentFull = (underruns.mBitFields.mFull -
4298 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4299 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4300 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4301 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4302 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4303 uint32_t recentUnderruns = recentPartial + recentEmpty;
4304 track->mObservedUnderruns = underruns;
4305 // don't count underruns that occur while stopping or pausing
4306 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004307 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4308 recentUnderruns > 0) {
4309 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4310 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004311 } else {
4312 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004313 }
4314
4315 // This is similar to the state machine for normal tracks,
4316 // with a few modifications for fast tracks.
4317 bool isActive = true;
4318 switch (track->mState) {
4319 case TrackBase::STOPPING_1:
4320 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004321 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004322 track->mState = TrackBase::STOPPING_2;
4323 }
4324 break;
4325 case TrackBase::PAUSING:
4326 // ramp down is not yet implemented
4327 track->setPaused();
4328 break;
4329 case TrackBase::RESUMING:
4330 // ramp up is not yet implemented
4331 track->mState = TrackBase::ACTIVE;
4332 break;
4333 case TrackBase::ACTIVE:
4334 if (recentFull > 0 || recentPartial > 0) {
4335 // track has provided at least some frames recently: reset retry count
4336 track->mRetryCount = kMaxTrackRetries;
4337 }
4338 if (recentUnderruns == 0) {
4339 // no recent underruns: stay active
4340 break;
4341 }
4342 // there has recently been an underrun of some kind
4343 if (track->sharedBuffer() == 0) {
4344 // were any of the recent underruns "empty" (no frames available)?
4345 if (recentEmpty == 0) {
4346 // no, then ignore the partial underruns as they are allowed indefinitely
4347 break;
4348 }
4349 // there has recently been an "empty" underrun: decrement the retry counter
4350 if (--(track->mRetryCount) > 0) {
4351 break;
4352 }
4353 // indicate to client process that the track was disabled because of underrun;
4354 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004355 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004356 // remove from active list, but state remains ACTIVE [confusing but true]
4357 isActive = false;
4358 break;
4359 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004360 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004361 case TrackBase::STOPPING_2:
4362 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004363 case TrackBase::STOPPED:
4364 case TrackBase::FLUSHED: // flush() while active
4365 // Check for presentation complete if track is inactive
4366 // We have consumed all the buffers of this track.
4367 // This would be incomplete if we auto-paused on underrun
4368 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004369 uint32_t latency = 0;
4370 status_t result = mOutput->stream->getLatency(&latency);
4371 ALOGE_IF(result != OK,
4372 "Error when retrieving output stream latency: %d", result);
4373 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004374 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004375 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4376 // track stays in active list until presentation is complete
4377 break;
4378 }
4379 }
4380 if (track->isStopping_2()) {
4381 track->mState = TrackBase::STOPPED;
4382 }
4383 if (track->isStopped()) {
4384 // Can't reset directly, as fast mixer is still polling this track
4385 // track->reset();
4386 // So instead mark this track as needing to be reset after push with ack
4387 resetMask |= 1 << i;
4388 }
4389 isActive = false;
4390 break;
4391 case TrackBase::IDLE:
4392 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004393 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004394 }
4395
4396 if (isActive) {
4397 // was it previously inactive?
4398 if (!(state->mTrackMask & (1 << j))) {
4399 ExtendedAudioBufferProvider *eabp = track;
4400 VolumeProvider *vp = track;
4401 fastTrack->mBufferProvider = eabp;
4402 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004403 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004404 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004405 fastTrack->mGeneration++;
4406 state->mTrackMask |= 1 << j;
4407 didModify = true;
4408 // no acknowledgement required for newly active tracks
4409 }
Kevin Rocard12381092018-04-11 09:19:59 -07004410 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004411 // cache the combined master volume and stream type volume for fast mixer; this
4412 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004413 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004414 proxy->framesReleased()).first;
4415 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004416 * mStreamTypes[track->streamType()].volume
4417 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004418 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004419 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4420 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4421 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4422 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004423 ++fastTracks;
4424 } else {
4425 // was it previously active?
4426 if (state->mTrackMask & (1 << j)) {
4427 fastTrack->mBufferProvider = NULL;
4428 fastTrack->mGeneration++;
4429 state->mTrackMask &= ~(1 << j);
4430 didModify = true;
4431 // If any fast tracks were removed, we must wait for acknowledgement
4432 // because we're about to decrement the last sp<> on those tracks.
4433 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4434 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004435 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4436 // AudioTrack may start (which may not be with a start() but with a write()
4437 // after underrun) and immediately paused or released. In that case the
4438 // FastTrack state hasn't had time to update.
4439 // TODO Remove the ALOGW when this theory is confirmed.
4440 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004441 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4442 j, track->mState, state->mTrackMask, recentUnderruns,
4443 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004444 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004445 }
4446 tracksToRemove->add(track);
4447 // Avoids a misleading display in dumpsys
4448 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4449 }
4450 continue;
4451 }
4452
4453 { // local variable scope to avoid goto warning
4454
4455 audio_track_cblk_t* cblk = track->cblk();
4456
4457 // The first time a track is added we wait
4458 // for all its buffers to be filled before processing it
4459 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004460
4461 // if an active track doesn't exist in the AudioMixer, create it.
4462 if (!mAudioMixer->exists(name)) {
4463 status_t status = mAudioMixer->create(
4464 name,
4465 track->mChannelMask,
4466 track->mFormat,
4467 track->mSessionId);
4468 if (status != OK) {
4469 ALOGW("%s: cannot create track name"
4470 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4471 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4472 tracksToRemove->add(track);
4473 track->invalidate(); // consider it dead.
4474 continue;
4475 }
4476 }
4477
Eric Laurent81784c32012-11-19 14:55:58 -08004478 // make sure that we have enough frames to mix one full buffer.
4479 // enforce this condition only once to enable draining the buffer in case the client
4480 // app does not call stop() and relies on underrun to stop:
4481 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4482 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004483 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004484 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004485 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004486
4487 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004488 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004489 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4490 // add frames already consumed but not yet released by the resampler
4491 // because mAudioTrackServerProxy->framesReady() will include these frames
4492 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4493
Eric Laurent81784c32012-11-19 14:55:58 -08004494 uint32_t minFrames = 1;
4495 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4496 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004497 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004498 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004499
4500 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004501 if (ATRACE_ENABLED()) {
4502 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004503 std::string traceName("nRdy");
4504 traceName += std::to_string(track->name());
4505 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004506 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004507 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004508 !track->isPaused() && !track->isTerminated())
4509 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004510 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004511
4512 mixedTracks++;
4513
Andy Hung69aed5f2014-02-25 17:24:40 -08004514 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4515 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004516 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004517 if (track->mainBuffer() != mSinkBuffer &&
4518 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004519 if (mEffectBufferEnabled) {
4520 mEffectBufferValid = true; // Later can set directly.
4521 }
Eric Laurent81784c32012-11-19 14:55:58 -08004522 chain = getEffectChain_l(track->sessionId());
4523 // Delegate volume control to effect in track effect chain if needed
4524 if (chain != 0) {
4525 tracksWithEffect++;
4526 } else {
4527 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4528 "session %d",
4529 name, track->sessionId());
4530 }
4531 }
4532
4533
4534 int param = AudioMixer::VOLUME;
4535 if (track->mFillingUpStatus == Track::FS_FILLED) {
4536 // no ramp for the first volume setting
4537 track->mFillingUpStatus = Track::FS_ACTIVE;
4538 if (track->mState == TrackBase::RESUMING) {
4539 track->mState = TrackBase::ACTIVE;
4540 param = AudioMixer::RAMP_VOLUME;
4541 }
4542 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004543 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004544 // FIXME should not make a decision based on mServer
4545 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004546 // If the track is stopped before the first frame was mixed,
4547 // do not apply ramp
4548 param = AudioMixer::RAMP_VOLUME;
4549 }
4550
4551 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004552 uint32_t vl, vr; // in U8.24 integer format
4553 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004554 // read original volumes with volume control
4555 float typeVolume = mStreamTypes[track->streamType()].volume;
4556 float v = masterVolume * typeVolume;
4557
Glenn Kastene4756fe2012-11-29 13:38:14 -08004558 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004559 vl = vr = 0;
4560 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004561 if (track->isPausing()) {
4562 track->setPaused();
4563 }
4564 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004565 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004566 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004567 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4568 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004569 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004570 if (vlf > GAIN_FLOAT_UNITY) {
4571 ALOGV("Track left volume out of range: %.3g", vlf);
4572 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004573 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004574 if (vrf > GAIN_FLOAT_UNITY) {
4575 ALOGV("Track right volume out of range: %.3g", vrf);
4576 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004577 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004578 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004579 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004580 // now apply the master volume and stream type volume and shaper volume
4581 vlf *= v * vh;
4582 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004583 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004584 // then derive vl and vr as U8.24 versions for the effect chain
4585 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4586 vl = (uint32_t) (scaleto8_24 * vlf);
4587 vr = (uint32_t) (scaleto8_24 * vrf);
4588 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004589 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004590 // send level comes from shared memory and so may be corrupt
4591 if (sendLevel > MAX_GAIN_INT) {
4592 ALOGV("Track send level out of range: %04X", sendLevel);
4593 sendLevel = MAX_GAIN_INT;
4594 }
Andy Hung6be49402014-05-30 10:42:03 -07004595 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4596 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004597 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004598
Kevin Rocard12381092018-04-11 09:19:59 -07004599 track->setFinalVolume((vrf + vlf) / 2.f);
4600
Eric Laurent81784c32012-11-19 14:55:58 -08004601 // Delegate volume control to effect in track effect chain if needed
4602 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4603 // Do not ramp volume if volume is controlled by effect
4604 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004605 // Update remaining floating point volume levels
4606 vlf = (float)vl / (1 << 24);
4607 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004608 track->mHasVolumeController = true;
4609 } else {
4610 // force no volume ramp when volume controller was just disabled or removed
4611 // from effect chain to avoid volume spike
4612 if (track->mHasVolumeController) {
4613 param = AudioMixer::VOLUME;
4614 }
4615 track->mHasVolumeController = false;
4616 }
4617
Eric Laurent7c29ec92017-09-20 17:54:22 -07004618 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4619 // still applied by the mixer.
4620 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4621 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4622 if (v != mLeftVolFloat) {
4623 status_t result = mOutput->stream->setVolume(v, v);
4624 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4625 if (result == OK) {
4626 mLeftVolFloat = v;
4627 }
4628 }
4629 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4630 // remove stream volume contribution from software volume.
4631 if (v != 0.0f && mLeftVolFloat == v) {
4632 vlf = min(1.0f, vlf / v);
4633 vrf = min(1.0f, vrf / v);
4634 vaf = min(1.0f, vaf / v);
4635 }
4636 }
Eric Laurent81784c32012-11-19 14:55:58 -08004637 // XXX: these things DON'T need to be done each time
4638 mAudioMixer->setBufferProvider(name, track);
4639 mAudioMixer->enable(name);
4640
Andy Hung6be49402014-05-30 10:42:03 -07004641 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4642 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4643 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004644 mAudioMixer->setParameter(
4645 name,
4646 AudioMixer::TRACK,
4647 AudioMixer::FORMAT, (void *)track->format());
4648 mAudioMixer->setParameter(
4649 name,
4650 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004651 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004652 mAudioMixer->setParameter(
4653 name,
4654 AudioMixer::TRACK,
4655 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004656 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004657 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004658 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004659 if (reqSampleRate == 0) {
4660 reqSampleRate = mSampleRate;
4661 } else if (reqSampleRate > maxSampleRate) {
4662 reqSampleRate = maxSampleRate;
4663 }
Eric Laurent81784c32012-11-19 14:55:58 -08004664 mAudioMixer->setParameter(
4665 name,
4666 AudioMixer::RESAMPLE,
4667 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004668 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004669
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004670 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004671 mAudioMixer->setParameter(
4672 name,
4673 AudioMixer::TIMESTRETCH,
4674 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004675 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004676
Andy Hung69aed5f2014-02-25 17:24:40 -08004677 /*
4678 * Select the appropriate output buffer for the track.
4679 *
Andy Hung98ef9782014-03-04 14:46:50 -08004680 * Tracks with effects go into their own effects chain buffer
4681 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004682 *
4683 * Other tracks can use mMixerBuffer for higher precision
4684 * channel accumulation. If this buffer is enabled
4685 * (mMixerBufferEnabled true), then selected tracks will accumulate
4686 * into it.
4687 *
4688 */
4689 if (mMixerBufferEnabled
4690 && (track->mainBuffer() == mSinkBuffer
4691 || track->mainBuffer() == mMixerBuffer)) {
4692 mAudioMixer->setParameter(
4693 name,
4694 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004695 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004696 mAudioMixer->setParameter(
4697 name,
4698 AudioMixer::TRACK,
4699 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4700 // TODO: override track->mainBuffer()?
4701 mMixerBufferValid = true;
4702 } else {
4703 mAudioMixer->setParameter(
4704 name,
4705 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004706 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004707 mAudioMixer->setParameter(
4708 name,
4709 AudioMixer::TRACK,
4710 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4711 }
Eric Laurent81784c32012-11-19 14:55:58 -08004712 mAudioMixer->setParameter(
4713 name,
4714 AudioMixer::TRACK,
4715 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4716
4717 // reset retry count
4718 track->mRetryCount = kMaxTrackRetries;
4719
4720 // If one track is ready, set the mixer ready if:
4721 // - the mixer was not ready during previous round OR
4722 // - no other track is not ready
4723 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4724 mixerStatus != MIXER_TRACKS_ENABLED) {
4725 mixerStatus = MIXER_TRACKS_READY;
4726 }
4727 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004728 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004729 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4730 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004731 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004732 } else {
4733 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004734 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004735
Eric Laurent81784c32012-11-19 14:55:58 -08004736 // clear effect chain input buffer if an active track underruns to avoid sending
4737 // previous audio buffer again to effects
4738 chain = getEffectChain_l(track->sessionId());
4739 if (chain != 0) {
4740 chain->clearInputBuffer();
4741 }
4742
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004743 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004744 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4745 track->isStopped() || track->isPaused()) {
4746 // We have consumed all the buffers of this track.
4747 // Remove it from the list of active tracks.
4748 // TODO: use actual buffer filling status instead of latency when available from
4749 // audio HAL
4750 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004751 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004752 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4753 if (track->isStopped()) {
4754 track->reset();
4755 }
4756 tracksToRemove->add(track);
4757 }
4758 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004759 // No buffers for this track. Give it a few chances to
4760 // fill a buffer, then remove it from active list.
4761 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004762 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004763 tracksToRemove->add(track);
4764 // indicate to client process that the track was disabled because of underrun;
4765 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004766 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004767 // If one track is not ready, mark the mixer also not ready if:
4768 // - the mixer was ready during previous round OR
4769 // - no other track is ready
4770 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4771 mixerStatus != MIXER_TRACKS_READY) {
4772 mixerStatus = MIXER_TRACKS_ENABLED;
4773 }
4774 }
4775 mAudioMixer->disable(name);
4776 }
4777
4778 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004779
4780 }
4781
4782 // Push the new FastMixer state if necessary
4783 bool pauseAudioWatchdog = false;
4784 if (didModify) {
4785 state->mFastTracksGen++;
4786 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4787 if (kUseFastMixer == FastMixer_Dynamic &&
4788 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4789 state->mCommand = FastMixerState::COLD_IDLE;
4790 state->mColdFutexAddr = &mFastMixerFutex;
4791 state->mColdGen++;
4792 mFastMixerFutex = 0;
4793 if (kUseFastMixer == FastMixer_Dynamic) {
4794 mNormalSink = mOutputSink;
4795 }
4796 // If we go into cold idle, need to wait for acknowledgement
4797 // so that fast mixer stops doing I/O.
4798 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4799 pauseAudioWatchdog = true;
4800 }
Eric Laurent81784c32012-11-19 14:55:58 -08004801 }
4802 if (sq != NULL) {
4803 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004804 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4805 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4806 // when bringing the output sink into standby.)
4807 //
4808 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4809 //
4810 // This occurs with BT suspend when we idle the FastMixer with
4811 // active tracks, which may be added or removed.
4812 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004813 }
4814#ifdef AUDIO_WATCHDOG
4815 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4816 mAudioWatchdog->pause();
4817 }
4818#endif
4819
4820 // Now perform the deferred reset on fast tracks that have stopped
4821 while (resetMask != 0) {
4822 size_t i = __builtin_ctz(resetMask);
4823 ALOG_ASSERT(i < count);
4824 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004825 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004826 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4827 track->reset();
4828 }
4829
Andy Hung80d03d22018-04-10 10:32:11 -07004830 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4831 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4832 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4833 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4834 // See also the implementation of destroyTrack_l().
4835 for (const auto &track : *tracksToRemove) {
4836 const int name = track->name();
4837 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4838 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4839 }
4840 }
4841
Eric Laurent81784c32012-11-19 14:55:58 -08004842 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004843 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004844
Eric Laurent97d547d2014-09-02 14:45:53 -07004845 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4846 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004847 }
4848
4849 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004850 // as long as there are effects we should clear the effects buffer, to avoid
4851 // passing a non-clean buffer to the effect chain
4852 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004853 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004854 // sink or mix buffer must be cleared if all tracks are connected to an
4855 // effect chain as in this case the mixer will not write to the sink or mix buffer
4856 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004857 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4858 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004859 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004860 if (mMixerBufferValid) {
4861 memset(mMixerBuffer, 0, mMixerBufferSize);
4862 // TODO: In testing, mSinkBuffer below need not be cleared because
4863 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4864 // after mixing.
4865 //
4866 // To enforce this guarantee:
4867 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4868 // (mixedTracks == 0 && fastTracks > 0))
4869 // must imply MIXER_TRACKS_READY.
4870 // Later, we may clear buffers regardless, and skip much of this logic.
4871 }
Andy Hung98ef9782014-03-04 14:46:50 -08004872 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004873 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004874 }
4875
4876 // if any fast tracks, then status is ready
4877 mMixerStatusIgnoringFastTracks = mixerStatus;
4878 if (fastTracks > 0) {
4879 mixerStatus = MIXER_TRACKS_READY;
4880 }
4881 return mixerStatus;
4882}
4883
Eric Laurentad7dd962016-09-22 12:38:37 -07004884// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004885uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004886{
4887 uint32_t trackCount = 0;
4888 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004889 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004890 trackCount++;
4891 }
4892 }
4893 return trackCount;
4894}
4895
Andy Hung1bc088a2018-02-09 15:57:31 -08004896// isTrackAllowed_l() must be called with ThreadBase::mLock held
4897bool AudioFlinger::MixerThread::isTrackAllowed_l(
4898 audio_channel_mask_t channelMask, audio_format_t format,
4899 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004900{
Andy Hung1bc088a2018-02-09 15:57:31 -08004901 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4902 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004903 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004904 // Check validity as we don't call AudioMixer::create() here.
4905 if (!AudioMixer::isValidFormat(format)) {
4906 ALOGW("%s: invalid format: %#x", __func__, format);
4907 return false;
4908 }
4909 if (!AudioMixer::isValidChannelMask(channelMask)) {
4910 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4911 return false;
4912 }
4913 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004914}
4915
Eric Laurent10351942014-05-08 18:49:52 -07004916// checkForNewParameter_l() must be called with ThreadBase::mLock held
4917bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4918 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004919{
Eric Laurent81784c32012-11-19 14:55:58 -08004920 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004921 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004922
Eric Laurent10351942014-05-08 18:49:52 -07004923 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004924
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004925 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004926
Eric Laurent10351942014-05-08 18:49:52 -07004927 AudioParameter param = AudioParameter(keyValuePair);
4928 int value;
4929 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4930 reconfig = true;
4931 }
4932 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004933 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004934 status = BAD_VALUE;
4935 } else {
4936 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004937 reconfig = true;
4938 }
Eric Laurent10351942014-05-08 18:49:52 -07004939 }
4940 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004941 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004942 status = BAD_VALUE;
4943 } else {
4944 // no need to save value, since it's constant
4945 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004946 }
Eric Laurent10351942014-05-08 18:49:52 -07004947 }
4948 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4949 // do not accept frame count changes if tracks are open as the track buffer
4950 // size depends on frame count and correct behavior would not be guaranteed
4951 // if frame count is changed after track creation
4952 if (!mTracks.isEmpty()) {
4953 status = INVALID_OPERATION;
4954 } else {
4955 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004956 }
Eric Laurent10351942014-05-08 18:49:52 -07004957 }
4958 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004959#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004960 // when changing the audio output device, call addBatteryData to notify
4961 // the change
4962 if (mOutDevice != value) {
4963 uint32_t params = 0;
4964 // check whether speaker is on
4965 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4966 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004967 }
Eric Laurent10351942014-05-08 18:49:52 -07004968
4969 audio_devices_t deviceWithoutSpeaker
4970 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4971 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004972 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004973 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4974 }
4975
4976 if (params != 0) {
4977 addBatteryData(params);
4978 }
4979 }
Eric Laurent81784c32012-11-19 14:55:58 -08004980#endif
4981
Eric Laurent10351942014-05-08 18:49:52 -07004982 // forward device change to effects that have requested to be
4983 // aware of attached audio device.
4984 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004985 a2dpDeviceChanged =
4986 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004987 mOutDevice = value;
4988 for (size_t i = 0; i < mEffectChains.size(); i++) {
4989 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004990 }
4991 }
Eric Laurent10351942014-05-08 18:49:52 -07004992 }
Eric Laurent81784c32012-11-19 14:55:58 -08004993
Eric Laurent10351942014-05-08 18:49:52 -07004994 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004995 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004996 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004997 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004998 mStandby = true;
4999 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005000 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005001 }
Eric Laurent10351942014-05-08 18:49:52 -07005002 if (status == NO_ERROR && reconfig) {
5003 readOutputParameters_l();
5004 delete mAudioMixer;
5005 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005006 for (const auto &track : mTracks) {
5007 const int name = track->name();
5008 status_t status = mAudioMixer->create(
5009 name,
5010 track->mChannelMask,
5011 track->mFormat,
5012 track->mSessionId);
5013 ALOGW_IF(status != NO_ERROR,
5014 "%s: cannot create track name"
5015 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5016 __func__,
5017 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005018 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005019 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005020 }
Eric Laurent81784c32012-11-19 14:55:58 -08005021 }
5022
Eric Laurent42537be2016-01-08 17:16:42 -08005023 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005024}
5025
5026
5027void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5028{
Eric Laurent81784c32012-11-19 14:55:58 -08005029 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005030 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005031 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005032 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08005033
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005034 if (hasFastMixer()) {
5035 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5036
5037 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5038 // while we are dumping it. It may be inconsistent, but it won't mutate!
5039 // This is a large object so we place it on the heap.
5040 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5041 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
5042 copy->dump(fd);
5043 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08005044
5045#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005046 // Similar for state queue
5047 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5048 observerCopy.dump(fd);
5049 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5050 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005051#endif
5052
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005053#ifdef AUDIO_WATCHDOG
5054 if (mAudioWatchdog != 0) {
5055 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5056 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5057 wdCopy.dump(fd);
5058 }
5059#endif
5060
5061 } else {
5062 dprintf(fd, " No FastMixer\n");
5063 }
5064
Glenn Kasten46909e72013-02-26 09:20:22 -08005065#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08005066 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07005067 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08005068#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005069
Eric Laurent81784c32012-11-19 14:55:58 -08005070}
5071
5072uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5073{
5074 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5075}
5076
5077uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5078{
5079 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5080}
5081
5082void AudioFlinger::MixerThread::cacheParameters_l()
5083{
5084 PlaybackThread::cacheParameters_l();
5085
5086 // FIXME: Relaxed timing because of a certain device that can't meet latency
5087 // Should be reduced to 2x after the vendor fixes the driver issue
5088 // increase threshold again due to low power audio mode. The way this warning
5089 // threshold is calculated and its usefulness should be reconsidered anyway.
5090 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5091}
5092
5093// ----------------------------------------------------------------------------
5094
5095AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005096 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5097 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005098{
5099}
5100
Eric Laurentbfb1b832013-01-07 09:53:42 -08005101AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5102 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005103 ThreadBase::type_t type, bool systemReady)
5104 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005105 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005106{
5107}
5108
Eric Laurent81784c32012-11-19 14:55:58 -08005109AudioFlinger::DirectOutputThread::~DirectOutputThread()
5110{
5111}
5112
Eric Laurent5850c4c2016-11-10 13:04:31 -08005113void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005114{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005115 float left, right;
5116
5117 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5118 left = right = 0;
5119 } else {
5120 float typeVolume = mStreamTypes[track->streamType()].volume;
5121 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005122 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005123
Andy Hung10cbff12017-02-21 17:30:14 -08005124 // Get volumeshaper scaling
5125 std::pair<float /* volume */, bool /* active */>
5126 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005127 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005128 v *= vh.first;
5129 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005130
Glenn Kastenc56f3422014-03-21 17:53:17 -07005131 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5132 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5133 if (left > GAIN_FLOAT_UNITY) {
5134 left = GAIN_FLOAT_UNITY;
5135 }
5136 left *= v;
5137 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5138 if (right > GAIN_FLOAT_UNITY) {
5139 right = GAIN_FLOAT_UNITY;
5140 }
5141 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005142 }
5143
5144 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005145 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005146 if (left != mLeftVolFloat || right != mRightVolFloat) {
5147 mLeftVolFloat = left;
5148 mRightVolFloat = right;
5149
Eric Laurentbfb1b832013-01-07 09:53:42 -08005150 // Delegate volume control to effect in track effect chain if needed
5151 // only one effect chain can be present on DirectOutputThread, so if
5152 // there is one, the track is connected to it
5153 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005154 // if effect chain exists, volume is handled by it.
5155 // Convert volumes from float to 8.24
5156 uint32_t vl = (uint32_t)(left * (1 << 24));
5157 uint32_t vr = (uint32_t)(right * (1 << 24));
5158 // Direct/Offload effect chains set output volume in setVolume_l().
5159 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5160 } else {
5161 // otherwise we directly set the volume.
5162 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005163 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005164 }
5165 }
5166}
5167
Phil Burk43b4dcc2015-06-09 16:53:44 -07005168void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5169{
5170 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005171 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005172
Eric Laurent0f0631e2015-07-06 18:01:25 -07005173 if (previousTrack != 0 && latestTrack != 0) {
5174 if (mType == DIRECT) {
5175 if (previousTrack.get() != latestTrack.get()) {
5176 mFlushPending = true;
5177 }
5178 } else /* mType == OFFLOAD */ {
5179 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5180 mFlushPending = true;
5181 }
5182 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005183 }
5184 PlaybackThread::onAddNewTrack_l();
5185}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005186
Eric Laurent81784c32012-11-19 14:55:58 -08005187AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5188 Vector< sp<Track> > *tracksToRemove
5189)
5190{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005191 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005192 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005193 bool doHwPause = false;
5194 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005195
5196 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005197 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005198 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005199 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005200 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005201 continue;
5202 }
5203
Eric Laurent5850c4c2016-11-10 13:04:31 -08005204 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005205#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005206 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005207#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005208 // Only consider last track started for volume and mixer state control.
5209 // In theory an older track could underrun and restart after the new one starts
5210 // but as we only care about the transition phase between two tracks on a
5211 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005212 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005213 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005214
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005215 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005216 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005217 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005218 doHwPause = true;
5219 mHwPaused = true;
5220 }
5221 tracksToRemove->add(track);
5222 } else if (track->isFlushPending()) {
5223 track->flushAck();
5224 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005225 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005226 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005227 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005228 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005229 if (last) {
5230 mLeftVolFloat = mRightVolFloat = -1.0;
5231 if (mHwPaused) {
5232 doHwResume = true;
5233 mHwPaused = false;
5234 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005235 }
5236 }
5237
Eric Laurent81784c32012-11-19 14:55:58 -08005238 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005239 // for all its buffers to be filled before processing it.
5240 // Allow draining the buffer in case the client
5241 // app does not call stop() and relies on underrun to stop:
5242 // hence the test on (track->mRetryCount > 1).
5243 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005244 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005245 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005246 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005247 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005248 minFrames = mNormalFrameCount;
5249 } else {
5250 minFrames = 1;
5251 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005252
Eric Laurentab5cdba2014-06-09 17:22:27 -07005253 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5254 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005255 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005256 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005257
5258 if (track->mFillingUpStatus == Track::FS_FILLED) {
5259 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005260 if (last) {
5261 // make sure processVolume_l() will apply new volume even if 0
5262 mLeftVolFloat = mRightVolFloat = -1.0;
5263 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005264 if (!mHwSupportsPause) {
5265 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005266 }
5267 }
5268
5269 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005270 processVolume_l(track, last);
5271 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005272 sp<Track> previousTrack = mPreviousTrack.promote();
5273 if (previousTrack != 0) {
5274 if (track != previousTrack.get()) {
5275 // Flush any data still being written from last track
5276 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005277 // Invalidate previous track to force a seek when resuming.
5278 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005279 }
5280 }
5281 mPreviousTrack = track;
5282
Eric Laurentd595b7c2013-04-03 17:27:56 -07005283 // reset retry count
5284 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005285 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005286 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005287 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005288 doHwResume = true;
5289 mHwPaused = false;
5290 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005291 }
Eric Laurent81784c32012-11-19 14:55:58 -08005292 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005293 // clear effect chain input buffer if the last active track started underruns
5294 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005295 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005296 mEffectChains[0]->clearInputBuffer();
5297 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005298 if (track->isStopping_1()) {
5299 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005300 if (last && mHwPaused) {
5301 doHwResume = true;
5302 mHwPaused = false;
5303 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005304 }
5305 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5306 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005307 // We have consumed all the buffers of this track.
5308 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005309 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005310 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005311 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5312 } else {
5313 audioHALFrames = 0;
5314 }
5315
Andy Hung818e7a32016-02-16 18:08:07 -08005316 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005317 if (mStandby || !last ||
5318 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005319 if (track->isStopping_2()) {
5320 track->mState = TrackBase::STOPPED;
5321 }
Eric Laurent81784c32012-11-19 14:55:58 -08005322 if (track->isStopped()) {
5323 track->reset();
5324 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005325 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005326 }
5327 } else {
5328 // No buffers for this track. Give it a few chances to
5329 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005330 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005331 if (--(track->mRetryCount) <= 0) {
5332 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005333 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005334 // indicate to client process that the track was disabled because of underrun;
5335 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005336 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005337 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005338 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5339 "minFrames = %u, mFormat = %#x",
5340 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005341 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005342 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005343 doHwPause = true;
5344 mHwPaused = true;
5345 }
Eric Laurent81784c32012-11-19 14:55:58 -08005346 }
5347 }
5348 }
5349 }
5350
Eric Laurentd1f69b02014-12-15 14:33:13 -08005351 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005352 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005353 for (size_t i = 0; i < mTracks.size(); i++) {
5354 if (mTracks[i]->isFlushPending()) {
5355 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005356 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005357 }
5358 }
5359 }
5360
5361 // make sure the pause/flush/resume sequence is executed in the right order.
5362 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5363 // before flush and then resume HW. This can happen in case of pause/flush/resume
5364 // if resume is received before pause is executed.
5365 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005366 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005367 status_t result = mOutput->stream->pause();
5368 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005369 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005370 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005371 flushHw_l();
5372 }
5373 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005374 status_t result = mOutput->stream->resume();
5375 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005376 }
Eric Laurent81784c32012-11-19 14:55:58 -08005377 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005378 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005379
5380 return mixerStatus;
5381}
5382
5383void AudioFlinger::DirectOutputThread::threadLoop_mix()
5384{
Eric Laurent81784c32012-11-19 14:55:58 -08005385 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005386 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005387 // output audio to hardware
5388 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005389 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005390 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005391 status_t status = mActiveTrack->getNextBuffer(&buffer);
5392 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005393 // no need to pad with 0 for compressed audio
5394 if (audio_has_proportional_frames(mFormat)) {
5395 memset(curBuf, 0, frameCount * mFrameSize);
5396 }
Eric Laurent81784c32012-11-19 14:55:58 -08005397 break;
5398 }
5399 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5400 frameCount -= buffer.frameCount;
5401 curBuf += buffer.frameCount * mFrameSize;
5402 mActiveTrack->releaseBuffer(&buffer);
5403 }
Andy Hung2098f272014-02-27 14:00:06 -08005404 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005405 mSleepTimeUs = 0;
5406 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005407 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005408}
5409
5410void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5411{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005412 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005413 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005414 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005415 return;
5416 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005417 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005418 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005419 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005420 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005421 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005422 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005423 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005424 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005425 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005426 }
5427}
5428
Eric Laurentd1f69b02014-12-15 14:33:13 -08005429void AudioFlinger::DirectOutputThread::threadLoop_exit()
5430{
5431 {
5432 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005433 for (size_t i = 0; i < mTracks.size(); i++) {
5434 if (mTracks[i]->isFlushPending()) {
5435 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005436 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005437 }
5438 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005439 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005440 flushHw_l();
5441 }
5442 }
5443 PlaybackThread::threadLoop_exit();
5444}
5445
5446// must be called with thread mutex locked
5447bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5448{
5449 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005450 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005451
vivek mehta9cd7ad12016-03-17 00:18:29 -07005452 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5453 return !mStandby;
5454 }
5455
Eric Laurentd1f69b02014-12-15 14:33:13 -08005456 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5457 // after a timeout and we will enter standby then.
5458 if (mTracks.size() > 0) {
5459 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005460 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5461 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005462 }
5463
Eric Laurent5cff4032015-05-26 13:49:58 -07005464 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005465}
5466
Eric Laurent10351942014-05-08 18:49:52 -07005467// checkForNewParameter_l() must be called with ThreadBase::mLock held
5468bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5469 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005470{
5471 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005472 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005473
Eric Laurent10351942014-05-08 18:49:52 -07005474 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005475
Eric Laurent10351942014-05-08 18:49:52 -07005476 AudioParameter param = AudioParameter(keyValuePair);
5477 int value;
5478 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5479 // forward device change to effects that have requested to be
5480 // aware of attached audio device.
5481 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005482 a2dpDeviceChanged =
5483 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005484 mOutDevice = value;
5485 for (size_t i = 0; i < mEffectChains.size(); i++) {
5486 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005487 }
5488 }
Eric Laurent81784c32012-11-19 14:55:58 -08005489 }
Eric Laurent10351942014-05-08 18:49:52 -07005490 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5491 // do not accept frame count changes if tracks are open as the track buffer
5492 // size depends on frame count and correct behavior would not be garantied
5493 // if frame count is changed after track creation
5494 if (!mTracks.isEmpty()) {
5495 status = INVALID_OPERATION;
5496 } else {
5497 reconfig = true;
5498 }
5499 }
5500 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005501 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005502 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005503 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005504 mStandby = true;
5505 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005506 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005507 }
5508 if (status == NO_ERROR && reconfig) {
5509 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005510 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005511 }
5512 }
5513
Eric Laurent42537be2016-01-08 17:16:42 -08005514 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005515}
5516
5517uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5518{
5519 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005520 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005521 time = PlaybackThread::activeSleepTimeUs();
5522 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005523 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005524 }
5525 return time;
5526}
5527
5528uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5529{
5530 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005531 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005532 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5533 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005534 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 }
5536 return time;
5537}
5538
5539uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5540{
5541 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005542 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005543 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5544 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005545 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005546 }
5547 return time;
5548}
5549
5550void AudioFlinger::DirectOutputThread::cacheParameters_l()
5551{
5552 PlaybackThread::cacheParameters_l();
5553
5554 // use shorter standby delay as on normal output to release
5555 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005556 // no delay on outputs with HW A/V sync
5557 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005558 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005559 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005560 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005561 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005562 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005563 }
Eric Laurent81784c32012-11-19 14:55:58 -08005564}
5565
Eric Laurente659ef42014-09-29 13:06:46 -07005566void AudioFlinger::DirectOutputThread::flushHw_l()
5567{
Phil Burk062e67a2015-02-11 13:40:50 -08005568 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005569 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005570 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005571}
5572
Andy Hung10cbff12017-02-21 17:30:14 -08005573int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5574 // If a VolumeShaper is active, we must wake up periodically to update volume.
5575 const int64_t NS_PER_MS = 1000000;
5576 return mVolumeShaperActive ?
5577 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5578}
5579
Eric Laurent81784c32012-11-19 14:55:58 -08005580// ----------------------------------------------------------------------------
5581
Eric Laurentbfb1b832013-01-07 09:53:42 -08005582AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005583 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005584 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005585 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005586 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005587 mDrainSequence(0),
5588 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005589{
5590}
5591
5592AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5593{
5594}
5595
5596void AudioFlinger::AsyncCallbackThread::onFirstRef()
5597{
5598 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5599}
5600
5601bool AudioFlinger::AsyncCallbackThread::threadLoop()
5602{
5603 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005604 uint32_t writeAckSequence;
5605 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005606 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005607
5608 {
5609 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005610 while (!((mWriteAckSequence & 1) ||
5611 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005612 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005613 exitPending())) {
5614 mWaitWorkCV.wait(mLock);
5615 }
5616
Eric Laurentbfb1b832013-01-07 09:53:42 -08005617 if (exitPending()) {
5618 break;
5619 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005620 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5621 mWriteAckSequence, mDrainSequence);
5622 writeAckSequence = mWriteAckSequence;
5623 mWriteAckSequence &= ~1;
5624 drainSequence = mDrainSequence;
5625 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005626 asyncError = mAsyncError;
5627 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005628 }
5629 {
Eric Laurent4de95592013-09-26 15:28:21 -07005630 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5631 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005632 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005633 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005634 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005635 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005636 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005637 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005638 if (asyncError) {
5639 playbackThread->onAsyncError();
5640 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005641 }
5642 }
5643 }
5644 return false;
5645}
5646
5647void AudioFlinger::AsyncCallbackThread::exit()
5648{
5649 ALOGV("AsyncCallbackThread::exit");
5650 Mutex::Autolock _l(mLock);
5651 requestExit();
5652 mWaitWorkCV.broadcast();
5653}
5654
Eric Laurent3b4529e2013-09-05 18:09:19 -07005655void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005656{
5657 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005658 // bit 0 is cleared
5659 mWriteAckSequence = sequence << 1;
5660}
5661
5662void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5663{
5664 Mutex::Autolock _l(mLock);
5665 // ignore unexpected callbacks
5666 if (mWriteAckSequence & 2) {
5667 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005668 mWaitWorkCV.signal();
5669 }
5670}
5671
Eric Laurent3b4529e2013-09-05 18:09:19 -07005672void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005673{
5674 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005675 // bit 0 is cleared
5676 mDrainSequence = sequence << 1;
5677}
5678
5679void AudioFlinger::AsyncCallbackThread::resetDraining()
5680{
5681 Mutex::Autolock _l(mLock);
5682 // ignore unexpected callbacks
5683 if (mDrainSequence & 2) {
5684 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005685 mWaitWorkCV.signal();
5686 }
5687}
5688
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005689void AudioFlinger::AsyncCallbackThread::setAsyncError()
5690{
5691 Mutex::Autolock _l(mLock);
5692 mAsyncError = true;
5693 mWaitWorkCV.signal();
5694}
5695
Eric Laurentbfb1b832013-01-07 09:53:42 -08005696
5697// ----------------------------------------------------------------------------
5698AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005699 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5700 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005701 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5702 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005704 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005705 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005706 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005707}
5708
Eric Laurentbfb1b832013-01-07 09:53:42 -08005709void AudioFlinger::OffloadThread::threadLoop_exit()
5710{
5711 if (mFlushPending || mHwPaused) {
5712 // If a flush is pending or track was paused, just discard buffered data
5713 flushHw_l();
5714 } else {
5715 mMixerStatus = MIXER_DRAIN_ALL;
5716 threadLoop_drain();
5717 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005718 if (mUseAsyncWrite) {
5719 ALOG_ASSERT(mCallbackThread != 0);
5720 mCallbackThread->exit();
5721 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005722 PlaybackThread::threadLoop_exit();
5723}
5724
5725AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5726 Vector< sp<Track> > *tracksToRemove
5727)
5728{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005729 size_t count = mActiveTracks.size();
5730
5731 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005732 bool doHwPause = false;
5733 bool doHwResume = false;
5734
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005735 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005736
Eric Laurentbfb1b832013-01-07 09:53:42 -08005737 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005738 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005739 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005740#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005741 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005742#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005743 // Only consider last track started for volume and mixer state control.
5744 // In theory an older track could underrun and restart after the new one starts
5745 // but as we only care about the transition phase between two tracks on a
5746 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005747 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005748 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005749
Haynes Mathew George7844f672014-01-15 12:32:55 -08005750 if (track->isInvalid()) {
5751 ALOGW("An invalidated track shouldn't be in active list");
5752 tracksToRemove->add(track);
5753 continue;
5754 }
5755
5756 if (track->mState == TrackBase::IDLE) {
5757 ALOGW("An idle track shouldn't be in active list");
5758 continue;
5759 }
5760
Eric Laurentbfb1b832013-01-07 09:53:42 -08005761 if (track->isPausing()) {
5762 track->setPaused();
5763 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005764 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005765 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005766 mHwPaused = true;
5767 }
5768 // If we were part way through writing the mixbuffer to
5769 // the HAL we must save this until we resume
5770 // BUG - this will be wrong if a different track is made active,
5771 // in that case we want to discard the pending data in the
5772 // mixbuffer and tell the client to present it again when the
5773 // track is resumed
5774 mPausedWriteLength = mCurrentWriteLength;
5775 mPausedBytesRemaining = mBytesRemaining;
5776 mBytesRemaining = 0; // stop writing
5777 }
5778 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005779 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005780 if (track->isStopping_1()) {
5781 track->mRetryCount = kMaxTrackStopRetriesOffload;
5782 } else {
5783 track->mRetryCount = kMaxTrackRetriesOffload;
5784 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005785 track->flushAck();
5786 if (last) {
5787 mFlushPending = true;
5788 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005789 } else if (track->isResumePending()){
5790 track->resumeAck();
5791 if (last) {
5792 if (mPausedBytesRemaining) {
5793 // Need to continue write that was interrupted
5794 mCurrentWriteLength = mPausedWriteLength;
5795 mBytesRemaining = mPausedBytesRemaining;
5796 mPausedBytesRemaining = 0;
5797 }
5798 if (mHwPaused) {
5799 doHwResume = true;
5800 mHwPaused = false;
5801 // threadLoop_mix() will handle the case that we need to
5802 // resume an interrupted write
5803 }
5804 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005805 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005806
Eric Laurent3df841a2016-07-15 15:15:40 -07005807 mLeftVolFloat = mRightVolFloat = -1.0;
5808
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005809 // Do not handle new data in this iteration even if track->framesReady()
5810 mixerStatus = MIXER_TRACKS_ENABLED;
5811 }
5812 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005813 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005814 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005815 if (track->mFillingUpStatus == Track::FS_FILLED) {
5816 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005817 if (last) {
5818 // make sure processVolume_l() will apply new volume even if 0
5819 mLeftVolFloat = mRightVolFloat = -1.0;
5820 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005821 }
5822
5823 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005824 sp<Track> previousTrack = mPreviousTrack.promote();
5825 if (previousTrack != 0) {
5826 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005827 // Flush any data still being written from last track
5828 mBytesRemaining = 0;
5829 if (mPausedBytesRemaining) {
5830 // Last track was paused so we also need to flush saved
5831 // mixbuffer state and invalidate track so that it will
5832 // re-submit that unwritten data when it is next resumed
5833 mPausedBytesRemaining = 0;
5834 // Invalidate is a bit drastic - would be more efficient
5835 // to have a flag to tell client that some of the
5836 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005837 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005838 }
5839 // flush data already sent to the DSP if changing audio session as audio
5840 // comes from a different source. Also invalidate previous track to force a
5841 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005842 if (previousTrack->sessionId() != track->sessionId()) {
5843 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005844 }
5845 }
5846 }
5847 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005848 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005849 if (track->isStopping_1()) {
5850 track->mRetryCount = kMaxTrackStopRetriesOffload;
5851 } else {
5852 track->mRetryCount = kMaxTrackRetriesOffload;
5853 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005854 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005855 mixerStatus = MIXER_TRACKS_READY;
5856 }
5857 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005858 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005859 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005860 if (--(track->mRetryCount) <= 0) {
5861 // Hardware buffer can hold a large amount of audio so we must
5862 // wait for all current track's data to drain before we say
5863 // that the track is stopped.
5864 if (mBytesRemaining == 0) {
5865 // Only start draining when all data in mixbuffer
5866 // has been written
5867 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5868 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5869 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5870 if (last && !mStandby) {
5871 // do not modify drain sequence if we are already draining. This happens
5872 // when resuming from pause after drain.
5873 if ((mDrainSequence & 1) == 0) {
5874 mSleepTimeUs = 0;
5875 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5876 mixerStatus = MIXER_DRAIN_TRACK;
5877 mDrainSequence += 2;
5878 }
5879 if (mHwPaused) {
5880 // It is possible to move from PAUSED to STOPPING_1 without
5881 // a resume so we must ensure hardware is running
5882 doHwResume = true;
5883 mHwPaused = false;
5884 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005885 }
5886 }
Eric Laurente93cc032016-05-05 10:15:10 -07005887 } else if (last) {
5888 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5889 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005890 }
5891 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005892 // Drain has completed or we are in standby, signal presentation complete
5893 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005894 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005895 uint32_t latency = 0;
5896 status_t result = mOutput->stream->getLatency(&latency);
5897 ALOGE_IF(result != OK,
5898 "Error when retrieving output stream latency: %d", result);
5899 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005900 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005901 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005902 track->presentationComplete(framesWritten, audioHALFrames);
5903 track->reset();
5904 tracksToRemove->add(track);
5905 }
5906 } else {
5907 // No buffers for this track. Give it a few chances to
5908 // fill a buffer, then remove it from active list.
5909 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005910 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005911 uint64_t position = 0;
5912 struct timespec unused;
5913 // The running check restarts the retry counter at least once.
5914 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5915 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5916 running = true;
5917 mOffloadUnderrunPosition = position;
5918 }
5919 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005920 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5921 (long long)position, (long long)mOffloadUnderrunPosition);
5922 }
5923 if (running) { // still running, give us more time.
5924 track->mRetryCount = kMaxTrackRetriesOffload;
5925 } else {
5926 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5927 track->name());
5928 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005929 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005930 // it will then automatically call start() when data is available
5931 track->disable();
5932 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005933 } else if (last){
5934 mixerStatus = MIXER_TRACKS_ENABLED;
5935 }
5936 }
5937 }
5938 // compute volume for this track
5939 processVolume_l(track, last);
5940 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005941
Eric Laurentea0fade2013-10-04 16:23:48 -07005942 // make sure the pause/flush/resume sequence is executed in the right order.
5943 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5944 // before flush and then resume HW. This can happen in case of pause/flush/resume
5945 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005946 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005947 status_t result = mOutput->stream->pause();
5948 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005949 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005950 if (mFlushPending) {
5951 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005952 }
Eric Laurentfd477972013-10-25 18:10:40 -07005953 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005954 status_t result = mOutput->stream->resume();
5955 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005956 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005957
Eric Laurentbfb1b832013-01-07 09:53:42 -08005958 // remove all the tracks that need to be...
5959 removeTracks_l(*tracksToRemove);
5960
5961 return mixerStatus;
5962}
5963
Eric Laurentbfb1b832013-01-07 09:53:42 -08005964// must be called with thread mutex locked
5965bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5966{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005967 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5968 mWriteAckSequence, mDrainSequence);
5969 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005970 return true;
5971 }
5972 return false;
5973}
5974
Eric Laurentbfb1b832013-01-07 09:53:42 -08005975bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5976{
5977 Mutex::Autolock _l(mLock);
5978 return waitingAsyncCallback_l();
5979}
5980
5981void AudioFlinger::OffloadThread::flushHw_l()
5982{
Eric Laurente659ef42014-09-29 13:06:46 -07005983 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005984 // Flush anything still waiting in the mixbuffer
5985 mCurrentWriteLength = 0;
5986 mBytesRemaining = 0;
5987 mPausedWriteLength = 0;
5988 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005989 // reset bytes written count to reflect that DSP buffers are empty after flush.
5990 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005991 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005992
Eric Laurentbfb1b832013-01-07 09:53:42 -08005993 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005994 // discard any pending drain or write ack by incrementing sequence
5995 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5996 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005997 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005998 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5999 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006000 }
6001}
6002
Haynes Mathew George05317d22016-05-03 16:34:26 -07006003void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6004{
6005 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006006 if (PlaybackThread::invalidateTracks_l(streamType)) {
6007 mFlushPending = true;
6008 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006009}
6010
Eric Laurentbfb1b832013-01-07 09:53:42 -08006011// ----------------------------------------------------------------------------
6012
Eric Laurent81784c32012-11-19 14:55:58 -08006013AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006014 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006015 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006016 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006017 mWaitTimeMs(UINT_MAX)
6018{
6019 addOutputTrack(mainThread);
6020}
6021
6022AudioFlinger::DuplicatingThread::~DuplicatingThread()
6023{
6024 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6025 mOutputTracks[i]->destroy();
6026 }
6027}
6028
6029void AudioFlinger::DuplicatingThread::threadLoop_mix()
6030{
6031 // mix buffers...
6032 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006033 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006034 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006035 if (mMixerBufferValid) {
6036 memset(mMixerBuffer, 0, mMixerBufferSize);
6037 } else {
6038 memset(mSinkBuffer, 0, mSinkBufferSize);
6039 }
Eric Laurent81784c32012-11-19 14:55:58 -08006040 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006041 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006042 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006043 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006044 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006045}
6046
6047void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6048{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006049 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006050 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006051 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006052 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006053 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006054 }
6055 } else if (mBytesWritten != 0) {
6056 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6057 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006058 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006059 } else {
6060 // flush remaining overflow buffers in output tracks
6061 writeFrames = 0;
6062 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006063 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006064 }
6065}
6066
Eric Laurentbfb1b832013-01-07 09:53:42 -08006067ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006068{
6069 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08006070 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08006071 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006072 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006073 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006074}
6075
6076void AudioFlinger::DuplicatingThread::threadLoop_standby()
6077{
6078 // DuplicatingThread implements standby by stopping all tracks
6079 for (size_t i = 0; i < outputTracks.size(); i++) {
6080 outputTracks[i]->stop();
6081 }
6082}
6083
Andy Hung1bc088a2018-02-09 15:57:31 -08006084void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6085{
6086 MixerThread::dumpInternals(fd, args);
6087
6088 std::stringstream ss;
6089 const size_t numTracks = mOutputTracks.size();
6090 ss << " " << numTracks << " OutputTracks";
6091 if (numTracks > 0) {
6092 ss << ":";
6093 for (const auto &track : mOutputTracks) {
6094 const sp<ThreadBase> thread = track->thread().promote();
6095 ss << " (" << track->name() << " : ";
6096 if (thread.get() != nullptr) {
6097 ss << thread.get() << ", " << thread->id();
6098 } else {
6099 ss << "null";
6100 }
6101 ss << ")";
6102 }
6103 }
6104 ss << "\n";
6105 std::string result = ss.str();
6106 write(fd, result.c_str(), result.size());
6107}
6108
Eric Laurent81784c32012-11-19 14:55:58 -08006109void AudioFlinger::DuplicatingThread::saveOutputTracks()
6110{
6111 outputTracks = mOutputTracks;
6112}
6113
6114void AudioFlinger::DuplicatingThread::clearOutputTracks()
6115{
6116 outputTracks.clear();
6117}
6118
6119void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6120{
6121 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006122 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6123 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6124 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6125 const size_t frameCount =
6126 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6127 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6128 // from different OutputTracks and their associated MixerThreads (e.g. one may
6129 // nearly empty and the other may be dropping data).
6130
6131 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006132 this,
6133 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006134 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006135 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006136 frameCount,
6137 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006138 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6139 if (status != NO_ERROR) {
6140 ALOGE("addOutputTrack() initCheck failed %d", status);
6141 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006142 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006143 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6144 mOutputTracks.add(outputTrack);
6145 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6146 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006147}
6148
6149void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6150{
6151 Mutex::Autolock _l(mLock);
6152 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6153 if (mOutputTracks[i]->thread() == thread) {
6154 mOutputTracks[i]->destroy();
6155 mOutputTracks.removeAt(i);
6156 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006157 if (thread->getOutput() == mOutput) {
6158 mOutput = NULL;
6159 }
Eric Laurent81784c32012-11-19 14:55:58 -08006160 return;
6161 }
6162 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006163 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006164}
6165
6166// caller must hold mLock
6167void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6168{
6169 mWaitTimeMs = UINT_MAX;
6170 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6171 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6172 if (strong != 0) {
6173 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6174 if (waitTimeMs < mWaitTimeMs) {
6175 mWaitTimeMs = waitTimeMs;
6176 }
6177 }
6178 }
6179}
6180
6181
6182bool AudioFlinger::DuplicatingThread::outputsReady(
6183 const SortedVector< sp<OutputTrack> > &outputTracks)
6184{
6185 for (size_t i = 0; i < outputTracks.size(); i++) {
6186 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6187 if (thread == 0) {
6188 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6189 outputTracks[i].get());
6190 return false;
6191 }
6192 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6193 // see note at standby() declaration
6194 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6195 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6196 thread.get());
6197 return false;
6198 }
6199 }
6200 return true;
6201}
6202
Kevin Rocard12381092018-04-11 09:19:59 -07006203void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6204 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006205{
Kevin Rocard12381092018-04-11 09:19:59 -07006206 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6207 outputTrack->setMetadatas(metadata.tracks);
6208 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006209}
6210
Eric Laurent81784c32012-11-19 14:55:58 -08006211uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6212{
6213 return (mWaitTimeMs * 1000) / 2;
6214}
6215
6216void AudioFlinger::DuplicatingThread::cacheParameters_l()
6217{
6218 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6219 updateWaitTime_l();
6220
6221 MixerThread::cacheParameters_l();
6222}
6223
Eric Laurent6acd1d42017-01-04 14:23:29 -08006224
Eric Laurent81784c32012-11-19 14:55:58 -08006225// ----------------------------------------------------------------------------
6226// Record
6227// ----------------------------------------------------------------------------
6228
6229AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6230 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006231 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006232 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006233 audio_devices_t inDevice,
6234 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006235#ifdef TEE_SINK
6236 , const sp<NBAIO_Sink>& teeSink
6237#endif
6238 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006239 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006240 mInput(input),
6241 mActiveTracks(&this->mLocalLog),
6242 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006243 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006244 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006245#ifdef TEE_SINK
6246 , mTeeSink(teeSink)
6247#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006248 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6249 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006250 // mFastCapture below
6251 , mFastCaptureFutex(0)
6252 // mInputSource
6253 // mPipeSink
6254 // mPipeSource
6255 , mPipeFramesP2(0)
6256 // mPipeMemory
6257 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006258 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006259 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006260{
Glenn Kastend7dca052015-03-05 16:05:54 -08006261 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6262 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006263
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006264 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006265
6266 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006267 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006268 size_t numCounterOffers = 0;
6269 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006270#if !LOG_NDEBUG
6271 ssize_t index =
6272#else
6273 (void)
6274#endif
6275 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006276 ALOG_ASSERT(index == 0);
6277
6278 // initialize fast capture depending on configuration
6279 bool initFastCapture;
6280 switch (kUseFastCapture) {
6281 case FastCapture_Never:
6282 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006283 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006284 break;
6285 case FastCapture_Always:
6286 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006287 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006288 break;
6289 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006290 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006291 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6292 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6293 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006294 break;
6295 // case FastCapture_Dynamic:
6296 }
6297
6298 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006299 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006300 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006301 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6302 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006303 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006304 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006305 const sp<MemoryDealer> roHeap(readOnlyHeap());
6306 sp<IMemory> pipeMemory;
6307 if ((roHeap == 0) ||
6308 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006309 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6310 ALOGE("not enough memory for pipe buffer size=%zu; "
6311 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6312 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6313 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006314 goto failed;
6315 }
6316 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6317 memset(pipeBuffer, 0, pipeSize);
6318 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6319 const NBAIO_Format offers[1] = {format};
6320 size_t numCounterOffers = 0;
6321 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6322 ALOG_ASSERT(index == 0);
6323 mPipeSink = pipe;
6324 PipeReader *pipeReader = new PipeReader(*pipe);
6325 numCounterOffers = 0;
6326 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6327 ALOG_ASSERT(index == 0);
6328 mPipeSource = pipeReader;
6329 mPipeFramesP2 = pipeFramesP2;
6330 mPipeMemory = pipeMemory;
6331
6332 // create fast capture
6333 mFastCapture = new FastCapture();
6334 FastCaptureStateQueue *sq = mFastCapture->sq();
6335#ifdef STATE_QUEUE_DUMP
6336 // FIXME
6337#endif
6338 FastCaptureState *state = sq->begin();
6339 state->mCblk = NULL;
6340 state->mInputSource = mInputSource.get();
6341 state->mInputSourceGen++;
6342 state->mPipeSink = pipe;
6343 state->mPipeSinkGen++;
6344 state->mFrameCount = mFrameCount;
6345 state->mCommand = FastCaptureState::COLD_IDLE;
6346 // already done in constructor initialization list
6347 //mFastCaptureFutex = 0;
6348 state->mColdFutexAddr = &mFastCaptureFutex;
6349 state->mColdGen++;
6350 state->mDumpState = &mFastCaptureDumpState;
6351#ifdef TEE_SINK
6352 // FIXME
6353#endif
6354 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6355 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6356 sq->end();
6357 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6358
6359 // start the fast capture
6360 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6361 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006362 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006363 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006364#ifdef AUDIO_WATCHDOG
6365 // FIXME
6366#endif
6367
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006368 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006369 }
6370failed: ;
6371
6372 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006373}
6374
Eric Laurent81784c32012-11-19 14:55:58 -08006375AudioFlinger::RecordThread::~RecordThread()
6376{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006377 if (mFastCapture != 0) {
6378 FastCaptureStateQueue *sq = mFastCapture->sq();
6379 FastCaptureState *state = sq->begin();
6380 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6381 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6382 if (old == -1) {
6383 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6384 }
6385 }
6386 state->mCommand = FastCaptureState::EXIT;
6387 sq->end();
6388 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6389 mFastCapture->join();
6390 mFastCapture.clear();
6391 }
6392 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006393 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006394 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006395}
6396
6397void AudioFlinger::RecordThread::onFirstRef()
6398{
Glenn Kastend7dca052015-03-05 16:05:54 -08006399 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006400}
6401
Eric Laurent555530a2017-02-07 18:17:24 -08006402void AudioFlinger::RecordThread::preExit()
6403{
6404 ALOGV(" preExit()");
6405 Mutex::Autolock _l(mLock);
6406 for (size_t i = 0; i < mTracks.size(); i++) {
6407 sp<RecordTrack> track = mTracks[i];
6408 track->invalidate();
6409 }
6410 mActiveTracks.clear();
6411 mStartStopCond.broadcast();
6412}
6413
Eric Laurent81784c32012-11-19 14:55:58 -08006414bool AudioFlinger::RecordThread::threadLoop()
6415{
Eric Laurent81784c32012-11-19 14:55:58 -08006416 nsecs_t lastWarning = 0;
6417
6418 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006419
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006420reacquire_wakelock:
6421 sp<RecordTrack> activeTrack;
6422 {
6423 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006424 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006425 }
6426
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006427 // used to request a deferred sleep, to be executed later while mutex is unlocked
6428 uint32_t sleepUs = 0;
6429
6430 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006431 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006432 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006433
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006434 // activeTracks accumulates a copy of a subset of mActiveTracks
6435 Vector< sp<RecordTrack> > activeTracks;
6436
Glenn Kasten735f45f2014-08-18 15:51:59 -07006437 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006438 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006439
Glenn Kasten735f45f2014-08-18 15:51:59 -07006440 // reference to a fast track which is about to be removed
6441 sp<RecordTrack> fastTrackToRemove;
6442
Eric Laurent81784c32012-11-19 14:55:58 -08006443 { // scope for mLock
6444 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006445
Eric Laurent021cf962014-05-13 10:18:14 -07006446 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006447
Eric Laurent000a4192014-01-29 15:17:32 -08006448 // check exitPending here because checkForNewParameters_l() and
6449 // checkForNewParameters_l() can temporarily release mLock
6450 if (exitPending()) {
6451 break;
6452 }
6453
Eric Laurent5c25d562016-07-13 17:17:45 -07006454 // sleep with mutex unlocked
6455 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006456 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006457 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6458 ATRACE_END();
6459 sleepUs = 0;
6460 continue;
6461 }
6462
Glenn Kasten2b806402013-11-20 16:37:38 -08006463 // if no active track(s), then standby and release wakelock
6464 size_t size = mActiveTracks.size();
6465 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006466 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006467 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006468 releaseWakeLock_l();
6469 ALOGV("RecordThread: loop stopping");
6470 // go to sleep
6471 mWaitWorkCV.wait(mLock);
6472 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006473 goto reacquire_wakelock;
6474 }
6475
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006476 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006477 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006478 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006479
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006480 activeTrack = mActiveTracks[i];
6481 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006482 if (activeTrack->isFastTrack()) {
6483 ALOG_ASSERT(fastTrackToRemove == 0);
6484 fastTrackToRemove = activeTrack;
6485 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006486 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006487 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006488 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006489 continue;
6490 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006491
6492 TrackBase::track_state activeTrackState = activeTrack->mState;
6493 switch (activeTrackState) {
6494
6495 case TrackBase::PAUSING:
6496 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006497 doBroadcast = true;
6498 size--;
6499 continue;
6500
6501 case TrackBase::STARTING_1:
6502 sleepUs = 10000;
6503 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006504 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006505 continue;
6506
6507 case TrackBase::STARTING_2:
6508 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006509 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006510 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006511 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006512 break;
6513
6514 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006515 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006516 break;
6517
6518 case TrackBase::IDLE:
6519 i++;
6520 continue;
6521
6522 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006523 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006524 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006525
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006526 activeTracks.add(activeTrack);
6527 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006528
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006529 if (activeTrack->isFastTrack()) {
6530 ALOG_ASSERT(!mFastTrackAvail);
6531 ALOG_ASSERT(fastTrack == 0);
6532 fastTrack = activeTrack;
6533 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006534 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006535
Andy Hungdae27702016-10-31 14:01:16 -07006536 mActiveTracks.updatePowerState(this);
6537
Kevin Rocard069c2712018-03-29 19:09:14 -07006538 updateMetadata_l();
6539
Eric Laurent5c25d562016-07-13 17:17:45 -07006540 if (allStopped) {
6541 standbyIfNotAlreadyInStandby();
6542 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006543 if (doBroadcast) {
6544 mStartStopCond.broadcast();
6545 }
6546
6547 // sleep if there are no active tracks to process
6548 if (activeTracks.size() == 0) {
6549 if (sleepUs == 0) {
6550 sleepUs = kRecordThreadSleepUs;
6551 }
6552 continue;
6553 }
6554 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006555
Eric Laurent81784c32012-11-19 14:55:58 -08006556 lockEffectChains_l(effectChains);
6557 }
6558
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006559 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006560
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006561 size_t size = effectChains.size();
6562 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006563 // thread mutex is not locked, but effect chain is locked
6564 effectChains[i]->process_l();
6565 }
6566
Glenn Kasten735f45f2014-08-18 15:51:59 -07006567 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006568 if (mFastCapture != 0) {
6569 FastCaptureStateQueue *sq = mFastCapture->sq();
6570 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006571 bool didModify = false;
6572 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006573 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6574 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6575 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6576 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6577 if (old == -1) {
6578 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6579 }
6580 }
6581 state->mCommand = FastCaptureState::READ_WRITE;
6582#if 0 // FIXME
6583 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006584 FastThreadDumpState::kSamplingNforLowRamDevice :
6585 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006586#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006587 didModify = true;
6588 }
6589 audio_track_cblk_t *cblkOld = state->mCblk;
6590 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6591 if (cblkNew != cblkOld) {
6592 state->mCblk = cblkNew;
6593 // block until acked if removing a fast track
6594 if (cblkOld != NULL) {
6595 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6596 }
6597 didModify = true;
6598 }
6599 sq->end(didModify);
6600 if (didModify) {
6601 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006602#if 0
6603 if (kUseFastCapture == FastCapture_Dynamic) {
6604 mNormalSource = mPipeSource;
6605 }
6606#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006607 }
6608 }
6609
Glenn Kasten735f45f2014-08-18 15:51:59 -07006610 // now run the fast track destructor with thread mutex unlocked
6611 fastTrackToRemove.clear();
6612
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006613 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6614 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6615 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6616 // If destination is non-contiguous, first read past the nominal end of buffer, then
6617 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006618
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006619 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006620 ssize_t framesRead;
6621
6622 // If an NBAIO source is present, use it to read the normal capture's data
6623 if (mPipeSource != 0) {
6624 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006625 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006626
6627 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6628 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6629 // we immediately retry the read() to get data and prevent another overflow.
6630 for (int retries = 0; retries <= 2; ++retries) {
6631 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6632 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6633 framesToRead);
6634 if (framesRead != OVERRUN) break;
6635 }
6636
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006637 const ssize_t availableToRead = mPipeSource->availableToRead();
6638 if (availableToRead >= 0) {
6639 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6640 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6641 "more frames to read than fifo size, %zd > %zu",
6642 availableToRead, mPipeFramesP2);
6643 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6644 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6645 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6646 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006647 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6648 }
6649 if (framesRead < 0) {
6650 status_t status = (status_t) framesRead;
6651 switch (status) {
6652 case OVERRUN:
6653 ALOGW("overrun on read from pipe");
6654 framesRead = 0;
6655 break;
6656 case NEGOTIATE:
6657 ALOGE("re-negotiation is needed");
6658 framesRead = -1; // Will cause an attempt to recover.
6659 break;
6660 default:
6661 ALOGE("unknown error %d on read from pipe", status);
6662 break;
6663 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006664 }
6665 // otherwise use the HAL / AudioStreamIn directly
6666 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006667 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006668 size_t bytesRead;
6669 status_t result = mInput->stream->read(
6670 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006671 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006672 if (result < 0) {
6673 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006674 } else {
6675 framesRead = bytesRead / mFrameSize;
6676 }
6677 }
6678
Andy Hung3f0c9022016-01-15 17:49:46 -08006679 // Update server timestamp with server stats
6680 // systemTime() is optional if the hardware supports timestamps.
6681 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6682 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6683
6684 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006685 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006686 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006687 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006688 if (ret == NO_ERROR) {
6689 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6690 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6691 // Note: In general record buffers should tend to be empty in
6692 // a properly running pipeline.
6693 //
6694 // Also, it is not advantageous to call get_presentation_position during the read
6695 // as the read obtains a lock, preventing the timestamp call from executing.
6696 }
6697 }
6698 // Use this to track timestamp information
6699 // ALOGD("%s", mTimestamp.toString().c_str());
6700
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006701 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006702 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006703 // Force input into standby so that it tries to recover at next read attempt
6704 inputStandBy();
6705 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006706 }
6707 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006708 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006709 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006710 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006711
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006712 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006713 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006714 }
6715 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006716 {
6717 size_t part1 = mRsmpInFramesP2 - rear;
6718 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006719 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006720 (framesRead - part1) * mFrameSize);
6721 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006722 }
6723 rear = mRsmpInRear += framesRead;
6724
6725 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006726
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006727 // loop over each active track
6728 for (size_t i = 0; i < size; i++) {
6729 activeTrack = activeTracks[i];
6730
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006731 // skip fast tracks, as those are handled directly by FastCapture
6732 if (activeTrack->isFastTrack()) {
6733 continue;
6734 }
6735
Andy Hung73c02e42015-03-29 01:13:58 -07006736 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006737 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6738
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006739 enum {
6740 OVERRUN_UNKNOWN,
6741 OVERRUN_TRUE,
6742 OVERRUN_FALSE
6743 } overrun = OVERRUN_UNKNOWN;
6744
6745 // loop over getNextBuffer to handle circular sink
6746 for (;;) {
6747
6748 activeTrack->mSink.frameCount = ~0;
6749 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6750 size_t framesOut = activeTrack->mSink.frameCount;
6751 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6752
Andy Hung73c02e42015-03-29 01:13:58 -07006753 // check available frames and handle overrun conditions
6754 // if the record track isn't draining fast enough.
6755 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006756 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006757 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6758 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006759 overrun = OVERRUN_TRUE;
6760 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006761 if (framesOut == 0 || framesIn == 0) {
6762 break;
6763 }
6764
Andy Hung6770c6f2015-04-07 13:43:36 -07006765 // Don't allow framesOut to be larger than what is possible with resampling
6766 // from framesIn.
6767 // This isn't strictly necessary but helps limit buffer resizing in
6768 // RecordBufferConverter. TODO: remove when no longer needed.
6769 framesOut = min(framesOut,
6770 destinationFramesPossible(
6771 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006772 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6773 framesOut = activeTrack->mRecordBufferConverter->convert(
6774 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006775
6776 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6777 overrun = OVERRUN_FALSE;
6778 }
6779
6780 if (activeTrack->mFramesToDrop == 0) {
6781 if (framesOut > 0) {
6782 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006783 // Sanitize before releasing if the track has no access to the source data
6784 // An idle UID receives silence from non virtual devices until active
6785 if (activeTrack->isSilenced()) {
6786 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6787 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006788 activeTrack->releaseBuffer(&activeTrack->mSink);
6789 }
6790 } else {
6791 // FIXME could do a partial drop of framesOut
6792 if (activeTrack->mFramesToDrop > 0) {
6793 activeTrack->mFramesToDrop -= framesOut;
6794 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006795 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006796 }
6797 } else {
6798 activeTrack->mFramesToDrop += framesOut;
6799 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6800 activeTrack->mSyncStartEvent->isCancelled()) {
6801 ALOGW("Synced record %s, session %d, trigger session %d",
6802 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6803 activeTrack->sessionId(),
6804 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006805 activeTrack->mSyncStartEvent->triggerSession() :
6806 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006807 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006808 }
6809 }
6810 }
6811
6812 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006813 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006814 }
6815 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006816
6817 switch (overrun) {
6818 case OVERRUN_TRUE:
6819 // client isn't retrieving buffers fast enough
6820 if (!activeTrack->setOverflow()) {
6821 nsecs_t now = systemTime();
6822 // FIXME should lastWarning per track?
6823 if ((now - lastWarning) > kWarningThrottleNs) {
6824 ALOGW("RecordThread: buffer overflow");
6825 lastWarning = now;
6826 }
6827 }
6828 break;
6829 case OVERRUN_FALSE:
6830 activeTrack->clearOverflow();
6831 break;
6832 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006833 break;
6834 }
6835
Andy Hung3f0c9022016-01-15 17:49:46 -08006836 // update frame information and push timestamp out
6837 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006838 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006839 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6840 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006841 }
6842
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006843unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006844 // enable changes in effect chain
6845 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006846 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006847 }
6848
Glenn Kasten93e471f2013-08-19 08:40:07 -07006849 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006850
6851 {
6852 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006853 for (size_t i = 0; i < mTracks.size(); i++) {
6854 sp<RecordTrack> track = mTracks[i];
6855 track->invalidate();
6856 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006857 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006858 mStartStopCond.broadcast();
6859 }
6860
6861 releaseWakeLock();
6862
6863 ALOGV("RecordThread %p exiting", this);
6864 return false;
6865}
6866
Glenn Kasten93e471f2013-08-19 08:40:07 -07006867void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006868{
6869 if (!mStandby) {
6870 inputStandBy();
6871 mStandby = true;
6872 }
6873}
6874
6875void AudioFlinger::RecordThread::inputStandBy()
6876{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006877 // Idle the fast capture if it's currently running
6878 if (mFastCapture != 0) {
6879 FastCaptureStateQueue *sq = mFastCapture->sq();
6880 FastCaptureState *state = sq->begin();
6881 if (!(state->mCommand & FastCaptureState::IDLE)) {
6882 state->mCommand = FastCaptureState::COLD_IDLE;
6883 state->mColdFutexAddr = &mFastCaptureFutex;
6884 state->mColdGen++;
6885 mFastCaptureFutex = 0;
6886 sq->end();
6887 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6888 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6889#if 0
6890 if (kUseFastCapture == FastCapture_Dynamic) {
6891 // FIXME
6892 }
6893#endif
6894#ifdef AUDIO_WATCHDOG
6895 // FIXME
6896#endif
6897 } else {
6898 sq->end(false /*didModify*/);
6899 }
6900 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006901 status_t result = mInput->stream->standby();
6902 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006903
6904 // If going into standby, flush the pipe source.
6905 if (mPipeSource.get() != nullptr) {
6906 const ssize_t flushed = mPipeSource->flush();
6907 if (flushed > 0) {
6908 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6909 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6910 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6911 }
6912 }
Eric Laurent81784c32012-11-19 14:55:58 -08006913}
6914
Glenn Kasten05997e22014-03-13 15:08:33 -07006915// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006916sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006917 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006918 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006919 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006920 audio_format_t format,
6921 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006922 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006923 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006924 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006925 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006926 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006927 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006928 status_t *status,
6929 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006930{
Glenn Kasten74935e42013-12-19 08:56:45 -08006931 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006932 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006933 sp<RecordTrack> track;
6934 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006935 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006936 audio_input_flags_t requestedFlags = *flags;
6937 uint32_t sampleRate;
6938
6939 lStatus = initCheck();
6940 if (lStatus != NO_ERROR) {
6941 ALOGE("createRecordTrack_l() audio driver not initialized");
6942 goto Exit;
6943 }
6944
6945 if (*pSampleRate == 0) {
6946 *pSampleRate = mSampleRate;
6947 }
6948 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006949
6950 // special case for FAST flag considered OK if fast capture is present
6951 if (hasFastCapture()) {
6952 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6953 }
6954
Eric Laurentf14db3c2017-12-08 14:20:36 -08006955 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006956 if ((*flags & inputFlags) != *flags) {
6957 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6958 " input flags (%08x)",
6959 *flags, inputFlags);
6960 *flags = (audio_input_flags_t)(*flags & inputFlags);
6961 }
Eric Laurent81784c32012-11-19 14:55:58 -08006962
Glenn Kasten90e58b12013-07-31 16:16:02 -07006963 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006964 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006965 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006966 // we formerly checked for a callback handler (non-0 tid),
6967 // but that is no longer required for TRANSFER_OBTAIN mode
6968 //
Glenn Kasten74105912014-07-03 12:28:53 -07006969 // frame count is not specified, or is exactly the pipe depth
6970 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006971 // PCM data
6972 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006973 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006974 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006975 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006976 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006977 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006978 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006979 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006980 hasFastCapture() &&
6981 // there are sufficient fast track slots available
6982 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006983 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006984 // check compatibility with audio effects.
6985 Mutex::Autolock _l(mLock);
6986 // Do not accept FAST flag if the session has software effects
6987 sp<EffectChain> chain = getEffectChain_l(sessionId);
6988 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006989 audio_input_flags_t old = *flags;
6990 chain->checkInputFlagCompatibility(flags);
6991 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006992 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6993 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006994 }
6995 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006996 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006997 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6998 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006999 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007000 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7001 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007002 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007003 this, frameCount, mFrameCount, mPipeFramesP2,
7004 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007005 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007006 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007007 }
7008 }
7009
Eric Laurentf14db3c2017-12-08 14:20:36 -08007010 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7011 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7012 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7013 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7014 lStatus = BAD_TYPE;
7015 goto Exit;
7016 }
7017
Glenn Kasten74105912014-07-03 12:28:53 -07007018 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007019 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007020 // fast track: frame count is exactly the pipe depth
7021 frameCount = mPipeFramesP2;
7022 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007023 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007024 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007025 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7026 // or 20 ms if there is a fast capture
7027 // TODO This could be a roundupRatio inline, and const
7028 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7029 * sampleRate + mSampleRate - 1) / mSampleRate;
7030 // minimum number of notification periods is at least kMinNotifications,
7031 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7032 static const size_t kMinNotifications = 3;
7033 static const uint32_t kMinMs = 30;
7034 // TODO This could be a roundupRatio inline
7035 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7036 // TODO This could be a roundupRatio inline
7037 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7038 maxNotificationFrames;
7039 const size_t minFrameCount = maxNotificationFrames *
7040 max(kMinNotifications, minNotificationsByMs);
7041 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007042 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7043 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007044 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007045 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007046 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007047 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007048
7049 { // scope for mLock
7050 Mutex::Autolock _l(mLock);
7051
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007052 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007053 format, channelMask, frameCount,
7054 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007055 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007056
Glenn Kasten03003332013-08-06 15:40:54 -07007057 lStatus = track->initCheck();
7058 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007059 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007060 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007061 goto Exit;
7062 }
7063 mTracks.add(track);
7064
Eric Laurent05067782016-06-01 18:27:28 -07007065 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007066 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7067 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7068 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007069 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007070 }
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007072
Eric Laurent81784c32012-11-19 14:55:58 -08007073 lStatus = NO_ERROR;
7074
7075Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007076 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007077 return track;
7078}
7079
7080status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7081 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007082 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007083{
7084 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7085 sp<ThreadBase> strongMe = this;
7086 status_t status = NO_ERROR;
7087
7088 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007089 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007090 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007091 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007092 triggerSession,
7093 recordTrack->sessionId(),
7094 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007095 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007096 // Sync event can be cancelled by the trigger session if the track is not in a
7097 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007098 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007099 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007100 } else {
7101 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007102 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007103 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007104 }
7105 }
7106
7107 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007108 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007109 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007110 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7111 if (recordTrack->mState == TrackBase::PAUSING) {
7112 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007113 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007114 } else {
7115 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007116 }
7117 return status;
7118 }
7119
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007120 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7121 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7122 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007123 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007124 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007125 status_t status = NO_ERROR;
7126 if (recordTrack->isExternalTrack()) {
7127 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007128 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007129 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007130 mLock.lock();
7131 // FIXME should verify that recordTrack is still in mActiveTracks
7132 if (status != NO_ERROR) {
7133 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007134 recordTrack->clearSyncStartEvent();
7135 ALOGV("RecordThread::start error %d", status);
7136 return status;
7137 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007138 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007139 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007140 // Catch up with current buffer indices if thread is already running.
7141 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7142 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7143 // see previously buffered data before it called start(), but with greater risk of overrun.
7144
Andy Hung73c02e42015-03-29 01:13:58 -07007145 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07007146 // clear any converter state as new data will be discontinuous
7147 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007148 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007149 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007150 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007151 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007152 ALOGV("Record failed to start");
7153 status = BAD_VALUE;
7154 goto startError;
7155 }
Eric Laurent81784c32012-11-19 14:55:58 -08007156 return status;
7157 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007158
Eric Laurent81784c32012-11-19 14:55:58 -08007159startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007160 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007161 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007162 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007163 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007164 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007165 return status;
7166}
7167
Eric Laurent81784c32012-11-19 14:55:58 -08007168void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7169{
7170 sp<SyncEvent> strongEvent = event.promote();
7171
7172 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007173 sp<RefBase> ptr = strongEvent->cookie().promote();
7174 if (ptr != 0) {
7175 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7176 recordTrack->handleSyncStartEvent(strongEvent);
7177 }
Eric Laurent81784c32012-11-19 14:55:58 -08007178 }
7179}
7180
Glenn Kastena8356f62013-07-25 14:37:52 -07007181bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007182 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007183 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007184 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007185 return false;
7186 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007187 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007188 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007189 // signal thread to stop
7190 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007191 // do not wait for mStartStopCond if exiting
7192 if (exitPending()) {
7193 return true;
7194 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007195 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007196 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007197 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007198 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007199 ALOGV("Record stopped OK");
7200 return true;
7201 }
7202 return false;
7203}
7204
Glenn Kasten0f11b512014-01-31 16:18:54 -08007205bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007206{
7207 return false;
7208}
7209
Glenn Kasten0f11b512014-01-31 16:18:54 -08007210status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007211{
7212#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7213 if (!isValidSyncEvent(event)) {
7214 return BAD_VALUE;
7215 }
7216
Glenn Kastend848eb42016-03-08 13:42:11 -08007217 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007218 status_t ret = NAME_NOT_FOUND;
7219
7220 Mutex::Autolock _l(mLock);
7221
7222 for (size_t i = 0; i < mTracks.size(); i++) {
7223 sp<RecordTrack> track = mTracks[i];
7224 if (eventSession == track->sessionId()) {
7225 (void) track->setSyncEvent(event);
7226 ret = NO_ERROR;
7227 }
7228 }
7229 return ret;
7230#else
7231 return BAD_VALUE;
7232#endif
7233}
7234
jiabin653cc0a2018-01-17 17:54:10 -08007235status_t AudioFlinger::RecordThread::getActiveMicrophones(
7236 std::vector<media::MicrophoneInfo>* activeMicrophones)
7237{
7238 ALOGV("RecordThread::getActiveMicrophones");
7239 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007240 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7241 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007242}
7243
Kevin Rocard069c2712018-03-29 19:09:14 -07007244void AudioFlinger::RecordThread::updateMetadata_l()
7245{
7246 if (mInput == nullptr || mInput->stream == nullptr ||
7247 !mActiveTracks.readAndClearHasChanged()) {
7248 return;
7249 }
7250 StreamInHalInterface::SinkMetadata metadata;
7251 for (const sp<RecordTrack> &track : mActiveTracks) {
7252 // No track is invalid as this is called after prepareTrack_l in the same critical section
7253 metadata.tracks.push_back({
7254 .source = track->attributes().source,
7255 .gain = 1, // capture tracks do not have volumes
7256 });
7257 }
7258 mInput->stream->updateSinkMetadata(metadata);
7259}
7260
Eric Laurent81784c32012-11-19 14:55:58 -08007261// destroyTrack_l() must be called with ThreadBase::mLock held
7262void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7263{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007264 track->terminate();
7265 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007266 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007267 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007268 removeTrack_l(track);
7269 }
7270}
7271
7272void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7273{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007274 String8 result;
7275 track->appendDump(result, false /* active */);
7276 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7277
Eric Laurent81784c32012-11-19 14:55:58 -08007278 mTracks.remove(track);
7279 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007280 if (track->isFastTrack()) {
7281 ALOG_ASSERT(!mFastTrackAvail);
7282 mFastTrackAvail = true;
7283 }
Eric Laurent81784c32012-11-19 14:55:58 -08007284}
7285
7286void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7287{
7288 dumpInternals(fd, args);
7289 dumpTracks(fd, args);
7290 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007291 dprintf(fd, " Local log:\n");
7292 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007293}
7294
7295void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7296{
Glenn Kasten44182c22015-03-05 17:12:23 -08007297 dumpBase(fd, args);
7298
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007299 AudioStreamIn *input = mInput;
7300 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7301 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7302 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007303 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007304 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007305 }
Andy Hungbfa64962017-06-12 14:43:19 -07007306
7307 if (input != nullptr) {
7308 dprintf(fd, " Hal stream dump:\n");
7309 (void)input->stream->dump(fd);
7310 }
7311
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007312 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007313 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007314
Glenn Kasten2f90c512015-12-02 11:40:09 -08007315 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7316 // while we are dumping it. It may be inconsistent, but it won't mutate!
7317 // This is a large object so we place it on the heap.
7318 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7319 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7320 copy->dump(fd);
7321 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007322}
7323
Glenn Kasten0f11b512014-01-31 16:18:54 -08007324void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007325{
Eric Laurent81784c32012-11-19 14:55:58 -08007326 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007327 size_t numtracks = mTracks.size();
7328 size_t numactive = mActiveTracks.size();
7329 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007330 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007331 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007332 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007333 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007334 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007335 RecordTrack::appendDumpHeader(result);
7336 for (size_t i = 0; i < numtracks ; ++i) {
7337 sp<RecordTrack> track = mTracks[i];
7338 if (track != 0) {
7339 bool active = mActiveTracks.indexOf(track) >= 0;
7340 if (active) {
7341 numactiveseen++;
7342 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007343 result.append(prefix);
7344 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007345 }
Eric Laurent81784c32012-11-19 14:55:58 -08007346 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007347 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007348 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007349 }
7350
Marco Nelissenb2208842014-02-07 14:00:50 -08007351 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007352 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007353 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007354 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007355 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007356 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007357 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007358 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007359 result.append(prefix);
7360 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007361 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007362 }
Eric Laurent81784c32012-11-19 14:55:58 -08007363
7364 }
7365 write(fd, result.string(), result.size());
7366}
7367
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007368void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7369{
7370 Mutex::Autolock _l(mLock);
7371 for (size_t i = 0; i < mTracks.size() ; i++) {
7372 sp<RecordTrack> track = mTracks[i];
7373 if (track != 0 && track->uid() == uid) {
7374 track->setSilenced(silenced);
7375 }
7376 }
7377}
Andy Hung73c02e42015-03-29 01:13:58 -07007378
7379void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7380{
7381 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7382 RecordThread *recordThread = (RecordThread *) threadBase.get();
7383 mRsmpInFront = recordThread->mRsmpInRear;
7384 mRsmpInUnrel = 0;
7385}
7386
7387void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7388 size_t *framesAvailable, bool *hasOverrun)
7389{
7390 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7391 RecordThread *recordThread = (RecordThread *) threadBase.get();
7392 const int32_t rear = recordThread->mRsmpInRear;
7393 const int32_t front = mRsmpInFront;
7394 const ssize_t filled = rear - front;
7395
7396 size_t framesIn;
7397 bool overrun = false;
7398 if (filled < 0) {
7399 // should not happen, but treat like a massive overrun and re-sync
7400 framesIn = 0;
7401 mRsmpInFront = rear;
7402 overrun = true;
7403 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7404 framesIn = (size_t) filled;
7405 } else {
7406 // client is not keeping up with server, but give it latest data
7407 framesIn = recordThread->mRsmpInFrames;
7408 mRsmpInFront = /* front = */ rear - framesIn;
7409 overrun = true;
7410 }
7411 if (framesAvailable != NULL) {
7412 *framesAvailable = framesIn;
7413 }
7414 if (hasOverrun != NULL) {
7415 *hasOverrun = overrun;
7416 }
7417}
7418
Eric Laurent81784c32012-11-19 14:55:58 -08007419// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007420status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007421 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007422{
Andy Hung73c02e42015-03-29 01:13:58 -07007423 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007424 if (threadBase == 0) {
7425 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007426 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007427 return NOT_ENOUGH_DATA;
7428 }
7429 RecordThread *recordThread = (RecordThread *) threadBase.get();
7430 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007431 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007432 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007433 // FIXME should not be P2 (don't want to increase latency)
7434 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007435 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007436 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007437 front &= recordThread->mRsmpInFramesP2 - 1;
7438 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007439 if (part1 > (size_t) filled) {
7440 part1 = filled;
7441 }
7442 size_t ask = buffer->frameCount;
7443 ALOG_ASSERT(ask > 0);
7444 if (part1 > ask) {
7445 part1 = ask;
7446 }
7447 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007448 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007449 buffer->raw = NULL;
7450 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007451 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007452 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007453 }
7454
Andy Hung57446612015-04-19 23:56:46 -07007455 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007456 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007457 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007458 return NO_ERROR;
7459}
7460
7461// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007462void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7463 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007464{
Glenn Kasten85948432013-08-19 12:09:05 -07007465 size_t stepCount = buffer->frameCount;
7466 if (stepCount == 0) {
7467 return;
7468 }
Andy Hung73c02e42015-03-29 01:13:58 -07007469 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7470 mRsmpInUnrel -= stepCount;
7471 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007472 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007473 buffer->frameCount = 0;
7474}
7475
Eric Laurentd8365c52017-07-16 15:27:05 -07007476void AudioFlinger::RecordThread::checkBtNrec()
7477{
7478 Mutex::Autolock _l(mLock);
7479 checkBtNrec_l();
7480}
7481
7482void AudioFlinger::RecordThread::checkBtNrec_l()
7483{
7484 // disable AEC and NS if the device is a BT SCO headset supporting those
7485 // pre processings
7486 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7487 mAudioFlinger->btNrecIsOff();
7488 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7489 for (size_t i = 0; i < mEffectChains.size(); i++) {
7490 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7491 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7492 }
7493 }
7494}
7495
Andy Hung97a893e2015-03-29 01:03:07 -07007496
Eric Laurent10351942014-05-08 18:49:52 -07007497bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7498 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007499{
7500 bool reconfig = false;
7501
Eric Laurent10351942014-05-08 18:49:52 -07007502 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007503
Eric Laurent10351942014-05-08 18:49:52 -07007504 audio_format_t reqFormat = mFormat;
7505 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007506 // 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 -07007507 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7508
7509 AudioParameter param = AudioParameter(keyValuePair);
7510 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007511
7512 // scope for AutoPark extends to end of method
7513 AutoPark<FastCapture> park(mFastCapture);
7514
Eric Laurent10351942014-05-08 18:49:52 -07007515 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7516 // channel count change can be requested. Do we mandate the first client defines the
7517 // HAL sampling rate and channel count or do we allow changes on the fly?
7518 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7519 samplingRate = value;
7520 reconfig = true;
7521 }
7522 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007523 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007524 status = BAD_VALUE;
7525 } else {
7526 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007527 reconfig = true;
7528 }
Eric Laurent10351942014-05-08 18:49:52 -07007529 }
7530 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7531 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007532 if (!audio_is_input_channel(mask) ||
7533 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007534 status = BAD_VALUE;
7535 } else {
7536 channelMask = mask;
7537 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007538 }
Eric Laurent10351942014-05-08 18:49:52 -07007539 }
7540 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7541 // do not accept frame count changes if tracks are open as the track buffer
7542 // size depends on frame count and correct behavior would not be guaranteed
7543 // if frame count is changed after track creation
7544 if (mActiveTracks.size() > 0) {
7545 status = INVALID_OPERATION;
7546 } else {
7547 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007548 }
Eric Laurent10351942014-05-08 18:49:52 -07007549 }
7550 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7551 // forward device change to effects that have requested to be
7552 // aware of attached audio device.
7553 for (size_t i = 0; i < mEffectChains.size(); i++) {
7554 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007555 }
Eric Laurent81784c32012-11-19 14:55:58 -08007556
Eric Laurent10351942014-05-08 18:49:52 -07007557 // store input device and output device but do not forward output device to audio HAL.
7558 // Note that status is ignored by the caller for output device
7559 // (see AudioFlinger::setParameters()
7560 if (audio_is_output_devices(value)) {
7561 mOutDevice = value;
7562 status = BAD_VALUE;
7563 } else {
7564 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007565 if (value != AUDIO_DEVICE_NONE) {
7566 mPrevInDevice = value;
7567 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007568 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007569 }
Eric Laurent10351942014-05-08 18:49:52 -07007570 }
7571 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7572 mAudioSource != (audio_source_t)value) {
7573 // forward device change to effects that have requested to be
7574 // aware of attached audio device.
7575 for (size_t i = 0; i < mEffectChains.size(); i++) {
7576 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007577 }
Eric Laurent10351942014-05-08 18:49:52 -07007578 mAudioSource = (audio_source_t)value;
7579 }
Glenn Kastene198c362013-08-13 09:13:36 -07007580
Eric Laurent10351942014-05-08 18:49:52 -07007581 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007582 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007583 if (status == INVALID_OPERATION) {
7584 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007585 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007586 }
7587 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007588 if (status == BAD_VALUE) {
7589 uint32_t sRate;
7590 audio_channel_mask_t channelMask;
7591 audio_format_t format;
7592 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7593 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7594 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7595 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7596 status = NO_ERROR;
7597 }
Eric Laurent81784c32012-11-19 14:55:58 -08007598 }
Eric Laurent10351942014-05-08 18:49:52 -07007599 if (status == NO_ERROR) {
7600 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007601 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007602 }
7603 }
Eric Laurent81784c32012-11-19 14:55:58 -08007604 }
Eric Laurent10351942014-05-08 18:49:52 -07007605
Eric Laurent81784c32012-11-19 14:55:58 -08007606 return reconfig;
7607}
7608
7609String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7610{
Eric Laurent81784c32012-11-19 14:55:58 -08007611 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007612 if (initCheck() == NO_ERROR) {
7613 String8 out_s8;
7614 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7615 return out_s8;
7616 }
Eric Laurent81784c32012-11-19 14:55:58 -08007617 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007618 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007619}
7620
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007621void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007622 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7623
7624 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007625
7626 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007627 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007628 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007629 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007630 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007631 desc->mChannelMask = mChannelMask;
7632 desc->mSamplingRate = mSampleRate;
7633 desc->mFormat = mFormat;
7634 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007635 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007636 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007637 break;
7638
Eric Laurent73e26b62015-04-27 16:55:58 -07007639 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007640 default:
7641 break;
7642 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007643 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007644}
7645
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007646void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007647{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007648 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7649 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007650 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007651 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007652 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007653 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7654 result = mInput->stream->getFrameSize(&mFrameSize);
7655 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7656 result = mInput->stream->getBufferSize(&mBufferSize);
7657 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007658 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007659 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7660 "mBufferSize=%lld, mFrameCount=%lld",
7661 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7662 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007663 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007664 // 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 -07007665 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007666 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007667 // A larger value should allow more old data to be read after a track calls start(),
7668 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007669 //
7670 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007671 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007672 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007673 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007674 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007675
7676 // TODO optimize audio capture buffer sizes ...
7677 // Here we calculate the size of the sliding buffer used as a source
7678 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7679 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7680 // be better to have it derived from the pipe depth in the long term.
7681 // The current value is higher than necessary. However it should not add to latency.
7682
Glenn Kasten85948432013-08-19 12:09:05 -07007683 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007684 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7685 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007686 // if posix_memalign fails, will segv here.
7687 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007688
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007689 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7690 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007691}
7692
Glenn Kasten5f972c02014-01-13 09:59:31 -08007693uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007694{
7695 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007696 uint32_t result;
7697 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7698 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007699 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007700 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007701}
7702
Eric Laurent4c415062016-06-17 16:14:16 -07007703// hasAudioSession_l() must be called with ThreadBase::mLock held
7704uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007705{
Eric Laurent81784c32012-11-19 14:55:58 -08007706 uint32_t result = 0;
7707 if (getEffectChain_l(sessionId) != 0) {
7708 result = EFFECT_SESSION;
7709 }
7710
7711 for (size_t i = 0; i < mTracks.size(); ++i) {
7712 if (sessionId == mTracks[i]->sessionId()) {
7713 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007714 if (mTracks[i]->isFastTrack()) {
7715 result |= FAST_SESSION;
7716 }
Eric Laurent81784c32012-11-19 14:55:58 -08007717 break;
7718 }
7719 }
7720
7721 return result;
7722}
7723
Glenn Kastend848eb42016-03-08 13:42:11 -08007724KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007725{
Glenn Kastend848eb42016-03-08 13:42:11 -08007726 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007727 Mutex::Autolock _l(mLock);
7728 for (size_t j = 0; j < mTracks.size(); ++j) {
7729 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007730 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007731 if (ids.indexOfKey(sessionId) < 0) {
7732 ids.add(sessionId, true);
7733 }
7734 }
7735 return ids;
7736}
7737
7738AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7739{
7740 Mutex::Autolock _l(mLock);
7741 AudioStreamIn *input = mInput;
7742 mInput = NULL;
7743 return input;
7744}
7745
7746// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007747sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007748{
7749 if (mInput == NULL) {
7750 return NULL;
7751 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007752 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007753}
7754
7755status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7756{
7757 // only one chain per input thread
7758 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007759 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007760 return INVALID_OPERATION;
7761 }
7762 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007763 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007764 chain->setInBuffer(NULL);
7765 chain->setOutBuffer(NULL);
7766
7767 checkSuspendOnAddEffectChain_l(chain);
7768
Eric Laurent1b928682014-10-02 19:41:47 -07007769 // make sure enabled pre processing effects state is communicated to the HAL as we
7770 // just moved them to a new input stream.
7771 chain->syncHalEffectsState();
7772
Eric Laurent81784c32012-11-19 14:55:58 -08007773 mEffectChains.add(chain);
7774
7775 return NO_ERROR;
7776}
7777
7778size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7779{
7780 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7781 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007782 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007783 chain.get(), mEffectChains.size(), this);
7784 if (mEffectChains.size() == 1) {
7785 mEffectChains.removeAt(0);
7786 }
7787 return 0;
7788}
7789
Eric Laurent1c333e22014-05-20 10:48:17 -07007790status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7791 audio_patch_handle_t *handle)
7792{
7793 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007794
7795 // store new device and send to effects
7796 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007797 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007798 for (size_t i = 0; i < mEffectChains.size(); i++) {
7799 mEffectChains[i]->setDevice_l(mInDevice);
7800 }
7801
Eric Laurentd8365c52017-07-16 15:27:05 -07007802 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007803
7804 // store new source and send to effects
7805 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7806 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007807 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007808 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007809 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007810 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007811
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007812 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007813 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7814 status = hwDevice->createAudioPatch(patch->num_sources,
7815 patch->sources,
7816 patch->num_sinks,
7817 patch->sinks,
7818 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007819 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007820 char *address;
7821 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7822 address = audio_device_address_to_parameter(
7823 patch->sources[0].ext.device.type,
7824 patch->sources[0].ext.device.address);
7825 } else {
7826 address = (char *)calloc(1, 1);
7827 }
7828 AudioParameter param = AudioParameter(String8(address));
7829 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007830 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007831 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007832 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007833 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007834 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007835 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007836 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007837
Eric Laurente8726fe2015-06-26 09:39:24 -07007838 if (mInDevice != mPrevInDevice) {
7839 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7840 mPrevInDevice = mInDevice;
7841 }
Eric Laurent296fb132015-05-01 11:38:42 -07007842
Eric Laurent1c333e22014-05-20 10:48:17 -07007843 return status;
7844}
7845
7846status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7847{
7848 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007849
7850 mInDevice = AUDIO_DEVICE_NONE;
7851
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007852 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007853 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7854 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007855 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007856 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007857 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007858 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007859 }
7860 return status;
7861}
7862
Eric Laurent83b88082014-06-20 18:31:16 -07007863void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7864{
7865 Mutex::Autolock _l(mLock);
7866 mTracks.add(record);
7867}
7868
7869void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7870{
7871 Mutex::Autolock _l(mLock);
7872 destroyTrack_l(record);
7873}
7874
7875void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7876{
7877 ThreadBase::getAudioPortConfig(config);
7878 config->role = AUDIO_PORT_ROLE_SINK;
7879 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7880 config->ext.mix.usecase.source = mAudioSource;
7881}
Eric Laurent1c333e22014-05-20 10:48:17 -07007882
Eric Laurent6acd1d42017-01-04 14:23:29 -08007883// ----------------------------------------------------------------------------
7884// Mmap
7885// ----------------------------------------------------------------------------
7886
7887AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7888 : mThread(thread)
7889{
Phil Burk9fabbf82017-08-03 12:02:00 -07007890 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007891}
7892
7893AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7894{
Phil Burk9fabbf82017-08-03 12:02:00 -07007895 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007896}
7897
7898status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7899 struct audio_mmap_buffer_info *info)
7900{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007901 return mThread->createMmapBuffer(minSizeFrames, info);
7902}
7903
7904status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7905{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007906 return mThread->getMmapPosition(position);
7907}
7908
Eric Laurenta54f1282017-07-01 19:39:32 -07007909status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007910 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007911
7912{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007913 return mThread->start(client, handle);
7914}
7915
7916status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7917{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007918 return mThread->stop(handle);
7919}
7920
Eric Laurent18b57012017-02-13 16:23:52 -08007921status_t AudioFlinger::MmapThreadHandle::standby()
7922{
Eric Laurent18b57012017-02-13 16:23:52 -08007923 return mThread->standby();
7924}
7925
Eric Laurent6acd1d42017-01-04 14:23:29 -08007926
7927AudioFlinger::MmapThread::MmapThread(
7928 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7929 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7930 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7931 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007932 mSessionId(AUDIO_SESSION_NONE),
7933 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007934 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07007935 mActiveTracks(&this->mLocalLog),
7936 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
7937 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007938{
Eric Laurent18b57012017-02-13 16:23:52 -08007939 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007940 readHalParameters_l();
7941}
7942
7943AudioFlinger::MmapThread::~MmapThread()
7944{
Eric Laurent18b57012017-02-13 16:23:52 -08007945 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007946}
7947
7948void AudioFlinger::MmapThread::onFirstRef()
7949{
7950 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7951}
7952
7953void AudioFlinger::MmapThread::disconnect()
7954{
Eric Laurent331679c2018-04-16 17:03:16 -07007955 ActiveTracks<MmapTrack> activeTracks;
7956 {
7957 Mutex::Autolock _l(mLock);
7958 for (const sp<MmapTrack> &t : mActiveTracks) {
7959 activeTracks.add(t);
7960 }
7961 }
7962 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007963 stop(t->portId());
7964 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007965 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007966 if (isOutput()) {
7967 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7968 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08007969 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007970 }
7971}
7972
7973
7974void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7975 audio_stream_type_t streamType __unused,
7976 audio_session_t sessionId,
7977 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007978 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007979 audio_port_handle_t portId)
7980{
7981 mAttr = *attr;
7982 mSessionId = sessionId;
7983 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007984 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007985 mPortId = portId;
7986}
7987
7988status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7989 struct audio_mmap_buffer_info *info)
7990{
7991 if (mHalStream == 0) {
7992 return NO_INIT;
7993 }
Eric Laurent18b57012017-02-13 16:23:52 -08007994 mStandby = true;
7995 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007996 return mHalStream->createMmapBuffer(minSizeFrames, info);
7997}
7998
7999status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8000{
8001 if (mHalStream == 0) {
8002 return NO_INIT;
8003 }
8004 return mHalStream->getMmapPosition(position);
8005}
8006
Eric Laurent331679c2018-04-16 17:03:16 -07008007status_t AudioFlinger::MmapThread::exitStandby()
8008{
8009 status_t ret = mHalStream->start();
8010 if (ret != NO_ERROR) {
8011 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8012 return ret;
8013 }
8014 mStandby = false;
8015 return NO_ERROR;
8016}
8017
Eric Laurenta54f1282017-07-01 19:39:32 -07008018status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008019 audio_port_handle_t *handle)
8020{
Eric Laurenta54f1282017-07-01 19:39:32 -07008021 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8022 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008023 if (mHalStream == 0) {
8024 return NO_INIT;
8025 }
8026
8027 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008028
Eric Laurenta54f1282017-07-01 19:39:32 -07008029 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008030 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008031 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008032 }
8033
8034 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8035
8036 audio_io_handle_t io = mId;
8037 if (isOutput()) {
8038 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8039 config.sample_rate = mSampleRate;
8040 config.channel_mask = mChannelMask;
8041 config.format = mFormat;
8042 audio_stream_type_t stream = streamType();
8043 audio_output_flags_t flags =
8044 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008045 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008046 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8047 mSessionId,
8048 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008049 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008050 client.clientUid,
8051 &config,
8052 flags,
8053 &deviceId,
8054 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008055 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008056 audio_config_base_t config;
8057 config.sample_rate = mSampleRate;
8058 config.channel_mask = mChannelMask;
8059 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008060 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008061 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8062 mSessionId,
8063 client.clientPid,
8064 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008065 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008066 &config,
8067 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8068 &deviceId,
8069 &portId);
8070 }
8071 // APM should not chose a different input or output stream for the same set of attributes
8072 // and audo configuration
8073 if (ret != NO_ERROR || io != mId) {
8074 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8075 __FUNCTION__, ret, io, mId);
8076 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008077 }
8078
Eric Laurent331679c2018-04-16 17:03:16 -07008079 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008080 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008081 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008082 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008083 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008084 }
8085
Eric Laurent331679c2018-04-16 17:03:16 -07008086 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008087 // abort if start is rejected by audio policy manager
8088 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008089 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008090 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008091 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008092 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008093 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008094 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008095 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008096 }
Eric Laurent331679c2018-04-16 17:03:16 -07008097 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008098 } else {
8099 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008100 }
8101 return PERMISSION_DENIED;
8102 }
8103
Eric Laurent67f97292018-04-20 18:05:41 -07008104 if (isOutput()) {
8105 // force volume update when a new track is added
8106 mHalVolFloat = -1.0f;
8107 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008108 for (const sp<MmapTrack> &track : mActiveTracks) {
8109 if (track->isSilenced_l() && track->uid() != client.clientUid)
8110 track->invalidate();
8111 }
8112 }
8113
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008114 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8115 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -07008116 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008117
Eric Laurent331679c2018-04-16 17:03:16 -07008118 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008119 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008120 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008121 if (chain != 0) {
8122 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8123 chain->incTrackCnt();
8124 chain->incActiveTrackCnt();
8125 }
8126
8127 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008128 broadcast_l();
8129
Eric Laurenta54f1282017-07-01 19:39:32 -07008130 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008131
8132 return NO_ERROR;
8133}
8134
8135status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8136{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008137 ALOGV("%s handle %d", __FUNCTION__, handle);
8138
8139 if (mHalStream == 0) {
8140 return NO_INIT;
8141 }
8142
Eric Laurenta54f1282017-07-01 19:39:32 -07008143 if (handle == mPortId) {
8144 mHalStream->stop();
8145 return NO_ERROR;
8146 }
8147
Eric Laurent331679c2018-04-16 17:03:16 -07008148 Mutex::Autolock _l(mLock);
8149
Eric Laurent6acd1d42017-01-04 14:23:29 -08008150 sp<MmapTrack> track;
8151 for (const sp<MmapTrack> &t : mActiveTracks) {
8152 if (handle == t->portId()) {
8153 track = t;
8154 break;
8155 }
8156 }
8157 if (track == 0) {
8158 return BAD_VALUE;
8159 }
8160
8161 mActiveTracks.remove(track);
8162
Eric Laurent331679c2018-04-16 17:03:16 -07008163 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008164 if (isOutput()) {
8165 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008166 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008167 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008168 AudioSystem::stopInput(track->portId());
8169 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008170 }
Eric Laurent331679c2018-04-16 17:03:16 -07008171 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008172
8173 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8174 if (chain != 0) {
8175 chain->decActiveTrackCnt();
8176 chain->decTrackCnt();
8177 }
8178
8179 broadcast_l();
8180
Eric Laurent6acd1d42017-01-04 14:23:29 -08008181 return NO_ERROR;
8182}
8183
Eric Laurent18b57012017-02-13 16:23:52 -08008184status_t AudioFlinger::MmapThread::standby()
8185{
8186 ALOGV("%s", __FUNCTION__);
8187
8188 if (mHalStream == 0) {
8189 return NO_INIT;
8190 }
8191 if (mActiveTracks.size() != 0) {
8192 return INVALID_OPERATION;
8193 }
8194 mHalStream->standby();
8195 mStandby = true;
8196 releaseWakeLock();
8197 return NO_ERROR;
8198}
8199
Eric Laurent6acd1d42017-01-04 14:23:29 -08008200
8201void AudioFlinger::MmapThread::readHalParameters_l()
8202{
8203 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8204 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8205 mFormat = mHALFormat;
8206 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8207 result = mHalStream->getFrameSize(&mFrameSize);
8208 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8209 result = mHalStream->getBufferSize(&mBufferSize);
8210 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8211 mFrameCount = mBufferSize / mFrameSize;
8212}
8213
8214bool AudioFlinger::MmapThread::threadLoop()
8215{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008216 checkSilentMode_l();
8217
8218 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8219
8220 while (!exitPending())
8221 {
8222 Mutex::Autolock _l(mLock);
8223 Vector< sp<EffectChain> > effectChains;
8224
8225 if (mSignalPending) {
8226 // A signal was raised while we were unlocked
8227 mSignalPending = false;
8228 } else {
8229 if (mConfigEvents.isEmpty()) {
8230 // we're about to wait, flush the binder command buffer
8231 IPCThreadState::self()->flushCommands();
8232
8233 if (exitPending()) {
8234 break;
8235 }
8236
Eric Laurent6acd1d42017-01-04 14:23:29 -08008237 // wait until we have something to do...
8238 ALOGV("%s going to sleep", myName.string());
8239 mWaitWorkCV.wait(mLock);
8240 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008241
8242 checkSilentMode_l();
8243
8244 continue;
8245 }
8246 }
8247
8248 processConfigEvents_l();
8249
8250 processVolume_l();
8251
8252 checkInvalidTracks_l();
8253
8254 mActiveTracks.updatePowerState(this);
8255
Kevin Rocard069c2712018-03-29 19:09:14 -07008256 updateMetadata_l();
8257
Eric Laurent6acd1d42017-01-04 14:23:29 -08008258 lockEffectChains_l(effectChains);
8259 for (size_t i = 0; i < effectChains.size(); i ++) {
8260 effectChains[i]->process_l();
8261 }
8262 // enable changes in effect chain
8263 unlockEffectChains(effectChains);
8264 // Effect chains will be actually deleted here if they were removed from
8265 // mEffectChains list during mixing or effects processing
8266 }
8267
8268 threadLoop_exit();
8269
8270 if (!mStandby) {
8271 threadLoop_standby();
8272 mStandby = true;
8273 }
8274
Eric Laurent6acd1d42017-01-04 14:23:29 -08008275 ALOGV("Thread %p type %d exiting", this, mType);
8276 return false;
8277}
8278
8279// checkForNewParameter_l() must be called with ThreadBase::mLock held
8280bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8281 status_t& status)
8282{
8283 AudioParameter param = AudioParameter(keyValuePair);
8284 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008285 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008286 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008287 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008288 // forward device change to effects that have requested to be
8289 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008290 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008291 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008292 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008293 }
8294 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008295 if (audio_is_output_devices(device)) {
8296 mOutDevice = device;
8297 if (!isOutput()) {
8298 sendToHal = false;
8299 }
8300 } else {
8301 mInDevice = device;
8302 if (device != AUDIO_DEVICE_NONE) {
8303 mPrevInDevice = value;
8304 }
8305 // TODO: implement and call checkBtNrec_l();
8306 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008307 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008308 if (sendToHal) {
8309 status = mHalStream->setParameters(keyValuePair);
8310 } else {
8311 status = NO_ERROR;
8312 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008313
8314 return false;
8315}
8316
8317String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8318{
8319 Mutex::Autolock _l(mLock);
8320 String8 out_s8;
8321 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8322 return out_s8;
8323 }
8324 return String8();
8325}
8326
8327void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8328 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8329
8330 desc->mIoHandle = mId;
8331
8332 switch (event) {
8333 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008334 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008335 case AUDIO_INPUT_CONFIG_CHANGED:
8336 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008337 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008338 case AUDIO_OUTPUT_CONFIG_CHANGED:
8339 desc->mPatch = mPatch;
8340 desc->mChannelMask = mChannelMask;
8341 desc->mSamplingRate = mSampleRate;
8342 desc->mFormat = mFormat;
8343 desc->mFrameCount = mFrameCount;
8344 desc->mFrameCountHAL = mFrameCount;
8345 desc->mLatency = 0;
8346 break;
8347
8348 case AUDIO_INPUT_CLOSED:
8349 case AUDIO_OUTPUT_CLOSED:
8350 default:
8351 break;
8352 }
8353 mAudioFlinger->ioConfigChanged(event, desc, pid);
8354}
8355
8356status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8357 audio_patch_handle_t *handle)
8358{
8359 status_t status = NO_ERROR;
8360
8361 // store new device and send to effects
8362 audio_devices_t type = AUDIO_DEVICE_NONE;
8363 audio_port_handle_t deviceId;
8364 if (isOutput()) {
8365 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8366 type |= patch->sinks[i].ext.device.type;
8367 }
8368 deviceId = patch->sinks[0].id;
8369 } else {
8370 type = patch->sources[0].ext.device.type;
8371 deviceId = patch->sources[0].id;
8372 }
8373
8374 for (size_t i = 0; i < mEffectChains.size(); i++) {
8375 mEffectChains[i]->setDevice_l(type);
8376 }
8377
8378 if (isOutput()) {
8379 mOutDevice = type;
8380 } else {
8381 mInDevice = type;
8382 // store new source and send to effects
8383 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8384 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8385 for (size_t i = 0; i < mEffectChains.size(); i++) {
8386 mEffectChains[i]->setAudioSource_l(mAudioSource);
8387 }
8388 }
8389 }
8390
8391 if (mAudioHwDev->supportsAudioPatches()) {
8392 status = mHalDevice->createAudioPatch(patch->num_sources,
8393 patch->sources,
8394 patch->num_sinks,
8395 patch->sinks,
8396 handle);
8397 } else {
8398 char *address;
8399 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8400 //FIXME: we only support address on first sink with HAL version < 3.0
8401 address = audio_device_address_to_parameter(
8402 patch->sinks[0].ext.device.type,
8403 patch->sinks[0].ext.device.address);
8404 } else {
8405 address = (char *)calloc(1, 1);
8406 }
8407 AudioParameter param = AudioParameter(String8(address));
8408 free(address);
8409 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8410 if (!isOutput()) {
8411 param.addInt(String8(AudioParameter::keyInputSource),
8412 (int)patch->sinks[0].ext.mix.usecase.source);
8413 }
8414 status = mHalStream->setParameters(param.toString());
8415 *handle = AUDIO_PATCH_HANDLE_NONE;
8416 }
8417
8418 if (isOutput() && mPrevOutDevice != mOutDevice) {
8419 mPrevOutDevice = type;
8420 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008421 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008422 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008423 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008424 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008425 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008426 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008427 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008428 }
8429 if (!isOutput() && mPrevInDevice != mInDevice) {
8430 mPrevInDevice = type;
8431 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008432 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008433 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008434 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008435 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008436 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008437 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008438 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008439 }
8440 return status;
8441}
8442
8443status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8444{
8445 status_t status = NO_ERROR;
8446
8447 mInDevice = AUDIO_DEVICE_NONE;
8448
8449 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8450 supportsAudioPatches : false;
8451
8452 if (supportsAudioPatches) {
8453 status = mHalDevice->releaseAudioPatch(handle);
8454 } else {
8455 AudioParameter param;
8456 param.addInt(String8(AudioParameter::keyRouting), 0);
8457 status = mHalStream->setParameters(param.toString());
8458 }
8459 return status;
8460}
8461
8462void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8463{
8464 ThreadBase::getAudioPortConfig(config);
8465 if (isOutput()) {
8466 config->role = AUDIO_PORT_ROLE_SOURCE;
8467 config->ext.mix.hw_module = mAudioHwDev->handle();
8468 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8469 } else {
8470 config->role = AUDIO_PORT_ROLE_SINK;
8471 config->ext.mix.hw_module = mAudioHwDev->handle();
8472 config->ext.mix.usecase.source = mAudioSource;
8473 }
8474}
8475
8476status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8477{
8478 audio_session_t session = chain->sessionId();
8479
8480 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8481 // Attach all tracks with same session ID to this chain.
8482 // indicate all active tracks in the chain
8483 for (const sp<MmapTrack> &track : mActiveTracks) {
8484 if (session == track->sessionId()) {
8485 chain->incTrackCnt();
8486 chain->incActiveTrackCnt();
8487 }
8488 }
8489
8490 chain->setThread(this);
8491 chain->setInBuffer(nullptr);
8492 chain->setOutBuffer(nullptr);
8493 chain->syncHalEffectsState();
8494
8495 mEffectChains.add(chain);
8496 checkSuspendOnAddEffectChain_l(chain);
8497 return NO_ERROR;
8498}
8499
8500size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8501{
8502 audio_session_t session = chain->sessionId();
8503
8504 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8505
8506 for (size_t i = 0; i < mEffectChains.size(); i++) {
8507 if (chain == mEffectChains[i]) {
8508 mEffectChains.removeAt(i);
8509 // detach all active tracks from the chain
8510 // detach all tracks with same session ID from this chain
8511 for (const sp<MmapTrack> &track : mActiveTracks) {
8512 if (session == track->sessionId()) {
8513 chain->decActiveTrackCnt();
8514 chain->decTrackCnt();
8515 }
8516 }
8517 break;
8518 }
8519 }
8520 return mEffectChains.size();
8521}
8522
8523// hasAudioSession_l() must be called with ThreadBase::mLock held
8524uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8525{
8526 uint32_t result = 0;
8527 if (getEffectChain_l(sessionId) != 0) {
8528 result = EFFECT_SESSION;
8529 }
8530
8531 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8532 sp<MmapTrack> track = mActiveTracks[i];
8533 if (sessionId == track->sessionId()) {
8534 result |= TRACK_SESSION;
8535 if (track->isFastTrack()) {
8536 result |= FAST_SESSION;
8537 }
8538 break;
8539 }
8540 }
8541
8542 return result;
8543}
8544
8545void AudioFlinger::MmapThread::threadLoop_standby()
8546{
8547 mHalStream->standby();
8548}
8549
8550void AudioFlinger::MmapThread::threadLoop_exit()
8551{
Phil Burk7dce7282017-09-27 13:51:41 -07008552 // Do not call callback->onTearDown() because it is redundant for thread exit
8553 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008554}
8555
8556status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8557{
8558 return BAD_VALUE;
8559}
8560
8561bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8562{
8563 return false;
8564}
8565
8566status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8567 const effect_descriptor_t *desc, audio_session_t sessionId)
8568{
8569 // No global effect sessions on mmap threads
8570 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8571 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8572 desc->name, mThreadName);
8573 return BAD_VALUE;
8574 }
8575
8576 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8577 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8578 desc->name);
8579 return BAD_VALUE;
8580 }
8581 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008582 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8583 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008584 return BAD_VALUE;
8585 }
8586
8587 // Only allow effects without processing load or latency
8588 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8589 return BAD_VALUE;
8590 }
8591
8592 return NO_ERROR;
8593
8594}
8595
8596void AudioFlinger::MmapThread::checkInvalidTracks_l()
8597{
8598 for (const sp<MmapTrack> &track : mActiveTracks) {
8599 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008600 sp<MmapStreamCallback> callback = mCallback.promote();
8601 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008602 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008603 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008604 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008605 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8606 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8607 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008608 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008609 }
8610 }
8611}
8612
8613void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8614{
8615 dumpInternals(fd, args);
8616 dumpTracks(fd, args);
8617 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008618 dprintf(fd, " Local log:\n");
8619 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008620}
8621
8622void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8623{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008624 dumpBase(fd, args);
8625
8626 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8627 mAttr.content_type, mAttr.usage, mAttr.source);
8628 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8629 if (mActiveTracks.size() == 0) {
8630 dprintf(fd, " No active clients\n");
8631 }
8632}
8633
8634void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8635{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008636 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008637 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008638 dprintf(fd, " %zu Tracks\n", numtracks);
8639 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008640 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008641 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008642 MmapTrack::appendDumpHeader(result);
8643 for (size_t i = 0; i < numtracks ; ++i) {
8644 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008645 result.append(prefix);
8646 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008647 }
8648 } else {
8649 dprintf(fd, "\n");
8650 }
8651 write(fd, result.string(), result.size());
8652}
8653
8654AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8655 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8656 AudioHwDevice *hwDev, AudioStreamOut *output,
8657 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8658 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8659 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008660 mStreamVolume(1.0),
8661 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008662 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008663{
8664 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8665 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8666 mMasterVolume = audioFlinger->masterVolume_l();
8667 mMasterMute = audioFlinger->masterMute_l();
8668 if (mAudioHwDev) {
8669 if (mAudioHwDev->canSetMasterVolume()) {
8670 mMasterVolume = 1.0;
8671 }
8672
8673 if (mAudioHwDev->canSetMasterMute()) {
8674 mMasterMute = false;
8675 }
8676 }
8677}
8678
8679void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8680 audio_stream_type_t streamType,
8681 audio_session_t sessionId,
8682 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008683 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008684 audio_port_handle_t portId)
8685{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008686 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008687 mStreamType = streamType;
8688}
8689
8690AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8691{
8692 Mutex::Autolock _l(mLock);
8693 AudioStreamOut *output = mOutput;
8694 mOutput = NULL;
8695 return output;
8696}
8697
8698void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8699{
8700 Mutex::Autolock _l(mLock);
8701 // Don't apply master volume in SW if our HAL can do it for us.
8702 if (mAudioHwDev &&
8703 mAudioHwDev->canSetMasterVolume()) {
8704 mMasterVolume = 1.0;
8705 } else {
8706 mMasterVolume = value;
8707 }
8708}
8709
8710void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8711{
8712 Mutex::Autolock _l(mLock);
8713 // Don't apply master mute in SW if our HAL can do it for us.
8714 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8715 mMasterMute = false;
8716 } else {
8717 mMasterMute = muted;
8718 }
8719}
8720
8721void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8722{
8723 Mutex::Autolock _l(mLock);
8724 if (stream == mStreamType) {
8725 mStreamVolume = value;
8726 broadcast_l();
8727 }
8728}
8729
8730float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8731{
8732 Mutex::Autolock _l(mLock);
8733 if (stream == mStreamType) {
8734 return mStreamVolume;
8735 }
8736 return 0.0f;
8737}
8738
8739void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8740{
8741 Mutex::Autolock _l(mLock);
8742 if (stream == mStreamType) {
8743 mStreamMute= muted;
8744 broadcast_l();
8745 }
8746}
8747
8748void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8749{
8750 Mutex::Autolock _l(mLock);
8751 if (streamType == mStreamType) {
8752 for (const sp<MmapTrack> &track : mActiveTracks) {
8753 track->invalidate();
8754 }
8755 broadcast_l();
8756 }
8757}
8758
8759void AudioFlinger::MmapPlaybackThread::processVolume_l()
8760{
8761 float volume;
8762
8763 if (mMasterMute || mStreamMute) {
8764 volume = 0;
8765 } else {
8766 volume = mMasterVolume * mStreamVolume;
8767 }
8768
8769 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008770
8771 // Convert volumes from float to 8.24
8772 uint32_t vol = (uint32_t)(volume * (1 << 24));
8773
8774 // Delegate volume control to effect in track effect chain if needed
8775 // only one effect chain can be present on DirectOutputThread, so if
8776 // there is one, the track is connected to it
8777 if (!mEffectChains.isEmpty()) {
8778 mEffectChains[0]->setVolume_l(&vol, &vol);
8779 volume = (float)vol / (1 << 24);
8780 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008781 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008782 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8783 mHalVolFloat = volume; // HW volume control worked, so update value.
8784 mNoCallbackWarningCount = 0;
8785 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008786 sp<MmapStreamCallback> callback = mCallback.promote();
8787 if (callback != 0) {
8788 int channelCount;
8789 if (isOutput()) {
8790 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8791 } else {
8792 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8793 }
8794 Vector<float> values;
8795 for (int i = 0; i < channelCount; i++) {
8796 values.add(volume);
8797 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008798 mHalVolFloat = volume; // SW volume control worked, so update value.
8799 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008800 mLock.unlock();
8801 callback->onVolumeChanged(mChannelMask, values);
8802 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008803 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008804 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8805 ALOGW("Could not set MMAP stream volume: no volume callback!");
8806 mNoCallbackWarningCount++;
8807 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008808 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008809 }
8810 }
8811}
8812
Kevin Rocard069c2712018-03-29 19:09:14 -07008813void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8814{
8815 if (mOutput == nullptr || mOutput->stream == nullptr ||
8816 !mActiveTracks.readAndClearHasChanged()) {
8817 return;
8818 }
8819 StreamOutHalInterface::SourceMetadata metadata;
8820 for (const sp<MmapTrack> &track : mActiveTracks) {
8821 // No track is invalid as this is called after prepareTrack_l in the same critical section
8822 metadata.tracks.push_back({
8823 .usage = track->attributes().usage,
8824 .content_type = track->attributes().content_type,
8825 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8826 });
8827 }
8828 mOutput->stream->updateSourceMetadata(metadata);
8829}
8830
Eric Laurent6acd1d42017-01-04 14:23:29 -08008831void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8832{
8833 if (!mMasterMute) {
8834 char value[PROPERTY_VALUE_MAX];
8835 if (property_get("ro.audio.silent", value, "0") > 0) {
8836 char *endptr;
8837 unsigned long ul = strtoul(value, &endptr, 0);
8838 if (*endptr == '\0' && ul != 0) {
8839 ALOGD("Silence is golden");
8840 // The setprop command will not allow a property to be changed after
8841 // the first time it is set, so we don't have to worry about un-muting.
8842 setMasterMute_l(true);
8843 }
8844 }
8845 }
8846}
8847
8848void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8849{
8850 MmapThread::dumpInternals(fd, args);
8851
Glenn Kastend3bb6452016-12-05 18:14:37 -08008852 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8853 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008854 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8855}
8856
8857AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8858 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8859 AudioHwDevice *hwDev, AudioStreamIn *input,
8860 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8861 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8862 mInput(input)
8863{
8864 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8865 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8866}
8867
Eric Laurent331679c2018-04-16 17:03:16 -07008868status_t AudioFlinger::MmapCaptureThread::exitStandby()
8869{
8870 mInput->stream->setGain(1.0f);
8871 return MmapThread::exitStandby();
8872}
8873
Eric Laurent6acd1d42017-01-04 14:23:29 -08008874AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8875{
8876 Mutex::Autolock _l(mLock);
8877 AudioStreamIn *input = mInput;
8878 mInput = NULL;
8879 return input;
8880}
Kevin Rocard069c2712018-03-29 19:09:14 -07008881
Eric Laurent331679c2018-04-16 17:03:16 -07008882
8883void AudioFlinger::MmapCaptureThread::processVolume_l()
8884{
8885 bool changed = false;
8886 bool silenced = false;
8887
8888 sp<MmapStreamCallback> callback = mCallback.promote();
8889 if (callback == 0) {
8890 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8891 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
8892 mNoCallbackWarningCount++;
8893 }
8894 }
8895
8896 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
8897 // track is silenced and unmute otherwise
8898 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
8899 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
8900 changed = true;
8901 silenced = mActiveTracks[i]->isSilenced_l();
8902 }
8903 }
8904
8905 if (changed) {
8906 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
8907 }
8908}
8909
Kevin Rocard069c2712018-03-29 19:09:14 -07008910void AudioFlinger::MmapCaptureThread::updateMetadata_l()
8911{
8912 if (mInput == nullptr || mInput->stream == nullptr ||
8913 !mActiveTracks.readAndClearHasChanged()) {
8914 return;
8915 }
8916 StreamInHalInterface::SinkMetadata metadata;
8917 for (const sp<MmapTrack> &track : mActiveTracks) {
8918 // No track is invalid as this is called after prepareTrack_l in the same critical section
8919 metadata.tracks.push_back({
8920 .source = track->attributes().source,
8921 .gain = 1, // capture tracks do not have volumes
8922 });
8923 }
8924 mInput->stream->updateSinkMetadata(metadata);
8925}
8926
Eric Laurent331679c2018-04-16 17:03:16 -07008927void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
8928{
8929 Mutex::Autolock _l(mLock);
8930 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
8931 if (mActiveTracks[i]->uid() == uid) {
8932 mActiveTracks[i]->setSilenced_l(silenced);
8933 broadcast_l();
8934 }
8935 }
8936}
8937
Glenn Kasten63238ef2015-03-02 15:50:29 -08008938} // namespace android