blob: 160aa45bead5093f0fa5311c943d5802bcd3c0de [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
2289// addTrack_l() must be called with ThreadBase::mLock held
2290status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2291{
2292 status_t status = ALREADY_EXISTS;
2293
Eric Laurent81784c32012-11-19 14:55:58 -08002294 if (mActiveTracks.indexOf(track) < 0) {
2295 // the track is newly added, make sure it fills up all its
2296 // buffers before playing. This is to ensure the client will
2297 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002298 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002299 TrackBase::track_state state = track->mState;
2300 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002301 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002302 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002303 mLock.lock();
2304 // abort track was stopped/paused while we released the lock
2305 if (state != track->mState) {
2306 if (status == NO_ERROR) {
2307 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002308 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002309 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002310 mLock.lock();
2311 }
2312 return INVALID_OPERATION;
2313 }
2314 // abort if start is rejected by audio policy manager
2315 if (status != NO_ERROR) {
2316 return PERMISSION_DENIED;
2317 }
2318#ifdef ADD_BATTERY_DATA
2319 // to track the speaker usage
2320 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2321#endif
2322 }
2323
Eric Laurent51716182016-02-29 18:00:56 -08002324 // set retry count for buffer fill
2325 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002326 if (track->isStopping_1()) {
2327 track->mRetryCount = kMaxTrackStopRetriesOffload;
2328 } else {
2329 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2330 }
2331 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002332 } else {
2333 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002334 track->mFillingUpStatus =
2335 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002336 }
2337
Eric Laurent81784c32012-11-19 14:55:58 -08002338 track->mResetDone = false;
2339 track->mPresentationCompleteFrames = 0;
2340 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002341 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2342 if (chain != 0) {
2343 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2344 track->sessionId());
2345 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002346 }
2347
2348 status = NO_ERROR;
2349 }
2350
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002351 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002352 return status;
2353}
2354
Eric Laurentbfb1b832013-01-07 09:53:42 -08002355bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002356{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002357 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002358 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002359 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2360 track->mState = TrackBase::STOPPED;
2361 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002362 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002363 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002364 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002365 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002366
2367 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002368}
2369
2370void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2371{
2372 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002373
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002374 String8 result;
2375 track->appendDump(result, false /* active */);
2376 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002377
Eric Laurent81784c32012-11-19 14:55:58 -08002378 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002379 if (track->isFastTrack()) {
2380 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002381 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002382 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2383 mFastTrackAvailMask |= 1 << index;
2384 // redundant as track is about to be destroyed, for dumpsys only
2385 track->mFastIndex = -1;
2386 }
2387 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2388 if (chain != 0) {
2389 chain->decTrackCnt();
2390 }
2391}
2392
2393String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2394{
Eric Laurent81784c32012-11-19 14:55:58 -08002395 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002396 String8 out_s8;
2397 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2398 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002399 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002400 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002401}
2402
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002403void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002404 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2405 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002406
Eric Laurent73e26b62015-04-27 16:55:58 -07002407 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002408
2409 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002410 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002411 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002412 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002413 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002414 desc->mChannelMask = mChannelMask;
2415 desc->mSamplingRate = mSampleRate;
2416 desc->mFormat = mFormat;
2417 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002418 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002419 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002420 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002421 break;
2422
Eric Laurent73e26b62015-04-27 16:55:58 -07002423 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002424 default:
2425 break;
2426 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002427 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002428}
2429
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002430void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002431{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002432 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002433}
2434
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002435void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002436{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002437 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002438}
2439
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002440void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002441{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002442 mCallbackThread->setAsyncError();
2443}
2444
Eric Laurent3b4529e2013-09-05 18:09:19 -07002445void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002446{
2447 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002448 // reject out of sequence requests
2449 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2450 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 mWaitWorkCV.signal();
2452 }
2453}
2454
Eric Laurent3b4529e2013-09-05 18:09:19 -07002455void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456{
2457 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002458 // reject out of sequence requests
2459 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2460 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461 mWaitWorkCV.signal();
2462 }
2463}
2464
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002465void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002466{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002467 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002468 mSampleRate = mOutput->getSampleRate();
2469 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002470 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002471 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002472 }
Andy Hung9a592762014-07-21 21:56:01 -07002473 if ((mType == MIXER || mType == DUPLICATING)
2474 && !isValidPcmSinkChannelMask(mChannelMask)) {
2475 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2476 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002477 }
Andy Hunge5412692014-05-16 11:25:07 -07002478 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002479
2480 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002481 status_t result = mOutput->stream->getFormat(&mHALFormat);
2482 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002483 // Get format from the shim, which will be different than the HAL format
2484 // if playing compressed audio over HDMI passthrough.
2485 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002486 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002487 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002488 }
Andy Hung6146c082014-03-18 11:56:15 -07002489 if ((mType == MIXER || mType == DUPLICATING)
2490 && !isValidPcmSinkFormat(mFormat)) {
2491 LOG_FATAL("HAL format %#x not supported for mixed output",
2492 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002493 }
Phil Burk062e67a2015-02-11 13:40:50 -08002494 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002495 result = mOutput->stream->getBufferSize(&mBufferSize);
2496 LOG_ALWAYS_FATAL_IF(result != OK,
2497 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002498 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002499 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002500 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002501 mFrameCount);
2502 }
2503
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002504 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2505 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002506 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002507 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002508 }
2509 }
2510
Eric Laurentd1f69b02014-12-15 14:33:13 -08002511 mHwSupportsPause = false;
2512 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002513 bool supportsPause = false, supportsResume = false;
2514 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2515 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002516 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002517 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002518 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002519 } else if (supportsResume) {
2520 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002521 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002522 }
2523 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002524 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2525 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2526 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002527
Andy Hungfbfc3952015-01-15 13:33:51 -08002528 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2529 // For best precision, we use float instead of the associated output
2530 // device format (typically PCM 16 bit).
2531
2532 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2533 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2534 mBufferSize = mFrameSize * mFrameCount;
2535
2536 // TODO: We currently use the associated output device channel mask and sample rate.
2537 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2538 // (if a valid mask) to avoid premature downmix.
2539 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2540 // instead of the output device sample rate to avoid loss of high frequency information.
2541 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2542 }
2543
Andy Hung09a50072014-02-27 14:30:47 -08002544 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002545 double multiplier = 1.0;
2546 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2547 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002548 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2549 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002550
Eric Laurent81784c32012-11-19 14:55:58 -08002551 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2552 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2553 maxNormalFrameCount = maxNormalFrameCount & ~15;
2554 if (maxNormalFrameCount < minNormalFrameCount) {
2555 maxNormalFrameCount = minNormalFrameCount;
2556 }
2557 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2558 if (multiplier <= 1.0) {
2559 multiplier = 1.0;
2560 } else if (multiplier <= 2.0) {
2561 if (2 * mFrameCount <= maxNormalFrameCount) {
2562 multiplier = 2.0;
2563 } else {
2564 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2565 }
2566 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002567 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002568 }
2569 }
2570 mNormalFrameCount = multiplier * mFrameCount;
2571 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002572 if (mType == MIXER || mType == DUPLICATING) {
2573 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2574 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002575 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002576 mNormalFrameCount);
2577
Andy Hung08fb1742015-05-31 23:22:10 -07002578 // Check if we want to throttle the processing to no more than 2x normal rate
2579 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002580 mThreadThrottleTimeMs = 0;
2581 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002582 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2583
Andy Hung010a1a12014-03-13 13:57:33 -07002584 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2585 // Originally this was int16_t[] array, need to remove legacy implications.
2586 free(mSinkBuffer);
2587 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002588 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2589 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2590 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002591 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002592
Andy Hung69aed5f2014-02-25 17:24:40 -08002593 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2594 // drives the output.
2595 free(mMixerBuffer);
2596 mMixerBuffer = NULL;
2597 if (mMixerBufferEnabled) {
2598 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2599 mMixerBufferSize = mNormalFrameCount * mChannelCount
2600 * audio_bytes_per_sample(mMixerBufferFormat);
2601 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2602 }
Andy Hung98ef9782014-03-04 14:46:50 -08002603 free(mEffectBuffer);
2604 mEffectBuffer = NULL;
2605 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002606 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002607 mEffectBufferSize = mNormalFrameCount * mChannelCount
2608 * audio_bytes_per_sample(mEffectBufferFormat);
2609 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2610 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002611
Eric Laurent81784c32012-11-19 14:55:58 -08002612 // force reconfiguration of effect chains and engines to take new buffer size and audio
2613 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002614 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002615 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2616 // matter.
2617 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2618 Vector< sp<EffectChain> > effectChains = mEffectChains;
2619 for (size_t i = 0; i < effectChains.size(); i ++) {
2620 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2621 }
2622}
2623
Kevin Rocard069c2712018-03-29 19:09:14 -07002624void AudioFlinger::PlaybackThread::updateMetadata_l()
2625{
2626 // TODO: add volume support
2627 if (mOutput == nullptr || mOutput->stream == nullptr ||
2628 !mActiveTracks.readAndClearHasChanged()) {
2629 return;
2630 }
2631 StreamOutHalInterface::SourceMetadata metadata;
2632 for (const sp<Track> &track : mActiveTracks) {
2633 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocardb31f96f2018-04-03 09:00:09 -07002634 if (track->isOutputTrack()) {
2635 // TODO: OutputTrack (used for duplication) are currently not supported
2636 continue;
2637 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002638 metadata.tracks.push_back({
2639 .usage = track->attributes().usage,
2640 .content_type = track->attributes().content_type,
2641 .gain = 1,
2642 });
2643 }
2644 mOutput->stream->updateSourceMetadata(metadata);
2645}
Eric Laurent81784c32012-11-19 14:55:58 -08002646
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002647status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002648{
2649 if (halFrames == NULL || dspFrames == NULL) {
2650 return BAD_VALUE;
2651 }
2652 Mutex::Autolock _l(mLock);
2653 if (initCheck() != NO_ERROR) {
2654 return INVALID_OPERATION;
2655 }
Andy Hung818e7a32016-02-16 18:08:07 -08002656 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002657 *halFrames = framesWritten;
2658
2659 if (isSuspended()) {
2660 // return an estimation of rendered frames when the output is suspended
2661 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002662 *dspFrames = (uint32_t)
2663 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002664 return NO_ERROR;
2665 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002666 status_t status;
2667 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002668 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002669 *dspFrames = (size_t)frames;
2670 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002671 }
2672}
2673
Eric Laurent4c415062016-06-17 16:14:16 -07002674// hasAudioSession_l() must be called with ThreadBase::mLock held
2675uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002676{
Eric Laurent81784c32012-11-19 14:55:58 -08002677 uint32_t result = 0;
2678 if (getEffectChain_l(sessionId) != 0) {
2679 result = EFFECT_SESSION;
2680 }
2681
2682 for (size_t i = 0; i < mTracks.size(); ++i) {
2683 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002684 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002685 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002686 if (track->isFastTrack()) {
2687 result |= FAST_SESSION;
2688 }
Eric Laurent81784c32012-11-19 14:55:58 -08002689 break;
2690 }
2691 }
2692
2693 return result;
2694}
2695
Glenn Kastend848eb42016-03-08 13:42:11 -08002696uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002697{
2698 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2699 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2700 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2701 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2702 }
2703 for (size_t i = 0; i < mTracks.size(); i++) {
2704 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002705 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002706 return AudioSystem::getStrategyForStream(track->streamType());
2707 }
2708 }
2709 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2710}
2711
2712
Phil Burk062e67a2015-02-11 13:40:50 -08002713AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002714{
2715 Mutex::Autolock _l(mLock);
2716 return mOutput;
2717}
2718
Phil Burk062e67a2015-02-11 13:40:50 -08002719AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002720{
2721 Mutex::Autolock _l(mLock);
2722 AudioStreamOut *output = mOutput;
2723 mOutput = NULL;
2724 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2725 // must push a NULL and wait for ack
2726 mOutputSink.clear();
2727 mPipeSink.clear();
2728 mNormalSink.clear();
2729 return output;
2730}
2731
2732// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002733sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002734{
2735 if (mOutput == NULL) {
2736 return NULL;
2737 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002738 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002739}
2740
2741uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2742{
2743 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2744}
2745
2746status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2747{
2748 if (!isValidSyncEvent(event)) {
2749 return BAD_VALUE;
2750 }
2751
2752 Mutex::Autolock _l(mLock);
2753
2754 for (size_t i = 0; i < mTracks.size(); ++i) {
2755 sp<Track> track = mTracks[i];
2756 if (event->triggerSession() == track->sessionId()) {
2757 (void) track->setSyncEvent(event);
2758 return NO_ERROR;
2759 }
2760 }
2761
2762 return NAME_NOT_FOUND;
2763}
2764
2765bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2766{
2767 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2768}
2769
2770void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2771 const Vector< sp<Track> >& tracksToRemove)
2772{
2773 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002774 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002775 for (size_t i = 0 ; i < count ; i++) {
2776 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002777 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002778 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002779 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002780#ifdef ADD_BATTERY_DATA
2781 // to track the speaker usage
2782 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2783#endif
2784 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002785 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002786 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002787 }
Eric Laurent81784c32012-11-19 14:55:58 -08002788 }
2789 }
2790 }
Eric Laurent81784c32012-11-19 14:55:58 -08002791}
2792
2793void AudioFlinger::PlaybackThread::checkSilentMode_l()
2794{
2795 if (!mMasterMute) {
2796 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002797 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2798 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2799 return;
2800 }
Eric Laurent81784c32012-11-19 14:55:58 -08002801 if (property_get("ro.audio.silent", value, "0") > 0) {
2802 char *endptr;
2803 unsigned long ul = strtoul(value, &endptr, 0);
2804 if (*endptr == '\0' && ul != 0) {
2805 ALOGD("Silence is golden");
2806 // The setprop command will not allow a property to be changed after
2807 // the first time it is set, so we don't have to worry about un-muting.
2808 setMasterMute_l(true);
2809 }
2810 }
2811 }
2812}
2813
2814// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002815ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002816{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002817 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002818 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002820 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002821
2822 // If an NBAIO sink is present, use it to write the normal mixer's submix
2823 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002824
Andy Hung010a1a12014-03-13 13:57:33 -07002825 const size_t count = mBytesRemaining / mFrameSize;
2826
Simon Wilson2d590962012-11-29 15:18:50 -08002827 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002828 // update the setpoint when AudioFlinger::mScreenState changes
2829 uint32_t screenState = AudioFlinger::mScreenState;
2830 if (screenState != mScreenState) {
2831 mScreenState = screenState;
2832 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2833 if (pipe != NULL) {
2834 pipe->setAvgFrames((mScreenState & 1) ?
2835 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2836 }
2837 }
Andy Hung010a1a12014-03-13 13:57:33 -07002838 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002839 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002840 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002841 bytesWritten = framesWritten * mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002842 } else {
2843 bytesWritten = framesWritten;
2844 }
2845 // otherwise use the HAL / AudioStreamOut directly
2846 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002847 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002848
Eric Laurentbfb1b832013-01-07 09:53:42 -08002849 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002850 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2851 mWriteAckSequence += 2;
2852 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002853 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002854 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002855 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002856 // FIXME We should have an implementation of timestamps for direct output threads.
2857 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002858 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002859
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 if (mUseAsyncWrite &&
2861 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2862 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002863 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 }
Eric Laurent81784c32012-11-19 14:55:58 -08002867 }
2868
Eric Laurent81784c32012-11-19 14:55:58 -08002869 mNumWrites++;
2870 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002871 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 return bytesWritten;
2873}
2874
2875void AudioFlinger::PlaybackThread::threadLoop_drain()
2876{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002877 bool supportsDrain = false;
2878 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002879 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2880 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002881 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2882 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002884 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002885 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002886 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002887 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002888 }
2889}
2890
2891void AudioFlinger::PlaybackThread::threadLoop_exit()
2892{
Eric Laurent275e8e92014-11-30 15:14:47 -08002893 {
2894 Mutex::Autolock _l(mLock);
2895 for (size_t i = 0; i < mTracks.size(); i++) {
2896 sp<Track> track = mTracks[i];
2897 track->invalidate();
2898 }
Andy Hungdae27702016-10-31 14:01:16 -07002899 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2900 // After we exit there are no more track changes sent to BatteryNotifier
2901 // because that requires an active threadLoop.
2902 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2903 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002904 }
Eric Laurent81784c32012-11-19 14:55:58 -08002905}
2906
2907/*
2908The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002909 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002910 - mActiveSleepTimeUs from activeSleepTimeUs()
2911 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002912 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2913 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002914 - maxPeriod from frame count and sample rate (MIXER only)
2915
2916The parameters that affect these derived values are:
2917 - frame count
2918 - frame size
2919 - sample rate
2920 - device type: A2DP or not
2921 - device latency
2922 - format: PCM or not
2923 - active sleep time
2924 - idle sleep time
2925*/
2926
2927void AudioFlinger::PlaybackThread::cacheParameters_l()
2928{
Andy Hung25c2dac2014-02-27 14:56:00 -08002929 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002930 mActiveSleepTimeUs = activeSleepTimeUs();
2931 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002932
2933 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2934 // truncating audio when going to standby.
2935 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2936 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2937 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2938 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2939 }
2940 }
Eric Laurent81784c32012-11-19 14:55:58 -08002941}
2942
Eric Laurent13084622016-05-17 10:51:49 -07002943bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002944{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002945 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002946 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002947 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002948 size_t size = mTracks.size();
2949 for (size_t i = 0; i < size; i++) {
2950 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002951 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002952 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002953 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002954 }
2955 }
Eric Laurent13084622016-05-17 10:51:49 -07002956 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002957}
2958
Haynes Mathew George05317d22016-05-03 16:34:26 -07002959void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2960{
2961 Mutex::Autolock _l(mLock);
2962 invalidateTracks_l(streamType);
2963}
2964
Eric Laurent81784c32012-11-19 14:55:58 -08002965status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
2966{
Glenn Kastend848eb42016-03-08 13:42:11 -08002967 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08002968 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002969 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08002970 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
2971 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
2972 &halInBuffer);
2973 if (result != OK) return result;
2974 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07002975 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08002976 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08002977 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002978 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08002979 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08002980 if (mType != DIRECT) {
2981 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08002982 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07002983 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08002984 &halInBuffer);
2985 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07002986#ifdef FLOAT_EFFECT_CHAIN
2987 buffer = halInBuffer->audioBuffer()->f32;
2988#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08002989 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07002990#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08002991 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
2992 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08002993 }
2994
2995 // Attach all tracks with same session ID to this chain.
2996 for (size_t i = 0; i < mTracks.size(); ++i) {
2997 sp<Track> track = mTracks[i];
2998 if (session == track->sessionId()) {
2999 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3000 buffer);
3001 track->setMainBuffer(buffer);
3002 chain->incTrackCnt();
3003 }
3004 }
3005
3006 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003007 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003008 if (session == track->sessionId()) {
3009 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3010 chain->incActiveTrackCnt();
3011 }
3012 }
3013 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003014 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003015 chain->setInBuffer(halInBuffer);
3016 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003017 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003018 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003019 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3020 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003021 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003022 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003023 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003024 // Effect chain for other sessions are inserted at beginning of effect
3025 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003026 // sessions is not important.
3027 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3028 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3029 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003030 size_t size = mEffectChains.size();
3031 size_t i = 0;
3032 for (i = 0; i < size; i++) {
3033 if (mEffectChains[i]->sessionId() < session) {
3034 break;
3035 }
3036 }
3037 mEffectChains.insertAt(chain, i);
3038 checkSuspendOnAddEffectChain_l(chain);
3039
3040 return NO_ERROR;
3041}
3042
3043size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3044{
Glenn Kastend848eb42016-03-08 13:42:11 -08003045 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003046
3047 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3048
3049 for (size_t i = 0; i < mEffectChains.size(); i++) {
3050 if (chain == mEffectChains[i]) {
3051 mEffectChains.removeAt(i);
3052 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003053 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003054 if (session == track->sessionId()) {
3055 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3056 chain.get(), session);
3057 chain->decActiveTrackCnt();
3058 }
3059 }
3060
3061 // detach all tracks with same session ID from this chain
3062 for (size_t i = 0; i < mTracks.size(); ++i) {
3063 sp<Track> track = mTracks[i];
3064 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003065 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003066 chain->decTrackCnt();
3067 }
3068 }
3069 break;
3070 }
3071 }
3072 return mEffectChains.size();
3073}
3074
3075status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003076 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003077{
3078 Mutex::Autolock _l(mLock);
3079 return attachAuxEffect_l(track, EffectId);
3080}
3081
3082status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003083 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003084{
3085 status_t status = NO_ERROR;
3086
3087 if (EffectId == 0) {
3088 track->setAuxBuffer(0, NULL);
3089 } else {
3090 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3091 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3092 if (effect != 0) {
3093 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3094 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3095 } else {
3096 status = INVALID_OPERATION;
3097 }
3098 } else {
3099 status = BAD_VALUE;
3100 }
3101 }
3102 return status;
3103}
3104
3105void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3106{
3107 for (size_t i = 0; i < mTracks.size(); ++i) {
3108 sp<Track> track = mTracks[i];
3109 if (track->auxEffectId() == effectId) {
3110 attachAuxEffect_l(track, 0);
3111 }
3112 }
3113}
3114
3115bool AudioFlinger::PlaybackThread::threadLoop()
3116{
Glenn Kasten388d5712017-04-07 14:38:41 -07003117 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003118
Eric Laurent81784c32012-11-19 14:55:58 -08003119 Vector< sp<Track> > tracksToRemove;
3120
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003121 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003122 nsecs_t lastWriteFinished = -1; // time last server write completed
3123 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003124
3125 // MIXER
3126 nsecs_t lastWarning = 0;
3127
3128 // DUPLICATING
3129 // FIXME could this be made local to while loop?
3130 writeFrames = 0;
3131
3132 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003133 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003134
3135 if (mType == MIXER) {
3136 sleepTimeShift = 0;
3137 }
3138
3139 CpuStats cpuStats;
3140 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3141
3142 acquireWakeLock();
3143
Glenn Kasteneef598c2017-04-03 14:41:13 -07003144 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3145 // thread associated with this PlaybackThread.
3146 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3147 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003148 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3149 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003150 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003151 const char *logString = NULL;
3152
rago1bb90822017-05-02 18:31:48 -07003153 // Estimated time for next buffer to be written to hal. This is used only on
3154 // suspended mode (for now) to help schedule the wait time until next iteration.
3155 nsecs_t timeLoopNextNs = 0;
3156
Eric Laurent664539d2013-09-23 18:24:31 -07003157 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003158
Eric Laurent81784c32012-11-19 14:55:58 -08003159 while (!exitPending())
3160 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003161 // Log merge requests are performed during AudioFlinger binder transactions, but
3162 // that does not cover audio playback. It's requested here for that reason.
3163 mAudioFlinger->requestLogMerge();
3164
Eric Laurent81784c32012-11-19 14:55:58 -08003165 cpuStats.sample(myName);
3166
3167 Vector< sp<EffectChain> > effectChains;
3168
Eric Laurent81784c32012-11-19 14:55:58 -08003169 { // scope for mLock
3170
3171 Mutex::Autolock _l(mLock);
3172
Eric Laurent021cf962014-05-13 10:18:14 -07003173 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003174
Glenn Kasteneef598c2017-04-03 14:41:13 -07003175 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003176 if (logString != NULL) {
3177 mNBLogWriter->logTimestamp();
3178 mNBLogWriter->log(logString);
3179 logString = NULL;
3180 }
3181
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003182 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003183 // and associate with the sink frames written out. We need
3184 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003185 bool kernelLocationUpdate = false;
Andy Hunge10393e2015-06-12 13:59:33 -07003186 if (mNormalSink != 0) {
Andy Hungc54b1ff2016-02-23 14:07:07 -08003187 // Note: The DuplicatingThread may not have a mNormalSink.
Andy Hung818e7a32016-02-16 18:08:07 -08003188 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003189 // sink will block while writing.
Andy Hung818e7a32016-02-16 18:08:07 -08003190 ExtendedTimestamp timestamp; // use private copy to fetch
3191 (void) mNormalSink->getTimestamp(timestamp);
Andy Hung6d7b1192016-05-07 22:59:48 -07003192
3193 // We keep track of the last valid kernel position in case we are in underrun
3194 // and the normal mixer period is the same as the fast mixer period, or there
3195 // is some error from the HAL.
3196 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3197 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3198 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3199 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3200 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3201
3202 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3203 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3204 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3205 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003206 }
3207
3208 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3209 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003210 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003211 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003212 }
3213
Andy Hung818e7a32016-02-16 18:08:07 -08003214 // copy over kernel info
3215 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003216 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3217 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003218 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3219 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hungc54b1ff2016-02-23 14:07:07 -08003220 }
3221 // mFramesWritten for non-offloaded tracks are contiguous
3222 // even after standby() is called. This is useful for the track frame
3223 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003224 bool serverLocationUpdate = false;
3225 if (mFramesWritten != lastFramesWritten) {
3226 serverLocationUpdate = true;
3227 lastFramesWritten = mFramesWritten;
3228 }
3229 // Only update timestamps if there is a meaningful change.
3230 // Either the kernel timestamp must be valid or we have written something.
3231 if (kernelLocationUpdate || serverLocationUpdate) {
3232 if (serverLocationUpdate) {
3233 // use the time before we called the HAL write - it is a bit more accurate
3234 // to when the server last read data than the current time here.
3235 //
3236 // If we haven't written anything, mLastWriteTime will be -1
3237 // and we use systemTime().
3238 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3239 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3240 ? systemTime() : mLastWriteTime;
3241 }
Andy Hungdae27702016-10-31 14:01:16 -07003242
3243 for (const sp<Track> &t : mActiveTracks) {
3244 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003245 t->updateTrackFrameInfo(
3246 t->mAudioTrackServerProxy->framesReleased(),
3247 mFramesWritten,
3248 mTimestamp);
3249 }
Andy Hunge10393e2015-06-12 13:59:33 -07003250 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003251 }
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003252#if 0
3253 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003254 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003255 timespec ts;
3256 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003257 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003258 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003259 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003260 }
3261 ++z;
3262#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003263 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003264 if (mSignalPending) {
3265 // A signal was raised while we were unlocked
3266 mSignalPending = false;
3267 } else if (waitingAsyncCallback_l()) {
3268 if (exitPending()) {
3269 break;
3270 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003271 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003272 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003273 releaseWakeLock_l();
3274 released = true;
3275 }
Andy Hung10cbff12017-02-21 17:30:14 -08003276
3277 const int64_t waitNs = computeWaitTimeNs_l();
3278 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3279 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3280 if (status == TIMED_OUT) {
3281 mSignalPending = true; // if timeout recheck everything
3282 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003283 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003284 if (released) {
3285 acquireWakeLock_l();
3286 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003287 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3288 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003289
3290 continue;
3291 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003292 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 isSuspended()) {
3294 // put audio hardware into standby after short delay
3295 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003296
3297 threadLoop_standby();
3298
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003299 // This is where we go into standby
3300 if (!mStandby) {
3301 LOG_AUDIO_STATE();
3302 }
Eric Laurent81784c32012-11-19 14:55:58 -08003303 mStandby = true;
3304 }
3305
3306 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3307 // we're about to wait, flush the binder command buffer
3308 IPCThreadState::self()->flushCommands();
3309
3310 clearOutputTracks();
3311
3312 if (exitPending()) {
3313 break;
3314 }
3315
3316 releaseWakeLock_l();
3317 // wait until we have something to do...
3318 ALOGV("%s going to sleep", myName.string());
3319 mWaitWorkCV.wait(mLock);
3320 ALOGV("%s waking up", myName.string());
3321 acquireWakeLock_l();
3322
3323 mMixerStatus = MIXER_IDLE;
3324 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3325 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003326 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003327 checkSilentMode_l();
3328
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003329 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3330 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003331 if (mType == MIXER) {
3332 sleepTimeShift = 0;
3333 }
3334
3335 continue;
3336 }
3337 }
Eric Laurent81784c32012-11-19 14:55:58 -08003338 // mMixerStatusIgnoringFastTracks is also updated internally
3339 mMixerStatus = prepareTracks_l(&tracksToRemove);
3340
Andy Hungdae27702016-10-31 14:01:16 -07003341 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003342
Kevin Rocard069c2712018-03-29 19:09:14 -07003343 updateMetadata_l();
3344
Eric Laurent81784c32012-11-19 14:55:58 -08003345 // prevent any changes in effect chain list and in each effect chain
3346 // during mixing and effect process as the audio buffers could be deleted
3347 // or modified if an effect is created or deleted
3348 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003349 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003350
Eric Laurentbfb1b832013-01-07 09:53:42 -08003351 if (mBytesRemaining == 0) {
3352 mCurrentWriteLength = 0;
3353 if (mMixerStatus == MIXER_TRACKS_READY) {
3354 // threadLoop_mix() sets mCurrentWriteLength
3355 threadLoop_mix();
3356 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3357 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003358 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003359 // must be written to HAL
3360 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003361 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003362 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003363 }
3364 }
Andy Hung98ef9782014-03-04 14:46:50 -08003365 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003366 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003367 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3368 // or mSinkBuffer (if there are no effects).
3369 //
3370 // This is done pre-effects computation; if effects change to
3371 // support higher precision, this needs to move.
3372 //
3373 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003374 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003375 if (mMixerBufferValid) {
3376 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3377 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3378
Andy Hung2ddee192015-12-18 17:34:44 -08003379 // mono blend occurs for mixer threads only (not direct or offloaded)
3380 // and is handled here if we're going directly to the sink.
3381 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003382 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3383 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003384 }
3385
Andy Hung98ef9782014-03-04 14:46:50 -08003386 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3387 mNormalFrameCount * mChannelCount);
3388 }
3389
Eric Laurentbfb1b832013-01-07 09:53:42 -08003390 mBytesRemaining = mCurrentWriteLength;
3391 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003392 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3393 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3394 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3395 mBytesWritten += mBytesRemaining;
3396 mFramesWritten += framesRemaining;
3397 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003398 mBytesRemaining = 0;
3399 }
Eric Laurent81784c32012-11-19 14:55:58 -08003400
Eric Laurentbfb1b832013-01-07 09:53:42 -08003401 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003402 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003403 for (size_t i = 0; i < effectChains.size(); i ++) {
3404 effectChains[i]->process_l();
3405 }
Eric Laurent81784c32012-11-19 14:55:58 -08003406 }
3407 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003408 // Process effect chains for offloaded thread even if no audio
3409 // was read from audio track: process only updates effect state
3410 // and thus does have to be synchronized with audio writes but may have
3411 // to be called while waiting for async write callback
3412 if (mType == OFFLOAD) {
3413 for (size_t i = 0; i < effectChains.size(); i ++) {
3414 effectChains[i]->process_l();
3415 }
3416 }
Eric Laurent81784c32012-11-19 14:55:58 -08003417
Andy Hung98ef9782014-03-04 14:46:50 -08003418 // Only if the Effects buffer is enabled and there is data in the
3419 // Effects buffer (buffer valid), we need to
3420 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003421 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003422 if (mEffectBufferValid) {
3423 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003424
3425 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003426 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3427 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003428 }
3429
Andy Hung98ef9782014-03-04 14:46:50 -08003430 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3431 mNormalFrameCount * mChannelCount);
3432 }
3433
Eric Laurent81784c32012-11-19 14:55:58 -08003434 // enable changes in effect chain
3435 unlockEffectChains(effectChains);
3436
Eric Laurentbfb1b832013-01-07 09:53:42 -08003437 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003438 // mSleepTimeUs == 0 means we must write to audio hardware
3439 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003440 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003441 // We save lastWriteFinished here, as previousLastWriteFinished,
3442 // for throttling. On thread start, previousLastWriteFinished will be
3443 // set to -1, which properly results in no throttling after the first write.
3444 nsecs_t previousLastWriteFinished = lastWriteFinished;
3445 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003447 // FIXME rewrite to reduce number of system calls
3448 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003449 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003450 lastWriteFinished = systemTime();
3451 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003452 if (ret < 0) {
3453 mBytesRemaining = 0;
3454 } else {
3455 mBytesWritten += ret;
3456 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003457 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003458 }
3459 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3460 (mMixerStatus == MIXER_DRAIN_ALL)) {
3461 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003462 }
Andy Hung08fb1742015-05-31 23:22:10 -07003463 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003464 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003465 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003466 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003467 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003468 ATRACE_NAME("underrun");
3469 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003470 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003471 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003472 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003473 }
Andy Hung08fb1742015-05-31 23:22:10 -07003474
3475 if (mThreadThrottle
3476 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3477 && ret > 0) { // we wrote something
3478 // Limit MixerThread data processing to no more than twice the
3479 // expected processing rate.
3480 //
3481 // This helps prevent underruns with NuPlayer and other applications
3482 // which may set up buffers that are close to the minimum size, or use
3483 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3484 //
3485 // The throttle smooths out sudden large data drains from the device,
3486 // e.g. when it comes out of standby, which often causes problems with
3487 // (1) mixer threads without a fast mixer (which has its own warm-up)
3488 // (2) minimum buffer sized tracks (even if the track is full,
3489 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003490 //
3491 // Total time spent in last processing cycle equals time spent in
3492 // 1. threadLoop_write, as well as time spent in
3493 // 2. threadLoop_mix (significant for heavy mixing, especially
3494 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003495
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003496 // it's OK if deltaMs (and deltaNs) is an overestimate.
3497 nsecs_t deltaNs;
3498 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3499 __builtin_sub_overflow(
3500 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3501 const int32_t deltaMs = deltaNs / 1000000;
3502
Ivan Lozanoea04d392017-11-07 14:37:07 -08003503 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003504 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3505 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003506 // notify of throttle start on verbose log
3507 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3508 "mixer(%p) throttle begin:"
3509 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003510 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003511 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003512 // Throttle must be attributed to the previous mixer loop's write time
3513 // to allow back-to-back throttling.
3514 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003515 } else {
3516 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3517 if (diff > 0) {
3518 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003519 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003520 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3521 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003522 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003523 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3524 }
Andy Hung08fb1742015-05-31 23:22:10 -07003525 }
3526 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003527 }
Eric Laurent81784c32012-11-19 14:55:58 -08003528
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003530 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003531 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003532 // suspended requires accurate metering of sleep time.
3533 if (isSuspended()) {
3534 // advance by expected sleepTime
3535 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3536 const nsecs_t nowNs = systemTime();
3537
3538 // compute expected next time vs current time.
3539 // (negative deltas are treated as delays).
3540 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3541 if (deltaNs < -kMaxNextBufferDelayNs) {
3542 // Delays longer than the max allowed trigger a reset.
3543 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3544 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3545 timeLoopNextNs = nowNs + deltaNs;
3546 } else if (deltaNs < 0) {
3547 // Delays within the max delay allowed: zero the delta/sleepTime
3548 // to help the system catch up in the next iteration(s)
3549 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3550 deltaNs = 0;
3551 }
3552 // update sleep time (which is >= 0)
3553 mSleepTimeUs = deltaNs / 1000;
3554 }
Eric Laurente93cc032016-05-05 10:15:10 -07003555 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3556 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003557 }
Glenn Kastene7754022014-10-31 12:11:26 -07003558 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 }
Eric Laurent81784c32012-11-19 14:55:58 -08003560 }
3561
3562 // Finally let go of removed track(s), without the lock held
3563 // since we can't guarantee the destructors won't acquire that
3564 // same lock. This will also mutate and push a new fast mixer state.
3565 threadLoop_removeTracks(tracksToRemove);
3566 tracksToRemove.clear();
3567
3568 // FIXME I don't understand the need for this here;
3569 // it was in the original code but maybe the
3570 // assignment in saveOutputTracks() makes this unnecessary?
3571 clearOutputTracks();
3572
3573 // Effect chains will be actually deleted here if they were removed from
3574 // mEffectChains list during mixing or effects processing
3575 effectChains.clear();
3576
3577 // FIXME Note that the above .clear() is no longer necessary since effectChains
3578 // is now local to this block, but will keep it for now (at least until merge done).
3579 }
3580
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 threadLoop_exit();
3582
Eric Laurentcf817a22014-08-04 20:36:31 -07003583 if (!mStandby) {
3584 threadLoop_standby();
3585 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003586 }
3587
3588 releaseWakeLock();
3589
3590 ALOGV("Thread %p type %d exiting", this, mType);
3591 return false;
3592}
3593
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594// removeTracks_l() must be called with ThreadBase::mLock held
3595void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3596{
3597 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003598 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003599 for (size_t i=0 ; i<count ; i++) {
3600 const sp<Track>& track = tracksToRemove.itemAt(i);
3601 mActiveTracks.remove(track);
3602 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3603 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3604 if (chain != 0) {
3605 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3606 track->sessionId());
3607 chain->decActiveTrackCnt();
3608 }
3609 if (track->isTerminated()) {
3610 removeTrack_l(track);
3611 }
3612 }
3613 }
3614
3615}
Eric Laurent81784c32012-11-19 14:55:58 -08003616
Eric Laurentaccc1472013-09-20 09:36:34 -07003617status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3618{
3619 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003620 ExtendedTimestamp ets;
3621 status_t status = mNormalSink->getTimestamp(ets);
3622 if (status == NO_ERROR) {
3623 status = ets.getBestTimestamp(&timestamp);
3624 }
3625 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003626 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003627 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003628 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003629 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003630 timestamp.mPosition = (uint32_t)position64;
3631 return NO_ERROR;
3632 }
3633 }
3634 return INVALID_OPERATION;
3635}
Eric Laurent1c333e22014-05-20 10:48:17 -07003636
Eric Laurent054d9d32015-04-24 08:48:48 -07003637status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3638 audio_patch_handle_t *handle)
3639{
Andy Hungf60abce2016-08-26 11:37:54 -07003640 status_t status;
3641 if (property_get_bool("af.patch_park", false /* default_value */)) {
3642 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3643 // or if HAL does not properly lock against access.
3644 AutoPark<FastMixer> park(mFastMixer);
3645 status = PlaybackThread::createAudioPatch_l(patch, handle);
3646 } else {
3647 status = PlaybackThread::createAudioPatch_l(patch, handle);
3648 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003649 return status;
3650}
3651
Eric Laurent1c333e22014-05-20 10:48:17 -07003652status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3653 audio_patch_handle_t *handle)
3654{
3655 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003656
3657 // store new device and send to effects
3658 audio_devices_t type = AUDIO_DEVICE_NONE;
3659 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3660 type |= patch->sinks[i].ext.device.type;
3661 }
3662
3663#ifdef ADD_BATTERY_DATA
3664 // when changing the audio output device, call addBatteryData to notify
3665 // the change
3666 if (mOutDevice != type) {
3667 uint32_t params = 0;
3668 // check whether speaker is on
3669 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3670 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003671 }
3672
Eric Laurent054d9d32015-04-24 08:48:48 -07003673 audio_devices_t deviceWithoutSpeaker
3674 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3675 // check if any other device (except speaker) is on
3676 if (type & deviceWithoutSpeaker) {
3677 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3678 }
3679
3680 if (params != 0) {
3681 addBatteryData(params);
3682 }
3683 }
3684#endif
3685
3686 for (size_t i = 0; i < mEffectChains.size(); i++) {
3687 mEffectChains[i]->setDevice_l(type);
3688 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003689
3690 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3691 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3692 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003693 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003694 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003695
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003696 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003697 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3698 status = hwDevice->createAudioPatch(patch->num_sources,
3699 patch->sources,
3700 patch->num_sinks,
3701 patch->sinks,
3702 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003703 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003704 char *address;
3705 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3706 //FIXME: we only support address on first sink with HAL version < 3.0
3707 address = audio_device_address_to_parameter(
3708 patch->sinks[0].ext.device.type,
3709 patch->sinks[0].ext.device.address);
3710 } else {
3711 address = (char *)calloc(1, 1);
3712 }
3713 AudioParameter param = AudioParameter(String8(address));
3714 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003715 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003716 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003717 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003718 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003719 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003720 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003721 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3722 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003723 return status;
3724}
3725
Eric Laurent054d9d32015-04-24 08:48:48 -07003726status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3727{
Andy Hungf60abce2016-08-26 11:37:54 -07003728 status_t status;
3729 if (property_get_bool("af.patch_park", false /* default_value */)) {
3730 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3731 // or if HAL does not properly lock against access.
3732 AutoPark<FastMixer> park(mFastMixer);
3733 status = PlaybackThread::releaseAudioPatch_l(handle);
3734 } else {
3735 status = PlaybackThread::releaseAudioPatch_l(handle);
3736 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003737 return status;
3738}
3739
Eric Laurent1c333e22014-05-20 10:48:17 -07003740status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3741{
3742 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003743
3744 mOutDevice = AUDIO_DEVICE_NONE;
3745
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003746 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003747 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3748 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003749 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003750 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003751 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003752 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003753 }
3754 return status;
3755}
3756
Eric Laurent83b88082014-06-20 18:31:16 -07003757void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3758{
3759 Mutex::Autolock _l(mLock);
3760 mTracks.add(track);
3761}
3762
3763void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3764{
3765 Mutex::Autolock _l(mLock);
3766 destroyTrack_l(track);
3767}
3768
3769void AudioFlinger::PlaybackThread::getAudioPortConfig(struct audio_port_config *config)
3770{
3771 ThreadBase::getAudioPortConfig(config);
3772 config->role = AUDIO_PORT_ROLE_SOURCE;
3773 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3774 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
3775}
3776
Eric Laurent81784c32012-11-19 14:55:58 -08003777// ----------------------------------------------------------------------------
3778
3779AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003780 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3781 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003782 // mAudioMixer below
3783 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003784 mFastMixerFutex(0),
3785 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003786 // mOutputSink below
3787 // mPipeSink below
3788 // mNormalSink below
3789{
3790 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003791 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003792 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003793 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3794 mNormalFrameCount);
3795 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3796
Andy Hungfbfc3952015-01-15 13:33:51 -08003797 if (type == DUPLICATING) {
3798 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3799 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3800 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3801 return;
3802 }
Eric Laurent81784c32012-11-19 14:55:58 -08003803 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003804 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003805 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003806 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003807#if !LOG_NDEBUG
3808 ssize_t index =
3809#else
3810 (void)
3811#endif
3812 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003813 ALOG_ASSERT(index == 0);
3814
3815 // initialize fast mixer depending on configuration
3816 bool initFastMixer;
3817 switch (kUseFastMixer) {
3818 case FastMixer_Never:
3819 initFastMixer = false;
3820 break;
3821 case FastMixer_Always:
3822 initFastMixer = true;
3823 break;
3824 case FastMixer_Static:
3825 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003826 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3827 // where the period is less than an experimentally determined threshold that can be
3828 // scheduled reliably with CFS. However, the BT A2DP HAL is
3829 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3830 initFastMixer = mFrameCount < mNormalFrameCount
3831 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003832 break;
3833 }
Andy Hungfda69402017-02-15 14:33:12 -08003834 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3835 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3836 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003837 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003838 audio_format_t fastMixerFormat;
3839 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3840 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3841 } else {
3842 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3843 }
3844 if (mFormat != fastMixerFormat) {
3845 // change our Sink format to accept our intermediate precision
3846 mFormat = fastMixerFormat;
3847 free(mSinkBuffer);
3848 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3849 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3850 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3851 }
Eric Laurent81784c32012-11-19 14:55:58 -08003852
3853 // create a MonoPipe to connect our submix to FastMixer
3854 NBAIO_Format format = mOutputSink->format();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003855#ifdef TEE_SINK
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003856 NBAIO_Format origformat = format;
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003857#endif
Andy Hung1258c1a2014-05-23 21:22:17 -07003858 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003859 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003860 format.mFormat = fastMixerFormat;
3861 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3862
Eric Laurent81784c32012-11-19 14:55:58 -08003863 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3864 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3865 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3866 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3867 const NBAIO_Format offers[1] = {format};
3868 size_t numCounterOffers = 0;
Glenn Kastenfc302fd2016-04-11 14:11:26 -07003869#if !LOG_NDEBUG || defined(TEE_SINK)
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003870 ssize_t index =
3871#else
3872 (void)
3873#endif
3874 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003875 ALOG_ASSERT(index == 0);
3876 monoPipe->setAvgFrames((mScreenState & 1) ?
3877 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3878 mPipeSink = monoPipe;
3879
Glenn Kasten46909e72013-02-26 09:20:22 -08003880#ifdef TEE_SINK
Glenn Kastenda6ef132013-01-10 12:31:01 -08003881 if (mTeeSinkOutputEnabled) {
3882 // create a Pipe to archive a copy of FastMixer's output for dumpsys
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003883 Pipe *teeSink = new Pipe(mTeeSinkOutputFrames, origformat);
3884 const NBAIO_Format offers2[1] = {origformat};
Glenn Kastenda6ef132013-01-10 12:31:01 -08003885 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003886 index = teeSink->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003887 ALOG_ASSERT(index == 0);
3888 mTeeSink = teeSink;
3889 PipeReader *teeSource = new PipeReader(*teeSink);
3890 numCounterOffers = 0;
Glenn Kastenba0b34c2014-09-28 13:06:06 -07003891 index = teeSource->negotiate(offers2, 1, NULL, numCounterOffers);
Glenn Kastenda6ef132013-01-10 12:31:01 -08003892 ALOG_ASSERT(index == 0);
3893 mTeeSource = teeSource;
3894 }
Glenn Kasten46909e72013-02-26 09:20:22 -08003895#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003896
3897 // create fast mixer and configure it initially with just one fast track for our submix
3898 mFastMixer = new FastMixer();
3899 FastMixerStateQueue *sq = mFastMixer->sq();
3900#ifdef STATE_QUEUE_DUMP
3901 sq->setObserverDump(&mStateQueueObserverDump);
3902 sq->setMutatorDump(&mStateQueueMutatorDump);
3903#endif
3904 FastMixerState *state = sq->begin();
3905 FastTrack *fastTrack = &state->mFastTracks[0];
3906 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3907 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3908 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003909 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3910 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003911 fastTrack->mGeneration++;
3912 state->mFastTracksGen++;
3913 state->mTrackMask = 1;
3914 // fast mixer will use the HAL output sink
3915 state->mOutputSink = mOutputSink.get();
3916 state->mOutputSinkGen++;
3917 state->mFrameCount = mFrameCount;
3918 state->mCommand = FastMixerState::COLD_IDLE;
3919 // already done in constructor initialization list
3920 //mFastMixerFutex = 0;
3921 state->mColdFutexAddr = &mFastMixerFutex;
3922 state->mColdGen++;
3923 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten46909e72013-02-26 09:20:22 -08003924#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08003925 state->mTeeSink = mTeeSink.get();
Glenn Kasten46909e72013-02-26 09:20:22 -08003926#endif
Glenn Kasten9e58b552013-01-18 15:09:48 -08003927 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3928 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003929 sq->end();
3930 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3931
3932 // start the fast mixer
3933 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3934 pid_t tid = mFastMixer->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003935 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003936 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003937
3938#ifdef AUDIO_WATCHDOG
3939 // create and start the watchdog
3940 mAudioWatchdog = new AudioWatchdog();
3941 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3942 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3943 tid = mAudioWatchdog->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07003944 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003945#endif
3946
Eric Laurent81784c32012-11-19 14:55:58 -08003947 }
3948
3949 switch (kUseFastMixer) {
3950 case FastMixer_Never:
3951 case FastMixer_Dynamic:
3952 mNormalSink = mOutputSink;
3953 break;
3954 case FastMixer_Always:
3955 mNormalSink = mPipeSink;
3956 break;
3957 case FastMixer_Static:
3958 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3959 break;
3960 }
3961}
3962
3963AudioFlinger::MixerThread::~MixerThread()
3964{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003965 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003966 FastMixerStateQueue *sq = mFastMixer->sq();
3967 FastMixerState *state = sq->begin();
3968 if (state->mCommand == FastMixerState::COLD_IDLE) {
3969 int32_t old = android_atomic_inc(&mFastMixerFutex);
3970 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07003971 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08003972 }
3973 }
3974 state->mCommand = FastMixerState::EXIT;
3975 sq->end();
3976 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3977 mFastMixer->join();
3978 // Though the fast mixer thread has exited, it's state queue is still valid.
3979 // We'll use that extract the final state which contains one remaining fast track
3980 // corresponding to our sub-mix.
3981 state = sq->begin();
3982 ALOG_ASSERT(state->mTrackMask == 1);
3983 FastTrack *fastTrack = &state->mFastTracks[0];
3984 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
3985 delete fastTrack->mBufferProvider;
3986 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003987 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08003988#ifdef AUDIO_WATCHDOG
3989 if (mAudioWatchdog != 0) {
3990 mAudioWatchdog->requestExit();
3991 mAudioWatchdog->requestExitAndWait();
3992 mAudioWatchdog.clear();
3993 }
3994#endif
3995 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08003996 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08003997 delete mAudioMixer;
3998}
3999
4000
4001uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4002{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004003 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004004 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4005 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4006 }
4007 return latency;
4008}
4009
4010
4011void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4012{
4013 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4014}
4015
Eric Laurentbfb1b832013-01-07 09:53:42 -08004016ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004017{
4018 // FIXME we should only do one push per cycle; confirm this is true
4019 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004020 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004021 FastMixerStateQueue *sq = mFastMixer->sq();
4022 FastMixerState *state = sq->begin();
4023 if (state->mCommand != FastMixerState::MIX_WRITE &&
4024 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4025 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004026
4027 // FIXME workaround for first HAL write being CPU bound on some devices
4028 ATRACE_BEGIN("write");
4029 mOutput->write((char *)mSinkBuffer, 0);
4030 ATRACE_END();
4031
Eric Laurent81784c32012-11-19 14:55:58 -08004032 int32_t old = android_atomic_inc(&mFastMixerFutex);
4033 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004034 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004035 }
4036#ifdef AUDIO_WATCHDOG
4037 if (mAudioWatchdog != 0) {
4038 mAudioWatchdog->resume();
4039 }
4040#endif
4041 }
4042 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004043#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004044 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004045 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004046#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004047 sq->end();
4048 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4049 if (kUseFastMixer == FastMixer_Dynamic) {
4050 mNormalSink = mPipeSink;
4051 }
4052 } else {
4053 sq->end(false /*didModify*/);
4054 }
4055 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004056 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004057}
4058
4059void AudioFlinger::MixerThread::threadLoop_standby()
4060{
4061 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004062 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004063 FastMixerStateQueue *sq = mFastMixer->sq();
4064 FastMixerState *state = sq->begin();
4065 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004066 // Report any frames trapped in the Monopipe
4067 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4068 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4069 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4070 "monoPipeWritten:%lld monoPipeLeft:%lld",
4071 (long long)mFramesWritten, (long long)mSuspendedFrames,
4072 (long long)mPipeSink->framesWritten(), pipeFrames);
4073 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4074
Eric Laurent81784c32012-11-19 14:55:58 -08004075 state->mCommand = FastMixerState::COLD_IDLE;
4076 state->mColdFutexAddr = &mFastMixerFutex;
4077 state->mColdGen++;
4078 mFastMixerFutex = 0;
4079 sq->end();
4080 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4081 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4082 if (kUseFastMixer == FastMixer_Dynamic) {
4083 mNormalSink = mOutputSink;
4084 }
4085#ifdef AUDIO_WATCHDOG
4086 if (mAudioWatchdog != 0) {
4087 mAudioWatchdog->pause();
4088 }
4089#endif
4090 } else {
4091 sq->end(false /*didModify*/);
4092 }
4093 }
4094 PlaybackThread::threadLoop_standby();
4095}
4096
Eric Laurentbfb1b832013-01-07 09:53:42 -08004097bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4098{
4099 return false;
4100}
4101
4102bool AudioFlinger::PlaybackThread::shouldStandby_l()
4103{
4104 return !mStandby;
4105}
4106
4107bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4108{
4109 Mutex::Autolock _l(mLock);
4110 return waitingAsyncCallback_l();
4111}
4112
Eric Laurent81784c32012-11-19 14:55:58 -08004113// shared by MIXER and DIRECT, overridden by DUPLICATING
4114void AudioFlinger::PlaybackThread::threadLoop_standby()
4115{
4116 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004117 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004118 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004119 // discard any pending drain or write ack by incrementing sequence
4120 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4121 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004122 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004123 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4124 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004125 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004126 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004127}
4128
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004129void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4130{
4131 ALOGV("signal playback thread");
4132 broadcast_l();
4133}
4134
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004135void AudioFlinger::PlaybackThread::onAsyncError()
4136{
4137 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4138 invalidateTracks((audio_stream_type_t)i);
4139 }
4140}
4141
Eric Laurent81784c32012-11-19 14:55:58 -08004142void AudioFlinger::MixerThread::threadLoop_mix()
4143{
Eric Laurent81784c32012-11-19 14:55:58 -08004144 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004145 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004146 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004147 // increase sleep time progressively when application underrun condition clears.
4148 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4149 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4150 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004151 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004152 sleepTimeShift--;
4153 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004154 mSleepTimeUs = 0;
4155 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004156 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004157
Eric Laurent81784c32012-11-19 14:55:58 -08004158}
4159
4160void AudioFlinger::MixerThread::threadLoop_sleepTime()
4161{
4162 // If no tracks are ready, sleep once for the duration of an output
4163 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004164 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004165 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004166 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4167 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4168 mSleepTimeUs = kMinThreadSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004169 }
4170 // reduce sleep time in case of consecutive application underruns to avoid
4171 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4172 // duration we would end up writing less data than needed by the audio HAL if
4173 // the condition persists.
4174 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4175 sleepTimeShift++;
4176 }
4177 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004178 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004179 }
4180 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004181 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4182 // before effects processing or output.
4183 if (mMixerBufferValid) {
4184 memset(mMixerBuffer, 0, mMixerBufferSize);
4185 } else {
4186 memset(mSinkBuffer, 0, mSinkBufferSize);
4187 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004188 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004189 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4190 "anticipated start");
4191 }
4192 // TODO add standby time extension fct of effect tail
4193}
4194
4195// prepareTracks_l() must be called with ThreadBase::mLock held
4196AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4197 Vector< sp<Track> > *tracksToRemove)
4198{
Andy Hung1bc088a2018-02-09 15:57:31 -08004199 // clean up deleted track names in AudioMixer before allocating new tracks
4200 (void)mTracks.processDeletedTrackNames([this](int name) {
4201 // for each name, destroy it in the AudioMixer
4202 if (mAudioMixer->exists(name)) {
4203 mAudioMixer->destroy(name);
4204 }
4205 });
4206 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004207
4208 mixer_state mixerStatus = MIXER_IDLE;
4209 // find out which tracks need to be processed
4210 size_t count = mActiveTracks.size();
4211 size_t mixedTracks = 0;
4212 size_t tracksWithEffect = 0;
4213 // counts only _active_ fast tracks
4214 size_t fastTracks = 0;
4215 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4216
4217 float masterVolume = mMasterVolume;
4218 bool masterMute = mMasterMute;
4219
4220 if (masterMute) {
4221 masterVolume = 0;
4222 }
4223 // Delegate master volume control to effect in output mix effect chain if needed
4224 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4225 if (chain != 0) {
4226 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4227 chain->setVolume_l(&v, &v);
4228 masterVolume = (float)((v + (1 << 23)) >> 24);
4229 chain.clear();
4230 }
4231
4232 // prepare a new state to push
4233 FastMixerStateQueue *sq = NULL;
4234 FastMixerState *state = NULL;
4235 bool didModify = false;
4236 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004237 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004238 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004239 sq = mFastMixer->sq();
4240 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004241 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004242 }
4243
Andy Hung69aed5f2014-02-25 17:24:40 -08004244 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004245 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004246
Eric Laurent81784c32012-11-19 14:55:58 -08004247 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004248 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004249
4250 // this const just means the local variable doesn't change
4251 Track* const track = t.get();
4252
4253 // process fast tracks
4254 if (track->isFastTrack()) {
4255
4256 // It's theoretically possible (though unlikely) for a fast track to be created
4257 // and then removed within the same normal mix cycle. This is not a problem, as
4258 // the track never becomes active so it's fast mixer slot is never touched.
4259 // The converse, of removing an (active) track and then creating a new track
4260 // at the identical fast mixer slot within the same normal mix cycle,
4261 // is impossible because the slot isn't marked available until the end of each cycle.
4262 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004263 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004264 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4265 FastTrack *fastTrack = &state->mFastTracks[j];
4266
4267 // Determine whether the track is currently in underrun condition,
4268 // and whether it had a recent underrun.
4269 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4270 FastTrackUnderruns underruns = ftDump->mUnderruns;
4271 uint32_t recentFull = (underruns.mBitFields.mFull -
4272 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4273 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4274 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4275 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4276 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4277 uint32_t recentUnderruns = recentPartial + recentEmpty;
4278 track->mObservedUnderruns = underruns;
4279 // don't count underruns that occur while stopping or pausing
4280 // or stopped which can occur when flush() is called while active
Glenn Kasten82aaf942013-07-17 16:05:07 -07004281 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4282 recentUnderruns > 0) {
4283 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
4284 track->mAudioTrackServerProxy->tallyUnderrunFrames(recentUnderruns * mFrameCount);
Phil Burk2812d9e2016-01-04 10:34:30 -08004285 } else {
4286 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Eric Laurent81784c32012-11-19 14:55:58 -08004287 }
4288
4289 // This is similar to the state machine for normal tracks,
4290 // with a few modifications for fast tracks.
4291 bool isActive = true;
4292 switch (track->mState) {
4293 case TrackBase::STOPPING_1:
4294 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004295 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004296 track->mState = TrackBase::STOPPING_2;
4297 }
4298 break;
4299 case TrackBase::PAUSING:
4300 // ramp down is not yet implemented
4301 track->setPaused();
4302 break;
4303 case TrackBase::RESUMING:
4304 // ramp up is not yet implemented
4305 track->mState = TrackBase::ACTIVE;
4306 break;
4307 case TrackBase::ACTIVE:
4308 if (recentFull > 0 || recentPartial > 0) {
4309 // track has provided at least some frames recently: reset retry count
4310 track->mRetryCount = kMaxTrackRetries;
4311 }
4312 if (recentUnderruns == 0) {
4313 // no recent underruns: stay active
4314 break;
4315 }
4316 // there has recently been an underrun of some kind
4317 if (track->sharedBuffer() == 0) {
4318 // were any of the recent underruns "empty" (no frames available)?
4319 if (recentEmpty == 0) {
4320 // no, then ignore the partial underruns as they are allowed indefinitely
4321 break;
4322 }
4323 // there has recently been an "empty" underrun: decrement the retry counter
4324 if (--(track->mRetryCount) > 0) {
4325 break;
4326 }
4327 // indicate to client process that the track was disabled because of underrun;
4328 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004329 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004330 // remove from active list, but state remains ACTIVE [confusing but true]
4331 isActive = false;
4332 break;
4333 }
4334 // fall through
4335 case TrackBase::STOPPING_2:
4336 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004337 case TrackBase::STOPPED:
4338 case TrackBase::FLUSHED: // flush() while active
4339 // Check for presentation complete if track is inactive
4340 // We have consumed all the buffers of this track.
4341 // This would be incomplete if we auto-paused on underrun
4342 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004343 uint32_t latency = 0;
4344 status_t result = mOutput->stream->getLatency(&latency);
4345 ALOGE_IF(result != OK,
4346 "Error when retrieving output stream latency: %d", result);
4347 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004348 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004349 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4350 // track stays in active list until presentation is complete
4351 break;
4352 }
4353 }
4354 if (track->isStopping_2()) {
4355 track->mState = TrackBase::STOPPED;
4356 }
4357 if (track->isStopped()) {
4358 // Can't reset directly, as fast mixer is still polling this track
4359 // track->reset();
4360 // So instead mark this track as needing to be reset after push with ack
4361 resetMask |= 1 << i;
4362 }
4363 isActive = false;
4364 break;
4365 case TrackBase::IDLE:
4366 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004367 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004368 }
4369
4370 if (isActive) {
4371 // was it previously inactive?
4372 if (!(state->mTrackMask & (1 << j))) {
4373 ExtendedAudioBufferProvider *eabp = track;
4374 VolumeProvider *vp = track;
4375 fastTrack->mBufferProvider = eabp;
4376 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004377 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004378 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004379 fastTrack->mGeneration++;
4380 state->mTrackMask |= 1 << j;
4381 didModify = true;
4382 // no acknowledgement required for newly active tracks
4383 }
4384 // cache the combined master volume and stream type volume for fast mixer; this
4385 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004386 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004387 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004388 track->mCachedVolume = masterVolume
4389 * mStreamTypes[track->streamType()].volume
4390 * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004391 ++fastTracks;
4392 } else {
4393 // was it previously active?
4394 if (state->mTrackMask & (1 << j)) {
4395 fastTrack->mBufferProvider = NULL;
4396 fastTrack->mGeneration++;
4397 state->mTrackMask &= ~(1 << j);
4398 didModify = true;
4399 // If any fast tracks were removed, we must wait for acknowledgement
4400 // because we're about to decrement the last sp<> on those tracks.
4401 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4402 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004403 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4404 // AudioTrack may start (which may not be with a start() but with a write()
4405 // after underrun) and immediately paused or released. In that case the
4406 // FastTrack state hasn't had time to update.
4407 // TODO Remove the ALOGW when this theory is confirmed.
4408 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004409 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4410 j, track->mState, state->mTrackMask, recentUnderruns,
4411 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004412 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004413 }
4414 tracksToRemove->add(track);
4415 // Avoids a misleading display in dumpsys
4416 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4417 }
4418 continue;
4419 }
4420
4421 { // local variable scope to avoid goto warning
4422
4423 audio_track_cblk_t* cblk = track->cblk();
4424
4425 // The first time a track is added we wait
4426 // for all its buffers to be filled before processing it
4427 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004428
4429 // if an active track doesn't exist in the AudioMixer, create it.
4430 if (!mAudioMixer->exists(name)) {
4431 status_t status = mAudioMixer->create(
4432 name,
4433 track->mChannelMask,
4434 track->mFormat,
4435 track->mSessionId);
4436 if (status != OK) {
4437 ALOGW("%s: cannot create track name"
4438 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4439 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4440 tracksToRemove->add(track);
4441 track->invalidate(); // consider it dead.
4442 continue;
4443 }
4444 }
4445
Eric Laurent81784c32012-11-19 14:55:58 -08004446 // make sure that we have enough frames to mix one full buffer.
4447 // enforce this condition only once to enable draining the buffer in case the client
4448 // app does not call stop() and relies on underrun to stop:
4449 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4450 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004451 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004452 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004453 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004454
4455 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004456 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004457 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4458 // add frames already consumed but not yet released by the resampler
4459 // because mAudioTrackServerProxy->framesReady() will include these frames
4460 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4461
Eric Laurent81784c32012-11-19 14:55:58 -08004462 uint32_t minFrames = 1;
4463 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4464 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004465 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004466 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004467
4468 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004469 if (ATRACE_ENABLED()) {
4470 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004471 std::string traceName("nRdy");
4472 traceName += std::to_string(track->name());
4473 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004474 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004475 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004476 !track->isPaused() && !track->isTerminated())
4477 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004478 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004479
4480 mixedTracks++;
4481
Andy Hung69aed5f2014-02-25 17:24:40 -08004482 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4483 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004484 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004485 if (track->mainBuffer() != mSinkBuffer &&
4486 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004487 if (mEffectBufferEnabled) {
4488 mEffectBufferValid = true; // Later can set directly.
4489 }
Eric Laurent81784c32012-11-19 14:55:58 -08004490 chain = getEffectChain_l(track->sessionId());
4491 // Delegate volume control to effect in track effect chain if needed
4492 if (chain != 0) {
4493 tracksWithEffect++;
4494 } else {
4495 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4496 "session %d",
4497 name, track->sessionId());
4498 }
4499 }
4500
4501
4502 int param = AudioMixer::VOLUME;
4503 if (track->mFillingUpStatus == Track::FS_FILLED) {
4504 // no ramp for the first volume setting
4505 track->mFillingUpStatus = Track::FS_ACTIVE;
4506 if (track->mState == TrackBase::RESUMING) {
4507 track->mState = TrackBase::ACTIVE;
4508 param = AudioMixer::RAMP_VOLUME;
4509 }
4510 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004511 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004512 // FIXME should not make a decision based on mServer
4513 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004514 // If the track is stopped before the first frame was mixed,
4515 // do not apply ramp
4516 param = AudioMixer::RAMP_VOLUME;
4517 }
4518
4519 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004520 uint32_t vl, vr; // in U8.24 integer format
4521 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004522 // read original volumes with volume control
4523 float typeVolume = mStreamTypes[track->streamType()].volume;
4524 float v = masterVolume * typeVolume;
4525
Glenn Kastene4756fe2012-11-29 13:38:14 -08004526 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004527 vl = vr = 0;
4528 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004529 if (track->isPausing()) {
4530 track->setPaused();
4531 }
4532 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004533 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004534 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004535 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4536 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004537 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004538 if (vlf > GAIN_FLOAT_UNITY) {
4539 ALOGV("Track left volume out of range: %.3g", vlf);
4540 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004541 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004542 if (vrf > GAIN_FLOAT_UNITY) {
4543 ALOGV("Track right volume out of range: %.3g", vrf);
4544 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004545 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004546 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004547 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004548 // now apply the master volume and stream type volume and shaper volume
4549 vlf *= v * vh;
4550 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004551 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004552 // then derive vl and vr as U8.24 versions for the effect chain
4553 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4554 vl = (uint32_t) (scaleto8_24 * vlf);
4555 vr = (uint32_t) (scaleto8_24 * vrf);
4556 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004557 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004558 // send level comes from shared memory and so may be corrupt
4559 if (sendLevel > MAX_GAIN_INT) {
4560 ALOGV("Track send level out of range: %04X", sendLevel);
4561 sendLevel = MAX_GAIN_INT;
4562 }
Andy Hung6be49402014-05-30 10:42:03 -07004563 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4564 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004565 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566
Eric Laurent81784c32012-11-19 14:55:58 -08004567 // Delegate volume control to effect in track effect chain if needed
4568 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4569 // Do not ramp volume if volume is controlled by effect
4570 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004571 // Update remaining floating point volume levels
4572 vlf = (float)vl / (1 << 24);
4573 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004574 track->mHasVolumeController = true;
4575 } else {
4576 // force no volume ramp when volume controller was just disabled or removed
4577 // from effect chain to avoid volume spike
4578 if (track->mHasVolumeController) {
4579 param = AudioMixer::VOLUME;
4580 }
4581 track->mHasVolumeController = false;
4582 }
4583
Eric Laurent7c29ec92017-09-20 17:54:22 -07004584 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4585 // still applied by the mixer.
4586 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4587 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4588 if (v != mLeftVolFloat) {
4589 status_t result = mOutput->stream->setVolume(v, v);
4590 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4591 if (result == OK) {
4592 mLeftVolFloat = v;
4593 }
4594 }
4595 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4596 // remove stream volume contribution from software volume.
4597 if (v != 0.0f && mLeftVolFloat == v) {
4598 vlf = min(1.0f, vlf / v);
4599 vrf = min(1.0f, vrf / v);
4600 vaf = min(1.0f, vaf / v);
4601 }
4602 }
Eric Laurent81784c32012-11-19 14:55:58 -08004603 // XXX: these things DON'T need to be done each time
4604 mAudioMixer->setBufferProvider(name, track);
4605 mAudioMixer->enable(name);
4606
Andy Hung6be49402014-05-30 10:42:03 -07004607 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4608 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4609 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004610 mAudioMixer->setParameter(
4611 name,
4612 AudioMixer::TRACK,
4613 AudioMixer::FORMAT, (void *)track->format());
4614 mAudioMixer->setParameter(
4615 name,
4616 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004617 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004618 mAudioMixer->setParameter(
4619 name,
4620 AudioMixer::TRACK,
4621 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004622 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004623 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004624 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004625 if (reqSampleRate == 0) {
4626 reqSampleRate = mSampleRate;
4627 } else if (reqSampleRate > maxSampleRate) {
4628 reqSampleRate = maxSampleRate;
4629 }
Eric Laurent81784c32012-11-19 14:55:58 -08004630 mAudioMixer->setParameter(
4631 name,
4632 AudioMixer::RESAMPLE,
4633 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004634 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004635
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004636 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004637 mAudioMixer->setParameter(
4638 name,
4639 AudioMixer::TIMESTRETCH,
4640 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004641 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004642
Andy Hung69aed5f2014-02-25 17:24:40 -08004643 /*
4644 * Select the appropriate output buffer for the track.
4645 *
Andy Hung98ef9782014-03-04 14:46:50 -08004646 * Tracks with effects go into their own effects chain buffer
4647 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004648 *
4649 * Other tracks can use mMixerBuffer for higher precision
4650 * channel accumulation. If this buffer is enabled
4651 * (mMixerBufferEnabled true), then selected tracks will accumulate
4652 * into it.
4653 *
4654 */
4655 if (mMixerBufferEnabled
4656 && (track->mainBuffer() == mSinkBuffer
4657 || track->mainBuffer() == mMixerBuffer)) {
4658 mAudioMixer->setParameter(
4659 name,
4660 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004661 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004662 mAudioMixer->setParameter(
4663 name,
4664 AudioMixer::TRACK,
4665 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4666 // TODO: override track->mainBuffer()?
4667 mMixerBufferValid = true;
4668 } else {
4669 mAudioMixer->setParameter(
4670 name,
4671 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004672 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004673 mAudioMixer->setParameter(
4674 name,
4675 AudioMixer::TRACK,
4676 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4677 }
Eric Laurent81784c32012-11-19 14:55:58 -08004678 mAudioMixer->setParameter(
4679 name,
4680 AudioMixer::TRACK,
4681 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4682
4683 // reset retry count
4684 track->mRetryCount = kMaxTrackRetries;
4685
4686 // If one track is ready, set the mixer ready if:
4687 // - the mixer was not ready during previous round OR
4688 // - no other track is not ready
4689 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4690 mixerStatus != MIXER_TRACKS_ENABLED) {
4691 mixerStatus = MIXER_TRACKS_READY;
4692 }
4693 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004694 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004695 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4696 track, framesReady, desiredFrames);
Glenn Kasten82aaf942013-07-17 16:05:07 -07004697 track->mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004698 } else {
4699 track->mAudioTrackServerProxy->tallyUnderrunFrames(0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004700 }
Phil Burk2812d9e2016-01-04 10:34:30 -08004701
Eric Laurent81784c32012-11-19 14:55:58 -08004702 // clear effect chain input buffer if an active track underruns to avoid sending
4703 // previous audio buffer again to effects
4704 chain = getEffectChain_l(track->sessionId());
4705 if (chain != 0) {
4706 chain->clearInputBuffer();
4707 }
4708
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004709 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004710 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4711 track->isStopped() || track->isPaused()) {
4712 // We have consumed all the buffers of this track.
4713 // Remove it from the list of active tracks.
4714 // TODO: use actual buffer filling status instead of latency when available from
4715 // audio HAL
4716 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004717 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004718 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4719 if (track->isStopped()) {
4720 track->reset();
4721 }
4722 tracksToRemove->add(track);
4723 }
4724 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // No buffers for this track. Give it a few chances to
4726 // fill a buffer, then remove it from active list.
4727 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004728 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004729 tracksToRemove->add(track);
4730 // indicate to client process that the track was disabled because of underrun;
4731 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004732 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004733 // If one track is not ready, mark the mixer also not ready if:
4734 // - the mixer was ready during previous round OR
4735 // - no other track is ready
4736 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4737 mixerStatus != MIXER_TRACKS_READY) {
4738 mixerStatus = MIXER_TRACKS_ENABLED;
4739 }
4740 }
4741 mAudioMixer->disable(name);
4742 }
4743
4744 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004745
4746 }
4747
4748 // Push the new FastMixer state if necessary
4749 bool pauseAudioWatchdog = false;
4750 if (didModify) {
4751 state->mFastTracksGen++;
4752 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4753 if (kUseFastMixer == FastMixer_Dynamic &&
4754 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4755 state->mCommand = FastMixerState::COLD_IDLE;
4756 state->mColdFutexAddr = &mFastMixerFutex;
4757 state->mColdGen++;
4758 mFastMixerFutex = 0;
4759 if (kUseFastMixer == FastMixer_Dynamic) {
4760 mNormalSink = mOutputSink;
4761 }
4762 // If we go into cold idle, need to wait for acknowledgement
4763 // so that fast mixer stops doing I/O.
4764 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4765 pauseAudioWatchdog = true;
4766 }
Eric Laurent81784c32012-11-19 14:55:58 -08004767 }
4768 if (sq != NULL) {
4769 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004770 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4771 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4772 // when bringing the output sink into standby.)
4773 //
4774 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4775 //
4776 // This occurs with BT suspend when we idle the FastMixer with
4777 // active tracks, which may be added or removed.
4778 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004779 }
4780#ifdef AUDIO_WATCHDOG
4781 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4782 mAudioWatchdog->pause();
4783 }
4784#endif
4785
4786 // Now perform the deferred reset on fast tracks that have stopped
4787 while (resetMask != 0) {
4788 size_t i = __builtin_ctz(resetMask);
4789 ALOG_ASSERT(i < count);
4790 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004791 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004792 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4793 track->reset();
4794 }
4795
4796 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004797 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004798
Eric Laurent97d547d2014-09-02 14:45:53 -07004799 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4800 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004801 }
4802
4803 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004804 // as long as there are effects we should clear the effects buffer, to avoid
4805 // passing a non-clean buffer to the effect chain
4806 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004807 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004808 // sink or mix buffer must be cleared if all tracks are connected to an
4809 // effect chain as in this case the mixer will not write to the sink or mix buffer
4810 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004811 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4812 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004813 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004814 if (mMixerBufferValid) {
4815 memset(mMixerBuffer, 0, mMixerBufferSize);
4816 // TODO: In testing, mSinkBuffer below need not be cleared because
4817 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4818 // after mixing.
4819 //
4820 // To enforce this guarantee:
4821 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4822 // (mixedTracks == 0 && fastTracks > 0))
4823 // must imply MIXER_TRACKS_READY.
4824 // Later, we may clear buffers regardless, and skip much of this logic.
4825 }
Andy Hung98ef9782014-03-04 14:46:50 -08004826 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004827 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004828 }
4829
4830 // if any fast tracks, then status is ready
4831 mMixerStatusIgnoringFastTracks = mixerStatus;
4832 if (fastTracks > 0) {
4833 mixerStatus = MIXER_TRACKS_READY;
4834 }
4835 return mixerStatus;
4836}
4837
Eric Laurentad7dd962016-09-22 12:38:37 -07004838// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004839uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004840{
4841 uint32_t trackCount = 0;
4842 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004843 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004844 trackCount++;
4845 }
4846 }
4847 return trackCount;
4848}
4849
Andy Hung1bc088a2018-02-09 15:57:31 -08004850// isTrackAllowed_l() must be called with ThreadBase::mLock held
4851bool AudioFlinger::MixerThread::isTrackAllowed_l(
4852 audio_channel_mask_t channelMask, audio_format_t format,
4853 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004854{
Andy Hung1bc088a2018-02-09 15:57:31 -08004855 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4856 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004857 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004858 // Check validity as we don't call AudioMixer::create() here.
4859 if (!AudioMixer::isValidFormat(format)) {
4860 ALOGW("%s: invalid format: %#x", __func__, format);
4861 return false;
4862 }
4863 if (!AudioMixer::isValidChannelMask(channelMask)) {
4864 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4865 return false;
4866 }
4867 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004868}
4869
Eric Laurent10351942014-05-08 18:49:52 -07004870// checkForNewParameter_l() must be called with ThreadBase::mLock held
4871bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4872 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004873{
Eric Laurent81784c32012-11-19 14:55:58 -08004874 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004875 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004876
Eric Laurent10351942014-05-08 18:49:52 -07004877 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004878
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004879 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004880
Eric Laurent10351942014-05-08 18:49:52 -07004881 AudioParameter param = AudioParameter(keyValuePair);
4882 int value;
4883 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4884 reconfig = true;
4885 }
4886 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004887 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004888 status = BAD_VALUE;
4889 } else {
4890 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004891 reconfig = true;
4892 }
Eric Laurent10351942014-05-08 18:49:52 -07004893 }
4894 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004895 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004896 status = BAD_VALUE;
4897 } else {
4898 // no need to save value, since it's constant
4899 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004900 }
Eric Laurent10351942014-05-08 18:49:52 -07004901 }
4902 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4903 // do not accept frame count changes if tracks are open as the track buffer
4904 // size depends on frame count and correct behavior would not be guaranteed
4905 // if frame count is changed after track creation
4906 if (!mTracks.isEmpty()) {
4907 status = INVALID_OPERATION;
4908 } else {
4909 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004910 }
Eric Laurent10351942014-05-08 18:49:52 -07004911 }
4912 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08004913#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07004914 // when changing the audio output device, call addBatteryData to notify
4915 // the change
4916 if (mOutDevice != value) {
4917 uint32_t params = 0;
4918 // check whether speaker is on
4919 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
4920 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08004921 }
Eric Laurent10351942014-05-08 18:49:52 -07004922
4923 audio_devices_t deviceWithoutSpeaker
4924 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
4925 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07004926 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07004927 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4928 }
4929
4930 if (params != 0) {
4931 addBatteryData(params);
4932 }
4933 }
Eric Laurent81784c32012-11-19 14:55:58 -08004934#endif
4935
Eric Laurent10351942014-05-08 18:49:52 -07004936 // forward device change to effects that have requested to be
4937 // aware of attached audio device.
4938 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08004939 a2dpDeviceChanged =
4940 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07004941 mOutDevice = value;
4942 for (size_t i = 0; i < mEffectChains.size(); i++) {
4943 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08004944 }
4945 }
Eric Laurent10351942014-05-08 18:49:52 -07004946 }
Eric Laurent81784c32012-11-19 14:55:58 -08004947
Eric Laurent10351942014-05-08 18:49:52 -07004948 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004949 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07004950 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08004951 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07004952 mStandby = true;
4953 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004954 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08004955 }
Eric Laurent10351942014-05-08 18:49:52 -07004956 if (status == NO_ERROR && reconfig) {
4957 readOutputParameters_l();
4958 delete mAudioMixer;
4959 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08004960 for (const auto &track : mTracks) {
4961 const int name = track->name();
4962 status_t status = mAudioMixer->create(
4963 name,
4964 track->mChannelMask,
4965 track->mFormat,
4966 track->mSessionId);
4967 ALOGW_IF(status != NO_ERROR,
4968 "%s: cannot create track name"
4969 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4970 __func__,
4971 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07004972 }
Eric Laurent73e26b62015-04-27 16:55:58 -07004973 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07004974 }
Eric Laurent81784c32012-11-19 14:55:58 -08004975 }
4976
Eric Laurent42537be2016-01-08 17:16:42 -08004977 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08004978}
4979
4980
4981void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
4982{
Eric Laurent81784c32012-11-19 14:55:58 -08004983 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07004984 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08004985 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08004986 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent81784c32012-11-19 14:55:58 -08004987
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08004988 if (hasFastMixer()) {
4989 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
4990
4991 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
4992 // while we are dumping it. It may be inconsistent, but it won't mutate!
4993 // This is a large object so we place it on the heap.
4994 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
4995 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
4996 copy->dump(fd);
4997 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08004998
4999#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005000 // Similar for state queue
5001 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5002 observerCopy.dump(fd);
5003 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5004 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005005#endif
5006
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005007#ifdef AUDIO_WATCHDOG
5008 if (mAudioWatchdog != 0) {
5009 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5010 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5011 wdCopy.dump(fd);
5012 }
5013#endif
5014
5015 } else {
5016 dprintf(fd, " No FastMixer\n");
5017 }
5018
Glenn Kasten46909e72013-02-26 09:20:22 -08005019#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -08005020 // Write the tee output to a .wav file
Glenn Kasten5b2191a2016-08-19 11:44:47 -07005021 dumpTee(fd, mTeeSource, mId, 'M');
Glenn Kasten46909e72013-02-26 09:20:22 -08005022#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005023
Eric Laurent81784c32012-11-19 14:55:58 -08005024}
5025
5026uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5027{
5028 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5029}
5030
5031uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5032{
5033 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5034}
5035
5036void AudioFlinger::MixerThread::cacheParameters_l()
5037{
5038 PlaybackThread::cacheParameters_l();
5039
5040 // FIXME: Relaxed timing because of a certain device that can't meet latency
5041 // Should be reduced to 2x after the vendor fixes the driver issue
5042 // increase threshold again due to low power audio mode. The way this warning
5043 // threshold is calculated and its usefulness should be reconsidered anyway.
5044 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5045}
5046
5047// ----------------------------------------------------------------------------
5048
5049AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005050 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5051 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005052{
5053}
5054
Eric Laurentbfb1b832013-01-07 09:53:42 -08005055AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5056 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005057 ThreadBase::type_t type, bool systemReady)
5058 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005059 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005060{
5061}
5062
Eric Laurent81784c32012-11-19 14:55:58 -08005063AudioFlinger::DirectOutputThread::~DirectOutputThread()
5064{
5065}
5066
Eric Laurent5850c4c2016-11-10 13:04:31 -08005067void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005068{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005069 float left, right;
5070
5071 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5072 left = right = 0;
5073 } else {
5074 float typeVolume = mStreamTypes[track->streamType()].volume;
5075 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005076 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005077
Andy Hung10cbff12017-02-21 17:30:14 -08005078 // Get volumeshaper scaling
5079 std::pair<float /* volume */, bool /* active */>
5080 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005081 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005082 v *= vh.first;
5083 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005084
Glenn Kastenc56f3422014-03-21 17:53:17 -07005085 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5086 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5087 if (left > GAIN_FLOAT_UNITY) {
5088 left = GAIN_FLOAT_UNITY;
5089 }
5090 left *= v;
5091 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5092 if (right > GAIN_FLOAT_UNITY) {
5093 right = GAIN_FLOAT_UNITY;
5094 }
5095 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005096 }
5097
5098 if (lastTrack) {
5099 if (left != mLeftVolFloat || right != mRightVolFloat) {
5100 mLeftVolFloat = left;
5101 mRightVolFloat = right;
5102
5103 // Convert volumes from float to 8.24
5104 uint32_t vl = (uint32_t)(left * (1 << 24));
5105 uint32_t vr = (uint32_t)(right * (1 << 24));
5106
5107 // Delegate volume control to effect in track effect chain if needed
5108 // only one effect chain can be present on DirectOutputThread, so if
5109 // there is one, the track is connected to it
5110 if (!mEffectChains.isEmpty()) {
5111 mEffectChains[0]->setVolume_l(&vl, &vr);
5112 left = (float)vl / (1 << 24);
5113 right = (float)vr / (1 << 24);
5114 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005115 status_t result = mOutput->stream->setVolume(left, right);
5116 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005117 }
5118 }
5119}
5120
Phil Burk43b4dcc2015-06-09 16:53:44 -07005121void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5122{
5123 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005124 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005125
Eric Laurent0f0631e2015-07-06 18:01:25 -07005126 if (previousTrack != 0 && latestTrack != 0) {
5127 if (mType == DIRECT) {
5128 if (previousTrack.get() != latestTrack.get()) {
5129 mFlushPending = true;
5130 }
5131 } else /* mType == OFFLOAD */ {
5132 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5133 mFlushPending = true;
5134 }
5135 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005136 }
5137 PlaybackThread::onAddNewTrack_l();
5138}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005139
Eric Laurent81784c32012-11-19 14:55:58 -08005140AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5141 Vector< sp<Track> > *tracksToRemove
5142)
5143{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005144 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005145 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005146 bool doHwPause = false;
5147 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005148
5149 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005150 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005151 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005152 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005153 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005154 continue;
5155 }
5156
Eric Laurent5850c4c2016-11-10 13:04:31 -08005157 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005158#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005159 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005160#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005161 // Only consider last track started for volume and mixer state control.
5162 // In theory an older track could underrun and restart after the new one starts
5163 // but as we only care about the transition phase between two tracks on a
5164 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005165 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005166 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005167
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005168 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005169 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005170 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005171 doHwPause = true;
5172 mHwPaused = true;
5173 }
5174 tracksToRemove->add(track);
5175 } else if (track->isFlushPending()) {
5176 track->flushAck();
5177 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005178 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005179 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005180 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005181 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005182 if (last) {
5183 mLeftVolFloat = mRightVolFloat = -1.0;
5184 if (mHwPaused) {
5185 doHwResume = true;
5186 mHwPaused = false;
5187 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005188 }
5189 }
5190
Eric Laurent81784c32012-11-19 14:55:58 -08005191 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005192 // for all its buffers to be filled before processing it.
5193 // Allow draining the buffer in case the client
5194 // app does not call stop() and relies on underrun to stop:
5195 // hence the test on (track->mRetryCount > 1).
5196 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005197 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005198 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005199 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005200 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005201 minFrames = mNormalFrameCount;
5202 } else {
5203 minFrames = 1;
5204 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005205
Eric Laurentab5cdba2014-06-09 17:22:27 -07005206 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5207 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005208 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005209 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005210
5211 if (track->mFillingUpStatus == Track::FS_FILLED) {
5212 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005213 if (last) {
5214 // make sure processVolume_l() will apply new volume even if 0
5215 mLeftVolFloat = mRightVolFloat = -1.0;
5216 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005217 if (!mHwSupportsPause) {
5218 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005219 }
5220 }
5221
5222 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005223 processVolume_l(track, last);
5224 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005225 sp<Track> previousTrack = mPreviousTrack.promote();
5226 if (previousTrack != 0) {
5227 if (track != previousTrack.get()) {
5228 // Flush any data still being written from last track
5229 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005230 // Invalidate previous track to force a seek when resuming.
5231 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005232 }
5233 }
5234 mPreviousTrack = track;
5235
Eric Laurentd595b7c2013-04-03 17:27:56 -07005236 // reset retry count
5237 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005238 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005239 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005240 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005241 doHwResume = true;
5242 mHwPaused = false;
5243 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005244 }
Eric Laurent81784c32012-11-19 14:55:58 -08005245 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005246 // clear effect chain input buffer if the last active track started underruns
5247 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005248 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005249 mEffectChains[0]->clearInputBuffer();
5250 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005251 if (track->isStopping_1()) {
5252 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005253 if (last && mHwPaused) {
5254 doHwResume = true;
5255 mHwPaused = false;
5256 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005257 }
5258 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5259 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005260 // We have consumed all the buffers of this track.
5261 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005262 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005263 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005264 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5265 } else {
5266 audioHALFrames = 0;
5267 }
5268
Andy Hung818e7a32016-02-16 18:08:07 -08005269 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005270 if (mStandby || !last ||
5271 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005272 if (track->isStopping_2()) {
5273 track->mState = TrackBase::STOPPED;
5274 }
Eric Laurent81784c32012-11-19 14:55:58 -08005275 if (track->isStopped()) {
5276 track->reset();
5277 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005278 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005279 }
5280 } else {
5281 // No buffers for this track. Give it a few chances to
5282 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005283 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005284 if (--(track->mRetryCount) <= 0) {
5285 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005286 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005287 // indicate to client process that the track was disabled because of underrun;
5288 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005289 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005290 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005291 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5292 "minFrames = %u, mFormat = %#x",
5293 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005294 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005295 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005296 doHwPause = true;
5297 mHwPaused = true;
5298 }
Eric Laurent81784c32012-11-19 14:55:58 -08005299 }
5300 }
5301 }
5302 }
5303
Eric Laurentd1f69b02014-12-15 14:33:13 -08005304 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005305 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005306 for (size_t i = 0; i < mTracks.size(); i++) {
5307 if (mTracks[i]->isFlushPending()) {
5308 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005309 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005310 }
5311 }
5312 }
5313
5314 // make sure the pause/flush/resume sequence is executed in the right order.
5315 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5316 // before flush and then resume HW. This can happen in case of pause/flush/resume
5317 // if resume is received before pause is executed.
5318 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005319 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005320 status_t result = mOutput->stream->pause();
5321 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005322 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005323 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005324 flushHw_l();
5325 }
5326 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005327 status_t result = mOutput->stream->resume();
5328 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005329 }
Eric Laurent81784c32012-11-19 14:55:58 -08005330 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005332
5333 return mixerStatus;
5334}
5335
5336void AudioFlinger::DirectOutputThread::threadLoop_mix()
5337{
Eric Laurent81784c32012-11-19 14:55:58 -08005338 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005339 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005340 // output audio to hardware
5341 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005342 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005343 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005344 status_t status = mActiveTrack->getNextBuffer(&buffer);
5345 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005346 // no need to pad with 0 for compressed audio
5347 if (audio_has_proportional_frames(mFormat)) {
5348 memset(curBuf, 0, frameCount * mFrameSize);
5349 }
Eric Laurent81784c32012-11-19 14:55:58 -08005350 break;
5351 }
5352 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5353 frameCount -= buffer.frameCount;
5354 curBuf += buffer.frameCount * mFrameSize;
5355 mActiveTrack->releaseBuffer(&buffer);
5356 }
Andy Hung2098f272014-02-27 14:00:06 -08005357 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005358 mSleepTimeUs = 0;
5359 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005360 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005361}
5362
5363void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5364{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005365 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005366 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005367 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005368 return;
5369 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005370 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005371 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005372 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005373 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005374 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005375 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005376 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005377 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005378 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005379 }
5380}
5381
Eric Laurentd1f69b02014-12-15 14:33:13 -08005382void AudioFlinger::DirectOutputThread::threadLoop_exit()
5383{
5384 {
5385 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005386 for (size_t i = 0; i < mTracks.size(); i++) {
5387 if (mTracks[i]->isFlushPending()) {
5388 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005389 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005390 }
5391 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005392 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005393 flushHw_l();
5394 }
5395 }
5396 PlaybackThread::threadLoop_exit();
5397}
5398
5399// must be called with thread mutex locked
5400bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5401{
5402 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005403 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005404
vivek mehta9cd7ad12016-03-17 00:18:29 -07005405 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5406 return !mStandby;
5407 }
5408
Eric Laurentd1f69b02014-12-15 14:33:13 -08005409 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5410 // after a timeout and we will enter standby then.
5411 if (mTracks.size() > 0) {
5412 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005413 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5414 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005415 }
5416
Eric Laurent5cff4032015-05-26 13:49:58 -07005417 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005418}
5419
Eric Laurent10351942014-05-08 18:49:52 -07005420// checkForNewParameter_l() must be called with ThreadBase::mLock held
5421bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5422 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005423{
5424 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005425 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005426
Eric Laurent10351942014-05-08 18:49:52 -07005427 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005428
Eric Laurent10351942014-05-08 18:49:52 -07005429 AudioParameter param = AudioParameter(keyValuePair);
5430 int value;
5431 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5432 // forward device change to effects that have requested to be
5433 // aware of attached audio device.
5434 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005435 a2dpDeviceChanged =
5436 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005437 mOutDevice = value;
5438 for (size_t i = 0; i < mEffectChains.size(); i++) {
5439 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005440 }
5441 }
Eric Laurent81784c32012-11-19 14:55:58 -08005442 }
Eric Laurent10351942014-05-08 18:49:52 -07005443 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5444 // do not accept frame count changes if tracks are open as the track buffer
5445 // size depends on frame count and correct behavior would not be garantied
5446 // if frame count is changed after track creation
5447 if (!mTracks.isEmpty()) {
5448 status = INVALID_OPERATION;
5449 } else {
5450 reconfig = true;
5451 }
5452 }
5453 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005454 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005455 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005456 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005457 mStandby = true;
5458 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005459 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005460 }
5461 if (status == NO_ERROR && reconfig) {
5462 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005463 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005464 }
5465 }
5466
Eric Laurent42537be2016-01-08 17:16:42 -08005467 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005468}
5469
5470uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5471{
5472 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005473 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005474 time = PlaybackThread::activeSleepTimeUs();
5475 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005476 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005477 }
5478 return time;
5479}
5480
5481uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5482{
5483 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005484 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005485 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5486 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005487 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005488 }
5489 return time;
5490}
5491
5492uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5493{
5494 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005495 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005496 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5497 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005498 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005499 }
5500 return time;
5501}
5502
5503void AudioFlinger::DirectOutputThread::cacheParameters_l()
5504{
5505 PlaybackThread::cacheParameters_l();
5506
5507 // use shorter standby delay as on normal output to release
5508 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005509 // no delay on outputs with HW A/V sync
5510 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005511 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005512 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005513 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005514 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005515 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005516 }
Eric Laurent81784c32012-11-19 14:55:58 -08005517}
5518
Eric Laurente659ef42014-09-29 13:06:46 -07005519void AudioFlinger::DirectOutputThread::flushHw_l()
5520{
Phil Burk062e67a2015-02-11 13:40:50 -08005521 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005522 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005523 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005524}
5525
Andy Hung10cbff12017-02-21 17:30:14 -08005526int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5527 // If a VolumeShaper is active, we must wake up periodically to update volume.
5528 const int64_t NS_PER_MS = 1000000;
5529 return mVolumeShaperActive ?
5530 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5531}
5532
Eric Laurent81784c32012-11-19 14:55:58 -08005533// ----------------------------------------------------------------------------
5534
Eric Laurentbfb1b832013-01-07 09:53:42 -08005535AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005536 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005537 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005538 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005539 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005540 mDrainSequence(0),
5541 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005542{
5543}
5544
5545AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5546{
5547}
5548
5549void AudioFlinger::AsyncCallbackThread::onFirstRef()
5550{
5551 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5552}
5553
5554bool AudioFlinger::AsyncCallbackThread::threadLoop()
5555{
5556 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005557 uint32_t writeAckSequence;
5558 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005559 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005560
5561 {
5562 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005563 while (!((mWriteAckSequence & 1) ||
5564 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005565 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005566 exitPending())) {
5567 mWaitWorkCV.wait(mLock);
5568 }
5569
Eric Laurentbfb1b832013-01-07 09:53:42 -08005570 if (exitPending()) {
5571 break;
5572 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005573 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5574 mWriteAckSequence, mDrainSequence);
5575 writeAckSequence = mWriteAckSequence;
5576 mWriteAckSequence &= ~1;
5577 drainSequence = mDrainSequence;
5578 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005579 asyncError = mAsyncError;
5580 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005581 }
5582 {
Eric Laurent4de95592013-09-26 15:28:21 -07005583 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5584 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005585 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005586 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005587 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005588 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005589 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005590 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005591 if (asyncError) {
5592 playbackThread->onAsyncError();
5593 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005594 }
5595 }
5596 }
5597 return false;
5598}
5599
5600void AudioFlinger::AsyncCallbackThread::exit()
5601{
5602 ALOGV("AsyncCallbackThread::exit");
5603 Mutex::Autolock _l(mLock);
5604 requestExit();
5605 mWaitWorkCV.broadcast();
5606}
5607
Eric Laurent3b4529e2013-09-05 18:09:19 -07005608void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005609{
5610 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005611 // bit 0 is cleared
5612 mWriteAckSequence = sequence << 1;
5613}
5614
5615void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5616{
5617 Mutex::Autolock _l(mLock);
5618 // ignore unexpected callbacks
5619 if (mWriteAckSequence & 2) {
5620 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005621 mWaitWorkCV.signal();
5622 }
5623}
5624
Eric Laurent3b4529e2013-09-05 18:09:19 -07005625void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005626{
5627 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005628 // bit 0 is cleared
5629 mDrainSequence = sequence << 1;
5630}
5631
5632void AudioFlinger::AsyncCallbackThread::resetDraining()
5633{
5634 Mutex::Autolock _l(mLock);
5635 // ignore unexpected callbacks
5636 if (mDrainSequence & 2) {
5637 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005638 mWaitWorkCV.signal();
5639 }
5640}
5641
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005642void AudioFlinger::AsyncCallbackThread::setAsyncError()
5643{
5644 Mutex::Autolock _l(mLock);
5645 mAsyncError = true;
5646 mWaitWorkCV.signal();
5647}
5648
Eric Laurentbfb1b832013-01-07 09:53:42 -08005649
5650// ----------------------------------------------------------------------------
5651AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005652 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5653 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005654 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5655 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005656{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005657 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005658 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005659 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005660}
5661
Eric Laurentbfb1b832013-01-07 09:53:42 -08005662void AudioFlinger::OffloadThread::threadLoop_exit()
5663{
5664 if (mFlushPending || mHwPaused) {
5665 // If a flush is pending or track was paused, just discard buffered data
5666 flushHw_l();
5667 } else {
5668 mMixerStatus = MIXER_DRAIN_ALL;
5669 threadLoop_drain();
5670 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005671 if (mUseAsyncWrite) {
5672 ALOG_ASSERT(mCallbackThread != 0);
5673 mCallbackThread->exit();
5674 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005675 PlaybackThread::threadLoop_exit();
5676}
5677
5678AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5679 Vector< sp<Track> > *tracksToRemove
5680)
5681{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005682 size_t count = mActiveTracks.size();
5683
5684 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005685 bool doHwPause = false;
5686 bool doHwResume = false;
5687
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005688 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005689
Eric Laurentbfb1b832013-01-07 09:53:42 -08005690 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005691 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005692 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005693#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005694 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005695#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005696 // Only consider last track started for volume and mixer state control.
5697 // In theory an older track could underrun and restart after the new one starts
5698 // but as we only care about the transition phase between two tracks on a
5699 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005700 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005701 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005702
Haynes Mathew George7844f672014-01-15 12:32:55 -08005703 if (track->isInvalid()) {
5704 ALOGW("An invalidated track shouldn't be in active list");
5705 tracksToRemove->add(track);
5706 continue;
5707 }
5708
5709 if (track->mState == TrackBase::IDLE) {
5710 ALOGW("An idle track shouldn't be in active list");
5711 continue;
5712 }
5713
Eric Laurentbfb1b832013-01-07 09:53:42 -08005714 if (track->isPausing()) {
5715 track->setPaused();
5716 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005717 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005718 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005719 mHwPaused = true;
5720 }
5721 // If we were part way through writing the mixbuffer to
5722 // the HAL we must save this until we resume
5723 // BUG - this will be wrong if a different track is made active,
5724 // in that case we want to discard the pending data in the
5725 // mixbuffer and tell the client to present it again when the
5726 // track is resumed
5727 mPausedWriteLength = mCurrentWriteLength;
5728 mPausedBytesRemaining = mBytesRemaining;
5729 mBytesRemaining = 0; // stop writing
5730 }
5731 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005732 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005733 if (track->isStopping_1()) {
5734 track->mRetryCount = kMaxTrackStopRetriesOffload;
5735 } else {
5736 track->mRetryCount = kMaxTrackRetriesOffload;
5737 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005738 track->flushAck();
5739 if (last) {
5740 mFlushPending = true;
5741 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005742 } else if (track->isResumePending()){
5743 track->resumeAck();
5744 if (last) {
5745 if (mPausedBytesRemaining) {
5746 // Need to continue write that was interrupted
5747 mCurrentWriteLength = mPausedWriteLength;
5748 mBytesRemaining = mPausedBytesRemaining;
5749 mPausedBytesRemaining = 0;
5750 }
5751 if (mHwPaused) {
5752 doHwResume = true;
5753 mHwPaused = false;
5754 // threadLoop_mix() will handle the case that we need to
5755 // resume an interrupted write
5756 }
5757 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005758 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005759
Eric Laurent3df841a2016-07-15 15:15:40 -07005760 mLeftVolFloat = mRightVolFloat = -1.0;
5761
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005762 // Do not handle new data in this iteration even if track->framesReady()
5763 mixerStatus = MIXER_TRACKS_ENABLED;
5764 }
5765 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005766 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005767 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005768 if (track->mFillingUpStatus == Track::FS_FILLED) {
5769 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005770 if (last) {
5771 // make sure processVolume_l() will apply new volume even if 0
5772 mLeftVolFloat = mRightVolFloat = -1.0;
5773 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005774 }
5775
5776 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005777 sp<Track> previousTrack = mPreviousTrack.promote();
5778 if (previousTrack != 0) {
5779 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005780 // Flush any data still being written from last track
5781 mBytesRemaining = 0;
5782 if (mPausedBytesRemaining) {
5783 // Last track was paused so we also need to flush saved
5784 // mixbuffer state and invalidate track so that it will
5785 // re-submit that unwritten data when it is next resumed
5786 mPausedBytesRemaining = 0;
5787 // Invalidate is a bit drastic - would be more efficient
5788 // to have a flag to tell client that some of the
5789 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005790 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005791 }
5792 // flush data already sent to the DSP if changing audio session as audio
5793 // comes from a different source. Also invalidate previous track to force a
5794 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005795 if (previousTrack->sessionId() != track->sessionId()) {
5796 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005797 }
5798 }
5799 }
5800 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005801 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005802 if (track->isStopping_1()) {
5803 track->mRetryCount = kMaxTrackStopRetriesOffload;
5804 } else {
5805 track->mRetryCount = kMaxTrackRetriesOffload;
5806 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005807 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005808 mixerStatus = MIXER_TRACKS_READY;
5809 }
5810 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005811 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005812 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005813 if (--(track->mRetryCount) <= 0) {
5814 // Hardware buffer can hold a large amount of audio so we must
5815 // wait for all current track's data to drain before we say
5816 // that the track is stopped.
5817 if (mBytesRemaining == 0) {
5818 // Only start draining when all data in mixbuffer
5819 // has been written
5820 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5821 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5822 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5823 if (last && !mStandby) {
5824 // do not modify drain sequence if we are already draining. This happens
5825 // when resuming from pause after drain.
5826 if ((mDrainSequence & 1) == 0) {
5827 mSleepTimeUs = 0;
5828 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5829 mixerStatus = MIXER_DRAIN_TRACK;
5830 mDrainSequence += 2;
5831 }
5832 if (mHwPaused) {
5833 // It is possible to move from PAUSED to STOPPING_1 without
5834 // a resume so we must ensure hardware is running
5835 doHwResume = true;
5836 mHwPaused = false;
5837 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005838 }
5839 }
Eric Laurente93cc032016-05-05 10:15:10 -07005840 } else if (last) {
5841 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5842 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005843 }
5844 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005845 // Drain has completed or we are in standby, signal presentation complete
5846 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005847 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005848 uint32_t latency = 0;
5849 status_t result = mOutput->stream->getLatency(&latency);
5850 ALOGE_IF(result != OK,
5851 "Error when retrieving output stream latency: %d", result);
5852 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005853 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005854 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005855 track->presentationComplete(framesWritten, audioHALFrames);
5856 track->reset();
5857 tracksToRemove->add(track);
5858 }
5859 } else {
5860 // No buffers for this track. Give it a few chances to
5861 // fill a buffer, then remove it from active list.
5862 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005863 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005864 uint64_t position = 0;
5865 struct timespec unused;
5866 // The running check restarts the retry counter at least once.
5867 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5868 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5869 running = true;
5870 mOffloadUnderrunPosition = position;
5871 }
5872 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005873 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5874 (long long)position, (long long)mOffloadUnderrunPosition);
5875 }
5876 if (running) { // still running, give us more time.
5877 track->mRetryCount = kMaxTrackRetriesOffload;
5878 } else {
5879 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5880 track->name());
5881 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005882 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005883 // it will then automatically call start() when data is available
5884 track->disable();
5885 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005886 } else if (last){
5887 mixerStatus = MIXER_TRACKS_ENABLED;
5888 }
5889 }
5890 }
5891 // compute volume for this track
5892 processVolume_l(track, last);
5893 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005894
Eric Laurentea0fade2013-10-04 16:23:48 -07005895 // make sure the pause/flush/resume sequence is executed in the right order.
5896 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5897 // before flush and then resume HW. This can happen in case of pause/flush/resume
5898 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07005899 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005900 status_t result = mOutput->stream->pause();
5901 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005902 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005903 if (mFlushPending) {
5904 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005905 }
Eric Laurentfd477972013-10-25 18:10:40 -07005906 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005907 status_t result = mOutput->stream->resume();
5908 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07005909 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005910
Eric Laurentbfb1b832013-01-07 09:53:42 -08005911 // remove all the tracks that need to be...
5912 removeTracks_l(*tracksToRemove);
5913
5914 return mixerStatus;
5915}
5916
Eric Laurentbfb1b832013-01-07 09:53:42 -08005917// must be called with thread mutex locked
5918bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
5919{
Eric Laurent3b4529e2013-09-05 18:09:19 -07005920 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
5921 mWriteAckSequence, mDrainSequence);
5922 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005923 return true;
5924 }
5925 return false;
5926}
5927
Eric Laurentbfb1b832013-01-07 09:53:42 -08005928bool AudioFlinger::OffloadThread::waitingAsyncCallback()
5929{
5930 Mutex::Autolock _l(mLock);
5931 return waitingAsyncCallback_l();
5932}
5933
5934void AudioFlinger::OffloadThread::flushHw_l()
5935{
Eric Laurente659ef42014-09-29 13:06:46 -07005936 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005937 // Flush anything still waiting in the mixbuffer
5938 mCurrentWriteLength = 0;
5939 mBytesRemaining = 0;
5940 mPausedWriteLength = 0;
5941 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07005942 // reset bytes written count to reflect that DSP buffers are empty after flush.
5943 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07005944 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08005945
Eric Laurentbfb1b832013-01-07 09:53:42 -08005946 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005947 // discard any pending drain or write ack by incrementing sequence
5948 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5949 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005950 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005951 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5952 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005953 }
5954}
5955
Haynes Mathew George05317d22016-05-03 16:34:26 -07005956void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
5957{
5958 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07005959 if (PlaybackThread::invalidateTracks_l(streamType)) {
5960 mFlushPending = true;
5961 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07005962}
5963
Eric Laurentbfb1b832013-01-07 09:53:42 -08005964// ----------------------------------------------------------------------------
5965
Eric Laurent81784c32012-11-19 14:55:58 -08005966AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07005967 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005968 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07005969 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08005970 mWaitTimeMs(UINT_MAX)
5971{
5972 addOutputTrack(mainThread);
5973}
5974
5975AudioFlinger::DuplicatingThread::~DuplicatingThread()
5976{
5977 for (size_t i = 0; i < mOutputTracks.size(); i++) {
5978 mOutputTracks[i]->destroy();
5979 }
5980}
5981
5982void AudioFlinger::DuplicatingThread::threadLoop_mix()
5983{
5984 // mix buffers...
5985 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08005986 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08005987 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08005988 if (mMixerBufferValid) {
5989 memset(mMixerBuffer, 0, mMixerBufferSize);
5990 } else {
5991 memset(mSinkBuffer, 0, mSinkBufferSize);
5992 }
Eric Laurent81784c32012-11-19 14:55:58 -08005993 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005994 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005995 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08005996 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005997 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005998}
5999
6000void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6001{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006002 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006003 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006004 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006005 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006006 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006007 }
6008 } else if (mBytesWritten != 0) {
6009 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6010 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006011 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006012 } else {
6013 // flush remaining overflow buffers in output tracks
6014 writeFrames = 0;
6015 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006016 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006017 }
6018}
6019
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006021{
6022 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hungc25b84a2015-01-14 19:04:10 -08006023 outputTracks[i]->write(mSinkBuffer, writeFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08006024 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006025 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006026 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006027}
6028
6029void AudioFlinger::DuplicatingThread::threadLoop_standby()
6030{
6031 // DuplicatingThread implements standby by stopping all tracks
6032 for (size_t i = 0; i < outputTracks.size(); i++) {
6033 outputTracks[i]->stop();
6034 }
6035}
6036
Andy Hung1bc088a2018-02-09 15:57:31 -08006037void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6038{
6039 MixerThread::dumpInternals(fd, args);
6040
6041 std::stringstream ss;
6042 const size_t numTracks = mOutputTracks.size();
6043 ss << " " << numTracks << " OutputTracks";
6044 if (numTracks > 0) {
6045 ss << ":";
6046 for (const auto &track : mOutputTracks) {
6047 const sp<ThreadBase> thread = track->thread().promote();
6048 ss << " (" << track->name() << " : ";
6049 if (thread.get() != nullptr) {
6050 ss << thread.get() << ", " << thread->id();
6051 } else {
6052 ss << "null";
6053 }
6054 ss << ")";
6055 }
6056 }
6057 ss << "\n";
6058 std::string result = ss.str();
6059 write(fd, result.c_str(), result.size());
6060}
6061
Eric Laurent81784c32012-11-19 14:55:58 -08006062void AudioFlinger::DuplicatingThread::saveOutputTracks()
6063{
6064 outputTracks = mOutputTracks;
6065}
6066
6067void AudioFlinger::DuplicatingThread::clearOutputTracks()
6068{
6069 outputTracks.clear();
6070}
6071
6072void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6073{
6074 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006075 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6076 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6077 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6078 const size_t frameCount =
6079 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6080 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6081 // from different OutputTracks and their associated MixerThreads (e.g. one may
6082 // nearly empty and the other may be dropping data).
6083
6084 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006085 this,
6086 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006087 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006088 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006089 frameCount,
6090 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006091 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6092 if (status != NO_ERROR) {
6093 ALOGE("addOutputTrack() initCheck failed %d", status);
6094 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006095 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006096 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6097 mOutputTracks.add(outputTrack);
6098 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6099 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006100}
6101
6102void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6103{
6104 Mutex::Autolock _l(mLock);
6105 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6106 if (mOutputTracks[i]->thread() == thread) {
6107 mOutputTracks[i]->destroy();
6108 mOutputTracks.removeAt(i);
6109 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006110 if (thread->getOutput() == mOutput) {
6111 mOutput = NULL;
6112 }
Eric Laurent81784c32012-11-19 14:55:58 -08006113 return;
6114 }
6115 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006116 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006117}
6118
6119// caller must hold mLock
6120void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6121{
6122 mWaitTimeMs = UINT_MAX;
6123 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6124 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6125 if (strong != 0) {
6126 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6127 if (waitTimeMs < mWaitTimeMs) {
6128 mWaitTimeMs = waitTimeMs;
6129 }
6130 }
6131 }
6132}
6133
6134
6135bool AudioFlinger::DuplicatingThread::outputsReady(
6136 const SortedVector< sp<OutputTrack> > &outputTracks)
6137{
6138 for (size_t i = 0; i < outputTracks.size(); i++) {
6139 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6140 if (thread == 0) {
6141 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6142 outputTracks[i].get());
6143 return false;
6144 }
6145 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6146 // see note at standby() declaration
6147 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6148 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6149 thread.get());
6150 return false;
6151 }
6152 }
6153 return true;
6154}
6155
Kevin Rocard069c2712018-03-29 19:09:14 -07006156void AudioFlinger::DuplicatingThread::updateMetadata_l()
6157{
Kevin Rocardb31f96f2018-04-03 09:00:09 -07006158 // TODO: The duplicated track metadata needs to be pushed to downstream
6159 // but this information can be read at any time by the downstream threads.
6160 // Taking the lock of any downstream threads is no possible due to cross deadlock risks
6161 // (eg: during effect move).
6162 // A lock-free structure needs to be used to shared the metadata, probably an atomic
6163 // pointer to a metadata vector in each output tracks.
Kevin Rocard069c2712018-03-29 19:09:14 -07006164}
6165
Eric Laurent81784c32012-11-19 14:55:58 -08006166uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6167{
6168 return (mWaitTimeMs * 1000) / 2;
6169}
6170
6171void AudioFlinger::DuplicatingThread::cacheParameters_l()
6172{
6173 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6174 updateWaitTime_l();
6175
6176 MixerThread::cacheParameters_l();
6177}
6178
Eric Laurent6acd1d42017-01-04 14:23:29 -08006179
Eric Laurent81784c32012-11-19 14:55:58 -08006180// ----------------------------------------------------------------------------
6181// Record
6182// ----------------------------------------------------------------------------
6183
6184AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6185 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006186 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006187 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006188 audio_devices_t inDevice,
6189 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006190#ifdef TEE_SINK
6191 , const sp<NBAIO_Sink>& teeSink
6192#endif
6193 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006194 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006195 mInput(input),
6196 mActiveTracks(&this->mLocalLog),
6197 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006198 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006199 mRsmpInRear(0)
Glenn Kasten46909e72013-02-26 09:20:22 -08006200#ifdef TEE_SINK
6201 , mTeeSink(teeSink)
6202#endif
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006203 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6204 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006205 // mFastCapture below
6206 , mFastCaptureFutex(0)
6207 // mInputSource
6208 // mPipeSink
6209 // mPipeSource
6210 , mPipeFramesP2(0)
6211 // mPipeMemory
6212 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006213 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006214 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006215{
Glenn Kastend7dca052015-03-05 16:05:54 -08006216 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6217 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006218
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006219 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006220
6221 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006222 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006223 size_t numCounterOffers = 0;
6224 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006225#if !LOG_NDEBUG
6226 ssize_t index =
6227#else
6228 (void)
6229#endif
6230 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006231 ALOG_ASSERT(index == 0);
6232
6233 // initialize fast capture depending on configuration
6234 bool initFastCapture;
6235 switch (kUseFastCapture) {
6236 case FastCapture_Never:
6237 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006238 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006239 break;
6240 case FastCapture_Always:
6241 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006242 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006243 break;
6244 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006245 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006246 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6247 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6248 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006249 break;
6250 // case FastCapture_Dynamic:
6251 }
6252
6253 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006254 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006255 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006256 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6257 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006258 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006259 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006260 const sp<MemoryDealer> roHeap(readOnlyHeap());
6261 sp<IMemory> pipeMemory;
6262 if ((roHeap == 0) ||
6263 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006264 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6265 ALOGE("not enough memory for pipe buffer size=%zu; "
6266 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6267 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6268 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006269 goto failed;
6270 }
6271 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6272 memset(pipeBuffer, 0, pipeSize);
6273 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6274 const NBAIO_Format offers[1] = {format};
6275 size_t numCounterOffers = 0;
6276 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6277 ALOG_ASSERT(index == 0);
6278 mPipeSink = pipe;
6279 PipeReader *pipeReader = new PipeReader(*pipe);
6280 numCounterOffers = 0;
6281 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6282 ALOG_ASSERT(index == 0);
6283 mPipeSource = pipeReader;
6284 mPipeFramesP2 = pipeFramesP2;
6285 mPipeMemory = pipeMemory;
6286
6287 // create fast capture
6288 mFastCapture = new FastCapture();
6289 FastCaptureStateQueue *sq = mFastCapture->sq();
6290#ifdef STATE_QUEUE_DUMP
6291 // FIXME
6292#endif
6293 FastCaptureState *state = sq->begin();
6294 state->mCblk = NULL;
6295 state->mInputSource = mInputSource.get();
6296 state->mInputSourceGen++;
6297 state->mPipeSink = pipe;
6298 state->mPipeSinkGen++;
6299 state->mFrameCount = mFrameCount;
6300 state->mCommand = FastCaptureState::COLD_IDLE;
6301 // already done in constructor initialization list
6302 //mFastCaptureFutex = 0;
6303 state->mColdFutexAddr = &mFastCaptureFutex;
6304 state->mColdGen++;
6305 state->mDumpState = &mFastCaptureDumpState;
6306#ifdef TEE_SINK
6307 // FIXME
6308#endif
6309 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6310 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6311 sq->end();
6312 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6313
6314 // start the fast capture
6315 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6316 pid_t tid = mFastCapture->getTid();
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07006317 sendPrioConfigEvent(getpid_cached, tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006318 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006319#ifdef AUDIO_WATCHDOG
6320 // FIXME
6321#endif
6322
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006323 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006324 }
6325failed: ;
6326
6327 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006328}
6329
Eric Laurent81784c32012-11-19 14:55:58 -08006330AudioFlinger::RecordThread::~RecordThread()
6331{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006332 if (mFastCapture != 0) {
6333 FastCaptureStateQueue *sq = mFastCapture->sq();
6334 FastCaptureState *state = sq->begin();
6335 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6336 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6337 if (old == -1) {
6338 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6339 }
6340 }
6341 state->mCommand = FastCaptureState::EXIT;
6342 sq->end();
6343 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6344 mFastCapture->join();
6345 mFastCapture.clear();
6346 }
6347 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006348 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006349 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006350}
6351
6352void AudioFlinger::RecordThread::onFirstRef()
6353{
Glenn Kastend7dca052015-03-05 16:05:54 -08006354 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006355}
6356
Eric Laurent555530a2017-02-07 18:17:24 -08006357void AudioFlinger::RecordThread::preExit()
6358{
6359 ALOGV(" preExit()");
6360 Mutex::Autolock _l(mLock);
6361 for (size_t i = 0; i < mTracks.size(); i++) {
6362 sp<RecordTrack> track = mTracks[i];
6363 track->invalidate();
6364 }
6365 mActiveTracks.clear();
6366 mStartStopCond.broadcast();
6367}
6368
Eric Laurent81784c32012-11-19 14:55:58 -08006369bool AudioFlinger::RecordThread::threadLoop()
6370{
Eric Laurent81784c32012-11-19 14:55:58 -08006371 nsecs_t lastWarning = 0;
6372
6373 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006374
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006375reacquire_wakelock:
6376 sp<RecordTrack> activeTrack;
6377 {
6378 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006379 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006380 }
6381
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006382 // used to request a deferred sleep, to be executed later while mutex is unlocked
6383 uint32_t sleepUs = 0;
6384
6385 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006386 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006387 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006388
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006389 // activeTracks accumulates a copy of a subset of mActiveTracks
6390 Vector< sp<RecordTrack> > activeTracks;
6391
Glenn Kasten735f45f2014-08-18 15:51:59 -07006392 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006393 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006394
Glenn Kasten735f45f2014-08-18 15:51:59 -07006395 // reference to a fast track which is about to be removed
6396 sp<RecordTrack> fastTrackToRemove;
6397
Eric Laurent81784c32012-11-19 14:55:58 -08006398 { // scope for mLock
6399 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006400
Eric Laurent021cf962014-05-13 10:18:14 -07006401 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006402
Eric Laurent000a4192014-01-29 15:17:32 -08006403 // check exitPending here because checkForNewParameters_l() and
6404 // checkForNewParameters_l() can temporarily release mLock
6405 if (exitPending()) {
6406 break;
6407 }
6408
Eric Laurent5c25d562016-07-13 17:17:45 -07006409 // sleep with mutex unlocked
6410 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006411 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006412 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6413 ATRACE_END();
6414 sleepUs = 0;
6415 continue;
6416 }
6417
Glenn Kasten2b806402013-11-20 16:37:38 -08006418 // if no active track(s), then standby and release wakelock
6419 size_t size = mActiveTracks.size();
6420 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006421 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006422 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006423 releaseWakeLock_l();
6424 ALOGV("RecordThread: loop stopping");
6425 // go to sleep
6426 mWaitWorkCV.wait(mLock);
6427 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006428 goto reacquire_wakelock;
6429 }
6430
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006431 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006432 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006433 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006434
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006435 activeTrack = mActiveTracks[i];
6436 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006437 if (activeTrack->isFastTrack()) {
6438 ALOG_ASSERT(fastTrackToRemove == 0);
6439 fastTrackToRemove = activeTrack;
6440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006441 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006442 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006443 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006444 continue;
6445 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006446
6447 TrackBase::track_state activeTrackState = activeTrack->mState;
6448 switch (activeTrackState) {
6449
6450 case TrackBase::PAUSING:
6451 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006452 doBroadcast = true;
6453 size--;
6454 continue;
6455
6456 case TrackBase::STARTING_1:
6457 sleepUs = 10000;
6458 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006459 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006460 continue;
6461
6462 case TrackBase::STARTING_2:
6463 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006464 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006465 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006466 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006467 break;
6468
6469 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006470 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006471 break;
6472
6473 case TrackBase::IDLE:
6474 i++;
6475 continue;
6476
6477 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006478 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006479 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006480
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006481 activeTracks.add(activeTrack);
6482 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006483
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006484 if (activeTrack->isFastTrack()) {
6485 ALOG_ASSERT(!mFastTrackAvail);
6486 ALOG_ASSERT(fastTrack == 0);
6487 fastTrack = activeTrack;
6488 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006489 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006490
Andy Hungdae27702016-10-31 14:01:16 -07006491 mActiveTracks.updatePowerState(this);
6492
Kevin Rocard069c2712018-03-29 19:09:14 -07006493 updateMetadata_l();
6494
Eric Laurent5c25d562016-07-13 17:17:45 -07006495 if (allStopped) {
6496 standbyIfNotAlreadyInStandby();
6497 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006498 if (doBroadcast) {
6499 mStartStopCond.broadcast();
6500 }
6501
6502 // sleep if there are no active tracks to process
6503 if (activeTracks.size() == 0) {
6504 if (sleepUs == 0) {
6505 sleepUs = kRecordThreadSleepUs;
6506 }
6507 continue;
6508 }
6509 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006510
Eric Laurent81784c32012-11-19 14:55:58 -08006511 lockEffectChains_l(effectChains);
6512 }
6513
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006514 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006515
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006516 size_t size = effectChains.size();
6517 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006518 // thread mutex is not locked, but effect chain is locked
6519 effectChains[i]->process_l();
6520 }
6521
Glenn Kasten735f45f2014-08-18 15:51:59 -07006522 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006523 if (mFastCapture != 0) {
6524 FastCaptureStateQueue *sq = mFastCapture->sq();
6525 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006526 bool didModify = false;
6527 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006528 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6529 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6530 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6531 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6532 if (old == -1) {
6533 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6534 }
6535 }
6536 state->mCommand = FastCaptureState::READ_WRITE;
6537#if 0 // FIXME
6538 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006539 FastThreadDumpState::kSamplingNforLowRamDevice :
6540 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006541#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006542 didModify = true;
6543 }
6544 audio_track_cblk_t *cblkOld = state->mCblk;
6545 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6546 if (cblkNew != cblkOld) {
6547 state->mCblk = cblkNew;
6548 // block until acked if removing a fast track
6549 if (cblkOld != NULL) {
6550 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6551 }
6552 didModify = true;
6553 }
6554 sq->end(didModify);
6555 if (didModify) {
6556 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006557#if 0
6558 if (kUseFastCapture == FastCapture_Dynamic) {
6559 mNormalSource = mPipeSource;
6560 }
6561#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006562 }
6563 }
6564
Glenn Kasten735f45f2014-08-18 15:51:59 -07006565 // now run the fast track destructor with thread mutex unlocked
6566 fastTrackToRemove.clear();
6567
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006568 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6569 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6570 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6571 // If destination is non-contiguous, first read past the nominal end of buffer, then
6572 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006573
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006574 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006575 ssize_t framesRead;
6576
6577 // If an NBAIO source is present, use it to read the normal capture's data
6578 if (mPipeSource != 0) {
6579 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006580 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hung57446612015-04-19 23:56:46 -07006581 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
Glenn Kastend79072e2016-01-06 08:41:20 -08006582 framesToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006583 // since pipe is non-blocking, simulate blocking input by waiting for 1/2 of
6584 // buffer size or at least for 20ms.
6585 size_t sleepFrames = max(
6586 min(mPipeFramesP2, mRsmpInFramesP2) / 2, FMS_20 * mSampleRate / 1000);
6587 if (framesRead <= (ssize_t) sleepFrames) {
6588 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6589 }
6590 if (framesRead < 0) {
6591 status_t status = (status_t) framesRead;
6592 switch (status) {
6593 case OVERRUN:
6594 ALOGW("overrun on read from pipe");
6595 framesRead = 0;
6596 break;
6597 case NEGOTIATE:
6598 ALOGE("re-negotiation is needed");
6599 framesRead = -1; // Will cause an attempt to recover.
6600 break;
6601 default:
6602 ALOGE("unknown error %d on read from pipe", status);
6603 break;
6604 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006605 }
6606 // otherwise use the HAL / AudioStreamIn directly
6607 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006608 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006609 size_t bytesRead;
6610 status_t result = mInput->stream->read(
6611 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006612 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006613 if (result < 0) {
6614 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006615 } else {
6616 framesRead = bytesRead / mFrameSize;
6617 }
6618 }
6619
Andy Hung3f0c9022016-01-15 17:49:46 -08006620 // Update server timestamp with server stats
6621 // systemTime() is optional if the hardware supports timestamps.
6622 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6623 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6624
6625 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006626 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006627 int64_t position, time;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006628 int ret = mInput->stream->getCapturePosition(&position, &time);
Andy Hung3f0c9022016-01-15 17:49:46 -08006629 if (ret == NO_ERROR) {
6630 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6631 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6632 // Note: In general record buffers should tend to be empty in
6633 // a properly running pipeline.
6634 //
6635 // Also, it is not advantageous to call get_presentation_position during the read
6636 // as the read obtains a lock, preventing the timestamp call from executing.
6637 }
6638 }
6639 // Use this to track timestamp information
6640 // ALOGD("%s", mTimestamp.toString().c_str());
6641
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006642 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006643 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006644 // Force input into standby so that it tries to recover at next read attempt
6645 inputStandBy();
6646 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006647 }
6648 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006649 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006650 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006651 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006652
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006653 if (mTeeSink != 0) {
Andy Hung57446612015-04-19 23:56:46 -07006654 (void) mTeeSink->write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006655 }
6656 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006657 {
6658 size_t part1 = mRsmpInFramesP2 - rear;
6659 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006660 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006661 (framesRead - part1) * mFrameSize);
6662 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006663 }
6664 rear = mRsmpInRear += framesRead;
6665
6666 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006667
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006668 // loop over each active track
6669 for (size_t i = 0; i < size; i++) {
6670 activeTrack = activeTracks[i];
6671
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006672 // skip fast tracks, as those are handled directly by FastCapture
6673 if (activeTrack->isFastTrack()) {
6674 continue;
6675 }
6676
Andy Hung73c02e42015-03-29 01:13:58 -07006677 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006678 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6679
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006680 enum {
6681 OVERRUN_UNKNOWN,
6682 OVERRUN_TRUE,
6683 OVERRUN_FALSE
6684 } overrun = OVERRUN_UNKNOWN;
6685
6686 // loop over getNextBuffer to handle circular sink
6687 for (;;) {
6688
6689 activeTrack->mSink.frameCount = ~0;
6690 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6691 size_t framesOut = activeTrack->mSink.frameCount;
6692 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6693
Andy Hung73c02e42015-03-29 01:13:58 -07006694 // check available frames and handle overrun conditions
6695 // if the record track isn't draining fast enough.
6696 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006697 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006698 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6699 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006700 overrun = OVERRUN_TRUE;
6701 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006702 if (framesOut == 0 || framesIn == 0) {
6703 break;
6704 }
6705
Andy Hung6770c6f2015-04-07 13:43:36 -07006706 // Don't allow framesOut to be larger than what is possible with resampling
6707 // from framesIn.
6708 // This isn't strictly necessary but helps limit buffer resizing in
6709 // RecordBufferConverter. TODO: remove when no longer needed.
6710 framesOut = min(framesOut,
6711 destinationFramesPossible(
6712 framesIn, mSampleRate, activeTrack->mSampleRate));
Andy Hung97a893e2015-03-29 01:03:07 -07006713 // process frames from the RecordThread buffer provider to the RecordTrack buffer
6714 framesOut = activeTrack->mRecordBufferConverter->convert(
6715 activeTrack->mSink.raw, activeTrack->mResamplerBufferProvider, framesOut);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006716
6717 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6718 overrun = OVERRUN_FALSE;
6719 }
6720
6721 if (activeTrack->mFramesToDrop == 0) {
6722 if (framesOut > 0) {
6723 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006724 // Sanitize before releasing if the track has no access to the source data
6725 // An idle UID receives silence from non virtual devices until active
6726 if (activeTrack->isSilenced()) {
6727 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6728 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006729 activeTrack->releaseBuffer(&activeTrack->mSink);
6730 }
6731 } else {
6732 // FIXME could do a partial drop of framesOut
6733 if (activeTrack->mFramesToDrop > 0) {
6734 activeTrack->mFramesToDrop -= framesOut;
6735 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006736 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006737 }
6738 } else {
6739 activeTrack->mFramesToDrop += framesOut;
6740 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6741 activeTrack->mSyncStartEvent->isCancelled()) {
6742 ALOGW("Synced record %s, session %d, trigger session %d",
6743 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6744 activeTrack->sessionId(),
6745 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006746 activeTrack->mSyncStartEvent->triggerSession() :
6747 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006748 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006749 }
6750 }
6751 }
6752
6753 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006754 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006755 }
6756 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006757
6758 switch (overrun) {
6759 case OVERRUN_TRUE:
6760 // client isn't retrieving buffers fast enough
6761 if (!activeTrack->setOverflow()) {
6762 nsecs_t now = systemTime();
6763 // FIXME should lastWarning per track?
6764 if ((now - lastWarning) > kWarningThrottleNs) {
6765 ALOGW("RecordThread: buffer overflow");
6766 lastWarning = now;
6767 }
6768 }
6769 break;
6770 case OVERRUN_FALSE:
6771 activeTrack->clearOverflow();
6772 break;
6773 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006774 break;
6775 }
6776
Andy Hung3f0c9022016-01-15 17:49:46 -08006777 // update frame information and push timestamp out
6778 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006779 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006780 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6781 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006782 }
6783
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006784unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006785 // enable changes in effect chain
6786 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006787 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006788 }
6789
Glenn Kasten93e471f2013-08-19 08:40:07 -07006790 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006791
6792 {
6793 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006794 for (size_t i = 0; i < mTracks.size(); i++) {
6795 sp<RecordTrack> track = mTracks[i];
6796 track->invalidate();
6797 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006798 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006799 mStartStopCond.broadcast();
6800 }
6801
6802 releaseWakeLock();
6803
6804 ALOGV("RecordThread %p exiting", this);
6805 return false;
6806}
6807
Glenn Kasten93e471f2013-08-19 08:40:07 -07006808void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006809{
6810 if (!mStandby) {
6811 inputStandBy();
6812 mStandby = true;
6813 }
6814}
6815
6816void AudioFlinger::RecordThread::inputStandBy()
6817{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006818 // Idle the fast capture if it's currently running
6819 if (mFastCapture != 0) {
6820 FastCaptureStateQueue *sq = mFastCapture->sq();
6821 FastCaptureState *state = sq->begin();
6822 if (!(state->mCommand & FastCaptureState::IDLE)) {
6823 state->mCommand = FastCaptureState::COLD_IDLE;
6824 state->mColdFutexAddr = &mFastCaptureFutex;
6825 state->mColdGen++;
6826 mFastCaptureFutex = 0;
6827 sq->end();
6828 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6829 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6830#if 0
6831 if (kUseFastCapture == FastCapture_Dynamic) {
6832 // FIXME
6833 }
6834#endif
6835#ifdef AUDIO_WATCHDOG
6836 // FIXME
6837#endif
6838 } else {
6839 sq->end(false /*didModify*/);
6840 }
6841 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006842 status_t result = mInput->stream->standby();
6843 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07006844
6845 // If going into standby, flush the pipe source.
6846 if (mPipeSource.get() != nullptr) {
6847 const ssize_t flushed = mPipeSource->flush();
6848 if (flushed > 0) {
6849 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
6850 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
6851 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6852 }
6853 }
Eric Laurent81784c32012-11-19 14:55:58 -08006854}
6855
Glenn Kasten05997e22014-03-13 15:08:33 -07006856// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07006857sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08006858 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006859 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006860 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08006861 audio_format_t format,
6862 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08006863 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08006864 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08006865 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08006866 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07006867 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08006868 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006869 status_t *status,
6870 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08006871{
Glenn Kasten74935e42013-12-19 08:56:45 -08006872 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006873 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006874 sp<RecordTrack> track;
6875 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07006876 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006877 audio_input_flags_t requestedFlags = *flags;
6878 uint32_t sampleRate;
6879
6880 lStatus = initCheck();
6881 if (lStatus != NO_ERROR) {
6882 ALOGE("createRecordTrack_l() audio driver not initialized");
6883 goto Exit;
6884 }
6885
6886 if (*pSampleRate == 0) {
6887 *pSampleRate = mSampleRate;
6888 }
6889 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07006890
6891 // special case for FAST flag considered OK if fast capture is present
6892 if (hasFastCapture()) {
6893 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
6894 }
6895
Eric Laurentf14db3c2017-12-08 14:20:36 -08006896 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07006897 if ((*flags & inputFlags) != *flags) {
6898 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
6899 " input flags (%08x)",
6900 *flags, inputFlags);
6901 *flags = (audio_input_flags_t)(*flags & inputFlags);
6902 }
Eric Laurent81784c32012-11-19 14:55:58 -08006903
Glenn Kasten90e58b12013-07-31 16:16:02 -07006904 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07006905 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07006906 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07006907 // we formerly checked for a callback handler (non-0 tid),
6908 // but that is no longer required for TRANSFER_OBTAIN mode
6909 //
Glenn Kasten74105912014-07-03 12:28:53 -07006910 // frame count is not specified, or is exactly the pipe depth
6911 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006912 // PCM data
6913 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006914 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006915 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006916 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006917 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08006918 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07006919 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07006920 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006921 hasFastCapture() &&
6922 // there are sufficient fast track slots available
6923 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07006924 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07006925 // check compatibility with audio effects.
6926 Mutex::Autolock _l(mLock);
6927 // Do not accept FAST flag if the session has software effects
6928 sp<EffectChain> chain = getEffectChain_l(sessionId);
6929 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07006930 audio_input_flags_t old = *flags;
6931 chain->checkInputFlagCompatibility(flags);
6932 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006933 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
6934 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07006935 }
6936 }
Eric Laurent122f7e72016-06-29 11:53:29 -07006937 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006938 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
6939 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07006940 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006941 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
6942 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006943 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006944 this, frameCount, mFrameCount, mPipeFramesP2,
6945 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07006946 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07006947 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07006948 }
6949 }
6950
Eric Laurentf14db3c2017-12-08 14:20:36 -08006951 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
6952 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
6953 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
6954 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
6955 lStatus = BAD_TYPE;
6956 goto Exit;
6957 }
6958
Glenn Kasten74105912014-07-03 12:28:53 -07006959 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07006960 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07006961 // fast track: frame count is exactly the pipe depth
6962 frameCount = mPipeFramesP2;
6963 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08006964 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07006965 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07006966 // not fast track: max notification period is resampled equivalent of one HAL buffer time
6967 // or 20 ms if there is a fast capture
6968 // TODO This could be a roundupRatio inline, and const
6969 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
6970 * sampleRate + mSampleRate - 1) / mSampleRate;
6971 // minimum number of notification periods is at least kMinNotifications,
6972 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
6973 static const size_t kMinNotifications = 3;
6974 static const uint32_t kMinMs = 30;
6975 // TODO This could be a roundupRatio inline
6976 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
6977 // TODO This could be a roundupRatio inline
6978 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
6979 maxNotificationFrames;
6980 const size_t minFrameCount = maxNotificationFrames *
6981 max(kMinNotifications, minNotificationsByMs);
6982 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08006983 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
6984 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07006985 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07006986 }
Glenn Kasten74935e42013-12-19 08:56:45 -08006987 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08006988 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08006989
6990 { // scope for mLock
6991 Mutex::Autolock _l(mLock);
6992
Kevin Rocard1f564ac2018-03-29 13:53:10 -07006993 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07006994 format, channelMask, frameCount,
6995 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08006996 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08006997
Glenn Kasten03003332013-08-06 15:40:54 -07006998 lStatus = track->initCheck();
6999 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007000 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007001 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007002 goto Exit;
7003 }
7004 mTracks.add(track);
7005
Eric Laurent05067782016-06-01 18:27:28 -07007006 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007007 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7008 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7009 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007010 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007011 }
Eric Laurent81784c32012-11-19 14:55:58 -08007012 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007013
Eric Laurent81784c32012-11-19 14:55:58 -08007014 lStatus = NO_ERROR;
7015
7016Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007017 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007018 return track;
7019}
7020
7021status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7022 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007023 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007024{
7025 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7026 sp<ThreadBase> strongMe = this;
7027 status_t status = NO_ERROR;
7028
7029 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007030 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007031 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007032 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007033 triggerSession,
7034 recordTrack->sessionId(),
7035 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007036 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007037 // Sync event can be cancelled by the trigger session if the track is not in a
7038 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007039 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007040 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007041 } else {
7042 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007043 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007044 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007045 }
7046 }
7047
7048 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007049 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007050 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007051 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7052 if (recordTrack->mState == TrackBase::PAUSING) {
7053 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007054 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007055 } else {
7056 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007057 }
7058 return status;
7059 }
7060
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007061 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7062 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7063 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007064 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007065 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007066 status_t status = NO_ERROR;
7067 if (recordTrack->isExternalTrack()) {
7068 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007069 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007070 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007071 mLock.lock();
7072 // FIXME should verify that recordTrack is still in mActiveTracks
7073 if (status != NO_ERROR) {
7074 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007075 recordTrack->clearSyncStartEvent();
7076 ALOGV("RecordThread::start error %d", status);
7077 return status;
7078 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007079 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007080 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007081 // Catch up with current buffer indices if thread is already running.
7082 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7083 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7084 // see previously buffered data before it called start(), but with greater risk of overrun.
7085
Andy Hung73c02e42015-03-29 01:13:58 -07007086 recordTrack->mResamplerBufferProvider->reset();
Andy Hung97a893e2015-03-29 01:03:07 -07007087 // clear any converter state as new data will be discontinuous
7088 recordTrack->mRecordBufferConverter->reset();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007089 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007090 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007091 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007092 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007093 ALOGV("Record failed to start");
7094 status = BAD_VALUE;
7095 goto startError;
7096 }
Eric Laurent81784c32012-11-19 14:55:58 -08007097 return status;
7098 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007099
Eric Laurent81784c32012-11-19 14:55:58 -08007100startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007101 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007102 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007103 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007104 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007105 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007106 return status;
7107}
7108
Eric Laurent81784c32012-11-19 14:55:58 -08007109void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7110{
7111 sp<SyncEvent> strongEvent = event.promote();
7112
7113 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007114 sp<RefBase> ptr = strongEvent->cookie().promote();
7115 if (ptr != 0) {
7116 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7117 recordTrack->handleSyncStartEvent(strongEvent);
7118 }
Eric Laurent81784c32012-11-19 14:55:58 -08007119 }
7120}
7121
Glenn Kastena8356f62013-07-25 14:37:52 -07007122bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007123 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007124 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007125 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007126 return false;
7127 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007128 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007129 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007130 // signal thread to stop
7131 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007132 // do not wait for mStartStopCond if exiting
7133 if (exitPending()) {
7134 return true;
7135 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007136 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007137 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007138 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007139 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007140 ALOGV("Record stopped OK");
7141 return true;
7142 }
7143 return false;
7144}
7145
Glenn Kasten0f11b512014-01-31 16:18:54 -08007146bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007147{
7148 return false;
7149}
7150
Glenn Kasten0f11b512014-01-31 16:18:54 -08007151status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007152{
7153#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7154 if (!isValidSyncEvent(event)) {
7155 return BAD_VALUE;
7156 }
7157
Glenn Kastend848eb42016-03-08 13:42:11 -08007158 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007159 status_t ret = NAME_NOT_FOUND;
7160
7161 Mutex::Autolock _l(mLock);
7162
7163 for (size_t i = 0; i < mTracks.size(); i++) {
7164 sp<RecordTrack> track = mTracks[i];
7165 if (eventSession == track->sessionId()) {
7166 (void) track->setSyncEvent(event);
7167 ret = NO_ERROR;
7168 }
7169 }
7170 return ret;
7171#else
7172 return BAD_VALUE;
7173#endif
7174}
7175
jiabin653cc0a2018-01-17 17:54:10 -08007176status_t AudioFlinger::RecordThread::getActiveMicrophones(
7177 std::vector<media::MicrophoneInfo>* activeMicrophones)
7178{
7179 ALOGV("RecordThread::getActiveMicrophones");
7180 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007181 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7182 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007183}
7184
Kevin Rocard069c2712018-03-29 19:09:14 -07007185void AudioFlinger::RecordThread::updateMetadata_l()
7186{
7187 if (mInput == nullptr || mInput->stream == nullptr ||
7188 !mActiveTracks.readAndClearHasChanged()) {
7189 return;
7190 }
7191 StreamInHalInterface::SinkMetadata metadata;
7192 for (const sp<RecordTrack> &track : mActiveTracks) {
7193 // No track is invalid as this is called after prepareTrack_l in the same critical section
7194 metadata.tracks.push_back({
7195 .source = track->attributes().source,
7196 .gain = 1, // capture tracks do not have volumes
7197 });
7198 }
7199 mInput->stream->updateSinkMetadata(metadata);
7200}
7201
Eric Laurent81784c32012-11-19 14:55:58 -08007202// destroyTrack_l() must be called with ThreadBase::mLock held
7203void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7204{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007205 track->terminate();
7206 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007207 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007208 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007209 removeTrack_l(track);
7210 }
7211}
7212
7213void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7214{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007215 String8 result;
7216 track->appendDump(result, false /* active */);
7217 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7218
Eric Laurent81784c32012-11-19 14:55:58 -08007219 mTracks.remove(track);
7220 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007221 if (track->isFastTrack()) {
7222 ALOG_ASSERT(!mFastTrackAvail);
7223 mFastTrackAvail = true;
7224 }
Eric Laurent81784c32012-11-19 14:55:58 -08007225}
7226
7227void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7228{
7229 dumpInternals(fd, args);
7230 dumpTracks(fd, args);
7231 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007232 dprintf(fd, " Local log:\n");
7233 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007234}
7235
7236void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7237{
Glenn Kasten44182c22015-03-05 17:12:23 -08007238 dumpBase(fd, args);
7239
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007240 AudioStreamIn *input = mInput;
7241 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7242 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7243 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007244 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007245 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007246 }
Andy Hungbfa64962017-06-12 14:43:19 -07007247
7248 if (input != nullptr) {
7249 dprintf(fd, " Hal stream dump:\n");
7250 (void)input->stream->dump(fd);
7251 }
7252
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007253 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007254 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007255
Glenn Kasten2f90c512015-12-02 11:40:09 -08007256 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7257 // while we are dumping it. It may be inconsistent, but it won't mutate!
7258 // This is a large object so we place it on the heap.
7259 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7260 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7261 copy->dump(fd);
7262 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007263}
7264
Glenn Kasten0f11b512014-01-31 16:18:54 -08007265void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007266{
Eric Laurent81784c32012-11-19 14:55:58 -08007267 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007268 size_t numtracks = mTracks.size();
7269 size_t numactive = mActiveTracks.size();
7270 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007271 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007272 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007273 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007274 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007275 result.append(prefix);
Marco Nelissenb2208842014-02-07 14:00:50 -08007276 RecordTrack::appendDumpHeader(result);
7277 for (size_t i = 0; i < numtracks ; ++i) {
7278 sp<RecordTrack> track = mTracks[i];
7279 if (track != 0) {
7280 bool active = mActiveTracks.indexOf(track) >= 0;
7281 if (active) {
7282 numactiveseen++;
7283 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007284 result.append(prefix);
7285 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007286 }
Eric Laurent81784c32012-11-19 14:55:58 -08007287 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007288 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007289 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007290 }
7291
Marco Nelissenb2208842014-02-07 14:00:50 -08007292 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007293 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007294 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007295 result.append(prefix);
Eric Laurent81784c32012-11-19 14:55:58 -08007296 RecordTrack::appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007297 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007298 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007299 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007300 result.append(prefix);
7301 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007302 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007303 }
Eric Laurent81784c32012-11-19 14:55:58 -08007304
7305 }
7306 write(fd, result.string(), result.size());
7307}
7308
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007309void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7310{
7311 Mutex::Autolock _l(mLock);
7312 for (size_t i = 0; i < mTracks.size() ; i++) {
7313 sp<RecordTrack> track = mTracks[i];
7314 if (track != 0 && track->uid() == uid) {
7315 track->setSilenced(silenced);
7316 }
7317 }
7318}
Andy Hung73c02e42015-03-29 01:13:58 -07007319
7320void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7321{
7322 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7323 RecordThread *recordThread = (RecordThread *) threadBase.get();
7324 mRsmpInFront = recordThread->mRsmpInRear;
7325 mRsmpInUnrel = 0;
7326}
7327
7328void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7329 size_t *framesAvailable, bool *hasOverrun)
7330{
7331 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7332 RecordThread *recordThread = (RecordThread *) threadBase.get();
7333 const int32_t rear = recordThread->mRsmpInRear;
7334 const int32_t front = mRsmpInFront;
7335 const ssize_t filled = rear - front;
7336
7337 size_t framesIn;
7338 bool overrun = false;
7339 if (filled < 0) {
7340 // should not happen, but treat like a massive overrun and re-sync
7341 framesIn = 0;
7342 mRsmpInFront = rear;
7343 overrun = true;
7344 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7345 framesIn = (size_t) filled;
7346 } else {
7347 // client is not keeping up with server, but give it latest data
7348 framesIn = recordThread->mRsmpInFrames;
7349 mRsmpInFront = /* front = */ rear - framesIn;
7350 overrun = true;
7351 }
7352 if (framesAvailable != NULL) {
7353 *framesAvailable = framesIn;
7354 }
7355 if (hasOverrun != NULL) {
7356 *hasOverrun = overrun;
7357 }
7358}
7359
Eric Laurent81784c32012-11-19 14:55:58 -08007360// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007361status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007362 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007363{
Andy Hung73c02e42015-03-29 01:13:58 -07007364 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007365 if (threadBase == 0) {
7366 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007367 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007368 return NOT_ENOUGH_DATA;
7369 }
7370 RecordThread *recordThread = (RecordThread *) threadBase.get();
7371 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007372 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007373 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007374 // FIXME should not be P2 (don't want to increase latency)
7375 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007376 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007377 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007378 front &= recordThread->mRsmpInFramesP2 - 1;
7379 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007380 if (part1 > (size_t) filled) {
7381 part1 = filled;
7382 }
7383 size_t ask = buffer->frameCount;
7384 ALOG_ASSERT(ask > 0);
7385 if (part1 > ask) {
7386 part1 = ask;
7387 }
7388 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007389 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007390 buffer->raw = NULL;
7391 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007392 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007393 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007394 }
7395
Andy Hung57446612015-04-19 23:56:46 -07007396 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007397 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007398 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007399 return NO_ERROR;
7400}
7401
7402// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007403void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7404 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007405{
Glenn Kasten85948432013-08-19 12:09:05 -07007406 size_t stepCount = buffer->frameCount;
7407 if (stepCount == 0) {
7408 return;
7409 }
Andy Hung73c02e42015-03-29 01:13:58 -07007410 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7411 mRsmpInUnrel -= stepCount;
7412 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007413 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007414 buffer->frameCount = 0;
7415}
7416
Eric Laurentd8365c52017-07-16 15:27:05 -07007417void AudioFlinger::RecordThread::checkBtNrec()
7418{
7419 Mutex::Autolock _l(mLock);
7420 checkBtNrec_l();
7421}
7422
7423void AudioFlinger::RecordThread::checkBtNrec_l()
7424{
7425 // disable AEC and NS if the device is a BT SCO headset supporting those
7426 // pre processings
7427 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7428 mAudioFlinger->btNrecIsOff();
7429 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7430 for (size_t i = 0; i < mEffectChains.size(); i++) {
7431 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7432 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7433 }
7434 }
7435}
7436
Andy Hung97a893e2015-03-29 01:03:07 -07007437
Eric Laurent10351942014-05-08 18:49:52 -07007438bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7439 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007440{
7441 bool reconfig = false;
7442
Eric Laurent10351942014-05-08 18:49:52 -07007443 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007444
Eric Laurent10351942014-05-08 18:49:52 -07007445 audio_format_t reqFormat = mFormat;
7446 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007447 // 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 -07007448 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7449
7450 AudioParameter param = AudioParameter(keyValuePair);
7451 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007452
7453 // scope for AutoPark extends to end of method
7454 AutoPark<FastCapture> park(mFastCapture);
7455
Eric Laurent10351942014-05-08 18:49:52 -07007456 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7457 // channel count change can be requested. Do we mandate the first client defines the
7458 // HAL sampling rate and channel count or do we allow changes on the fly?
7459 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7460 samplingRate = value;
7461 reconfig = true;
7462 }
7463 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007464 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007465 status = BAD_VALUE;
7466 } else {
7467 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007468 reconfig = true;
7469 }
Eric Laurent10351942014-05-08 18:49:52 -07007470 }
7471 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7472 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007473 if (!audio_is_input_channel(mask) ||
7474 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007475 status = BAD_VALUE;
7476 } else {
7477 channelMask = mask;
7478 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007479 }
Eric Laurent10351942014-05-08 18:49:52 -07007480 }
7481 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7482 // do not accept frame count changes if tracks are open as the track buffer
7483 // size depends on frame count and correct behavior would not be guaranteed
7484 // if frame count is changed after track creation
7485 if (mActiveTracks.size() > 0) {
7486 status = INVALID_OPERATION;
7487 } else {
7488 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007489 }
Eric Laurent10351942014-05-08 18:49:52 -07007490 }
7491 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7492 // forward device change to effects that have requested to be
7493 // aware of attached audio device.
7494 for (size_t i = 0; i < mEffectChains.size(); i++) {
7495 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007496 }
Eric Laurent81784c32012-11-19 14:55:58 -08007497
Eric Laurent10351942014-05-08 18:49:52 -07007498 // store input device and output device but do not forward output device to audio HAL.
7499 // Note that status is ignored by the caller for output device
7500 // (see AudioFlinger::setParameters()
7501 if (audio_is_output_devices(value)) {
7502 mOutDevice = value;
7503 status = BAD_VALUE;
7504 } else {
7505 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007506 if (value != AUDIO_DEVICE_NONE) {
7507 mPrevInDevice = value;
7508 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007509 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007510 }
Eric Laurent10351942014-05-08 18:49:52 -07007511 }
7512 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7513 mAudioSource != (audio_source_t)value) {
7514 // forward device change to effects that have requested to be
7515 // aware of attached audio device.
7516 for (size_t i = 0; i < mEffectChains.size(); i++) {
7517 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007518 }
Eric Laurent10351942014-05-08 18:49:52 -07007519 mAudioSource = (audio_source_t)value;
7520 }
Glenn Kastene198c362013-08-13 09:13:36 -07007521
Eric Laurent10351942014-05-08 18:49:52 -07007522 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007523 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007524 if (status == INVALID_OPERATION) {
7525 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007526 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007527 }
7528 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007529 if (status == BAD_VALUE) {
7530 uint32_t sRate;
7531 audio_channel_mask_t channelMask;
7532 audio_format_t format;
7533 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7534 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7535 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7536 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7537 status = NO_ERROR;
7538 }
Eric Laurent81784c32012-11-19 14:55:58 -08007539 }
Eric Laurent10351942014-05-08 18:49:52 -07007540 if (status == NO_ERROR) {
7541 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007542 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007543 }
7544 }
Eric Laurent81784c32012-11-19 14:55:58 -08007545 }
Eric Laurent10351942014-05-08 18:49:52 -07007546
Eric Laurent81784c32012-11-19 14:55:58 -08007547 return reconfig;
7548}
7549
7550String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7551{
Eric Laurent81784c32012-11-19 14:55:58 -08007552 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007553 if (initCheck() == NO_ERROR) {
7554 String8 out_s8;
7555 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7556 return out_s8;
7557 }
Eric Laurent81784c32012-11-19 14:55:58 -08007558 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007559 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007560}
7561
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007562void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007563 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7564
7565 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007566
7567 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007568 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007569 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007570 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007571 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007572 desc->mChannelMask = mChannelMask;
7573 desc->mSamplingRate = mSampleRate;
7574 desc->mFormat = mFormat;
7575 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007576 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007577 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007578 break;
7579
Eric Laurent73e26b62015-04-27 16:55:58 -07007580 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007581 default:
7582 break;
7583 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007584 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007585}
7586
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007587void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007588{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007589 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7590 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007591 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007592 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007593 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007594 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7595 result = mInput->stream->getFrameSize(&mFrameSize);
7596 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7597 result = mInput->stream->getBufferSize(&mBufferSize);
7598 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007599 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007600 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7601 "mBufferSize=%lld, mFrameCount=%lld",
7602 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7603 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007604 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007605 // 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 -07007606 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007607 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007608 // A larger value should allow more old data to be read after a track calls start(),
7609 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007610 //
7611 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007612 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007613 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007614 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007615 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007616
7617 // TODO optimize audio capture buffer sizes ...
7618 // Here we calculate the size of the sliding buffer used as a source
7619 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7620 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7621 // be better to have it derived from the pipe depth in the long term.
7622 // The current value is higher than necessary. However it should not add to latency.
7623
Glenn Kasten85948432013-08-19 12:09:05 -07007624 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007625 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7626 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007627 // if posix_memalign fails, will segv here.
7628 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007629
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007630 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7631 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007632}
7633
Glenn Kasten5f972c02014-01-13 09:59:31 -08007634uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007635{
7636 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007637 uint32_t result;
7638 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7639 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007640 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007641 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007642}
7643
Eric Laurent4c415062016-06-17 16:14:16 -07007644// hasAudioSession_l() must be called with ThreadBase::mLock held
7645uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007646{
Eric Laurent81784c32012-11-19 14:55:58 -08007647 uint32_t result = 0;
7648 if (getEffectChain_l(sessionId) != 0) {
7649 result = EFFECT_SESSION;
7650 }
7651
7652 for (size_t i = 0; i < mTracks.size(); ++i) {
7653 if (sessionId == mTracks[i]->sessionId()) {
7654 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007655 if (mTracks[i]->isFastTrack()) {
7656 result |= FAST_SESSION;
7657 }
Eric Laurent81784c32012-11-19 14:55:58 -08007658 break;
7659 }
7660 }
7661
7662 return result;
7663}
7664
Glenn Kastend848eb42016-03-08 13:42:11 -08007665KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007666{
Glenn Kastend848eb42016-03-08 13:42:11 -08007667 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007668 Mutex::Autolock _l(mLock);
7669 for (size_t j = 0; j < mTracks.size(); ++j) {
7670 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007671 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007672 if (ids.indexOfKey(sessionId) < 0) {
7673 ids.add(sessionId, true);
7674 }
7675 }
7676 return ids;
7677}
7678
7679AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7680{
7681 Mutex::Autolock _l(mLock);
7682 AudioStreamIn *input = mInput;
7683 mInput = NULL;
7684 return input;
7685}
7686
7687// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007688sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007689{
7690 if (mInput == NULL) {
7691 return NULL;
7692 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007693 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007694}
7695
7696status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7697{
7698 // only one chain per input thread
7699 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007700 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007701 return INVALID_OPERATION;
7702 }
7703 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007704 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007705 chain->setInBuffer(NULL);
7706 chain->setOutBuffer(NULL);
7707
7708 checkSuspendOnAddEffectChain_l(chain);
7709
Eric Laurent1b928682014-10-02 19:41:47 -07007710 // make sure enabled pre processing effects state is communicated to the HAL as we
7711 // just moved them to a new input stream.
7712 chain->syncHalEffectsState();
7713
Eric Laurent81784c32012-11-19 14:55:58 -08007714 mEffectChains.add(chain);
7715
7716 return NO_ERROR;
7717}
7718
7719size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7720{
7721 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7722 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007723 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007724 chain.get(), mEffectChains.size(), this);
7725 if (mEffectChains.size() == 1) {
7726 mEffectChains.removeAt(0);
7727 }
7728 return 0;
7729}
7730
Eric Laurent1c333e22014-05-20 10:48:17 -07007731status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7732 audio_patch_handle_t *handle)
7733{
7734 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007735
7736 // store new device and send to effects
7737 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007738 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007739 for (size_t i = 0; i < mEffectChains.size(); i++) {
7740 mEffectChains[i]->setDevice_l(mInDevice);
7741 }
7742
Eric Laurentd8365c52017-07-16 15:27:05 -07007743 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007744
7745 // store new source and send to effects
7746 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7747 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007748 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007749 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007750 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007751 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007752
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007753 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007754 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7755 status = hwDevice->createAudioPatch(patch->num_sources,
7756 patch->sources,
7757 patch->num_sinks,
7758 patch->sinks,
7759 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007760 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007761 char *address;
7762 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7763 address = audio_device_address_to_parameter(
7764 patch->sources[0].ext.device.type,
7765 patch->sources[0].ext.device.address);
7766 } else {
7767 address = (char *)calloc(1, 1);
7768 }
7769 AudioParameter param = AudioParameter(String8(address));
7770 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007771 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007772 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007773 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007774 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007775 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007776 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007777 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007778
Eric Laurente8726fe2015-06-26 09:39:24 -07007779 if (mInDevice != mPrevInDevice) {
7780 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7781 mPrevInDevice = mInDevice;
7782 }
Eric Laurent296fb132015-05-01 11:38:42 -07007783
Eric Laurent1c333e22014-05-20 10:48:17 -07007784 return status;
7785}
7786
7787status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7788{
7789 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007790
7791 mInDevice = AUDIO_DEVICE_NONE;
7792
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007793 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007794 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7795 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007796 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007797 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007798 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007799 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007800 }
7801 return status;
7802}
7803
Eric Laurent83b88082014-06-20 18:31:16 -07007804void AudioFlinger::RecordThread::addPatchRecord(const sp<PatchRecord>& record)
7805{
7806 Mutex::Autolock _l(mLock);
7807 mTracks.add(record);
7808}
7809
7810void AudioFlinger::RecordThread::deletePatchRecord(const sp<PatchRecord>& record)
7811{
7812 Mutex::Autolock _l(mLock);
7813 destroyTrack_l(record);
7814}
7815
7816void AudioFlinger::RecordThread::getAudioPortConfig(struct audio_port_config *config)
7817{
7818 ThreadBase::getAudioPortConfig(config);
7819 config->role = AUDIO_PORT_ROLE_SINK;
7820 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7821 config->ext.mix.usecase.source = mAudioSource;
7822}
Eric Laurent1c333e22014-05-20 10:48:17 -07007823
Eric Laurent6acd1d42017-01-04 14:23:29 -08007824// ----------------------------------------------------------------------------
7825// Mmap
7826// ----------------------------------------------------------------------------
7827
7828AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7829 : mThread(thread)
7830{
Phil Burk9fabbf82017-08-03 12:02:00 -07007831 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08007832}
7833
7834AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
7835{
Phil Burk9fabbf82017-08-03 12:02:00 -07007836 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007837}
7838
7839status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
7840 struct audio_mmap_buffer_info *info)
7841{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007842 return mThread->createMmapBuffer(minSizeFrames, info);
7843}
7844
7845status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
7846{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007847 return mThread->getMmapPosition(position);
7848}
7849
Eric Laurenta54f1282017-07-01 19:39:32 -07007850status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08007851 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007852
7853{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007854 return mThread->start(client, handle);
7855}
7856
7857status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
7858{
Eric Laurent6acd1d42017-01-04 14:23:29 -08007859 return mThread->stop(handle);
7860}
7861
Eric Laurent18b57012017-02-13 16:23:52 -08007862status_t AudioFlinger::MmapThreadHandle::standby()
7863{
Eric Laurent18b57012017-02-13 16:23:52 -08007864 return mThread->standby();
7865}
7866
Eric Laurent6acd1d42017-01-04 14:23:29 -08007867
7868AudioFlinger::MmapThread::MmapThread(
7869 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
7870 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
7871 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
7872 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007873 mSessionId(AUDIO_SESSION_NONE),
7874 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007875 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
7876 mActiveTracks(&this->mLocalLog)
Eric Laurent6acd1d42017-01-04 14:23:29 -08007877{
Eric Laurent18b57012017-02-13 16:23:52 -08007878 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007879 readHalParameters_l();
7880}
7881
7882AudioFlinger::MmapThread::~MmapThread()
7883{
Eric Laurent18b57012017-02-13 16:23:52 -08007884 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007885}
7886
7887void AudioFlinger::MmapThread::onFirstRef()
7888{
7889 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
7890}
7891
7892void AudioFlinger::MmapThread::disconnect()
7893{
7894 for (const sp<MmapTrack> &t : mActiveTracks) {
7895 stop(t->portId());
7896 }
Phil Burk9fabbf82017-08-03 12:02:00 -07007897 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08007898 if (isOutput()) {
7899 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
7900 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08007901 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007902 }
7903}
7904
7905
7906void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
7907 audio_stream_type_t streamType __unused,
7908 audio_session_t sessionId,
7909 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007910 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007911 audio_port_handle_t portId)
7912{
7913 mAttr = *attr;
7914 mSessionId = sessionId;
7915 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007916 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007917 mPortId = portId;
7918}
7919
7920status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
7921 struct audio_mmap_buffer_info *info)
7922{
7923 if (mHalStream == 0) {
7924 return NO_INIT;
7925 }
Eric Laurent18b57012017-02-13 16:23:52 -08007926 mStandby = true;
7927 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08007928 return mHalStream->createMmapBuffer(minSizeFrames, info);
7929}
7930
7931status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
7932{
7933 if (mHalStream == 0) {
7934 return NO_INIT;
7935 }
7936 return mHalStream->getMmapPosition(position);
7937}
7938
Eric Laurenta54f1282017-07-01 19:39:32 -07007939status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08007940 audio_port_handle_t *handle)
7941{
Eric Laurenta54f1282017-07-01 19:39:32 -07007942 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
7943 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007944 if (mHalStream == 0) {
7945 return NO_INIT;
7946 }
7947
7948 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08007949
Eric Laurenta54f1282017-07-01 19:39:32 -07007950 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08007951 // for the first track, reuse portId and session allocated when the stream was opened
Phil Burk7f6b40d2017-02-09 13:18:38 -08007952 ret = mHalStream->start();
7953 if (ret != NO_ERROR) {
7954 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
7955 return ret;
7956 }
Eric Laurent18b57012017-02-13 16:23:52 -08007957 mStandby = false;
Eric Laurenta54f1282017-07-01 19:39:32 -07007958 return NO_ERROR;
7959 }
7960
7961 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
7962
7963 audio_io_handle_t io = mId;
7964 if (isOutput()) {
7965 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7966 config.sample_rate = mSampleRate;
7967 config.channel_mask = mChannelMask;
7968 config.format = mFormat;
7969 audio_stream_type_t stream = streamType();
7970 audio_output_flags_t flags =
7971 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007972 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007973 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
7974 mSessionId,
7975 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02007976 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07007977 client.clientUid,
7978 &config,
7979 flags,
7980 &deviceId,
7981 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08007982 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07007983 audio_config_base_t config;
7984 config.sample_rate = mSampleRate;
7985 config.channel_mask = mChannelMask;
7986 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07007987 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07007988 ret = AudioSystem::getInputForAttr(&mAttr, &io,
7989 mSessionId,
7990 client.clientPid,
7991 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08007992 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07007993 &config,
7994 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
7995 &deviceId,
7996 &portId);
7997 }
7998 // APM should not chose a different input or output stream for the same set of attributes
7999 // and audo configuration
8000 if (ret != NO_ERROR || io != mId) {
8001 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8002 __FUNCTION__, ret, io, mId);
8003 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008004 }
8005
8006 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008007 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008008 } else {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008009 // TODO: Block recording for idle UIDs (b/72134552)
8010 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08008011 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008012 }
8013
8014 // abort if start is rejected by audio policy manager
8015 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008016 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008017 if (mActiveTracks.size() != 0) {
8018 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008019 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008020 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008021 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008022 }
Eric Laurent18b57012017-02-13 16:23:52 -08008023 } else {
8024 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008025 }
8026 return PERMISSION_DENIED;
8027 }
8028
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008029 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8030 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -07008031 client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008032
8033 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008034 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008035 if (chain != 0) {
8036 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8037 chain->incTrackCnt();
8038 chain->incActiveTrackCnt();
8039 }
8040
8041 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008042 broadcast_l();
8043
Eric Laurenta54f1282017-07-01 19:39:32 -07008044 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008045
8046 return NO_ERROR;
8047}
8048
8049status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8050{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008051 ALOGV("%s handle %d", __FUNCTION__, handle);
8052
8053 if (mHalStream == 0) {
8054 return NO_INIT;
8055 }
8056
Eric Laurenta54f1282017-07-01 19:39:32 -07008057 if (handle == mPortId) {
8058 mHalStream->stop();
8059 return NO_ERROR;
8060 }
8061
Eric Laurent6acd1d42017-01-04 14:23:29 -08008062 sp<MmapTrack> track;
8063 for (const sp<MmapTrack> &t : mActiveTracks) {
8064 if (handle == t->portId()) {
8065 track = t;
8066 break;
8067 }
8068 }
8069 if (track == 0) {
8070 return BAD_VALUE;
8071 }
8072
8073 mActiveTracks.remove(track);
8074
8075 if (isOutput()) {
8076 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008077 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008078 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008079 AudioSystem::stopInput(track->portId());
8080 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008081 }
8082
8083 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8084 if (chain != 0) {
8085 chain->decActiveTrackCnt();
8086 chain->decTrackCnt();
8087 }
8088
8089 broadcast_l();
8090
Eric Laurent6acd1d42017-01-04 14:23:29 -08008091 return NO_ERROR;
8092}
8093
Eric Laurent18b57012017-02-13 16:23:52 -08008094status_t AudioFlinger::MmapThread::standby()
8095{
8096 ALOGV("%s", __FUNCTION__);
8097
8098 if (mHalStream == 0) {
8099 return NO_INIT;
8100 }
8101 if (mActiveTracks.size() != 0) {
8102 return INVALID_OPERATION;
8103 }
8104 mHalStream->standby();
8105 mStandby = true;
8106 releaseWakeLock();
8107 return NO_ERROR;
8108}
8109
Eric Laurent6acd1d42017-01-04 14:23:29 -08008110
8111void AudioFlinger::MmapThread::readHalParameters_l()
8112{
8113 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8114 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8115 mFormat = mHALFormat;
8116 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8117 result = mHalStream->getFrameSize(&mFrameSize);
8118 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8119 result = mHalStream->getBufferSize(&mBufferSize);
8120 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8121 mFrameCount = mBufferSize / mFrameSize;
8122}
8123
8124bool AudioFlinger::MmapThread::threadLoop()
8125{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008126 checkSilentMode_l();
8127
8128 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8129
8130 while (!exitPending())
8131 {
8132 Mutex::Autolock _l(mLock);
8133 Vector< sp<EffectChain> > effectChains;
8134
8135 if (mSignalPending) {
8136 // A signal was raised while we were unlocked
8137 mSignalPending = false;
8138 } else {
8139 if (mConfigEvents.isEmpty()) {
8140 // we're about to wait, flush the binder command buffer
8141 IPCThreadState::self()->flushCommands();
8142
8143 if (exitPending()) {
8144 break;
8145 }
8146
Eric Laurent6acd1d42017-01-04 14:23:29 -08008147 // wait until we have something to do...
8148 ALOGV("%s going to sleep", myName.string());
8149 mWaitWorkCV.wait(mLock);
8150 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008151
8152 checkSilentMode_l();
8153
8154 continue;
8155 }
8156 }
8157
8158 processConfigEvents_l();
8159
8160 processVolume_l();
8161
8162 checkInvalidTracks_l();
8163
8164 mActiveTracks.updatePowerState(this);
8165
Kevin Rocard069c2712018-03-29 19:09:14 -07008166 updateMetadata_l();
8167
Eric Laurent6acd1d42017-01-04 14:23:29 -08008168 lockEffectChains_l(effectChains);
8169 for (size_t i = 0; i < effectChains.size(); i ++) {
8170 effectChains[i]->process_l();
8171 }
8172 // enable changes in effect chain
8173 unlockEffectChains(effectChains);
8174 // Effect chains will be actually deleted here if they were removed from
8175 // mEffectChains list during mixing or effects processing
8176 }
8177
8178 threadLoop_exit();
8179
8180 if (!mStandby) {
8181 threadLoop_standby();
8182 mStandby = true;
8183 }
8184
Eric Laurent6acd1d42017-01-04 14:23:29 -08008185 ALOGV("Thread %p type %d exiting", this, mType);
8186 return false;
8187}
8188
8189// checkForNewParameter_l() must be called with ThreadBase::mLock held
8190bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8191 status_t& status)
8192{
8193 AudioParameter param = AudioParameter(keyValuePair);
8194 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008195 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008196 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008197 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008198 // forward device change to effects that have requested to be
8199 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008200 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008201 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008202 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008203 }
8204 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008205 if (audio_is_output_devices(device)) {
8206 mOutDevice = device;
8207 if (!isOutput()) {
8208 sendToHal = false;
8209 }
8210 } else {
8211 mInDevice = device;
8212 if (device != AUDIO_DEVICE_NONE) {
8213 mPrevInDevice = value;
8214 }
8215 // TODO: implement and call checkBtNrec_l();
8216 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008217 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008218 if (sendToHal) {
8219 status = mHalStream->setParameters(keyValuePair);
8220 } else {
8221 status = NO_ERROR;
8222 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008223
8224 return false;
8225}
8226
8227String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8228{
8229 Mutex::Autolock _l(mLock);
8230 String8 out_s8;
8231 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8232 return out_s8;
8233 }
8234 return String8();
8235}
8236
8237void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8238 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8239
8240 desc->mIoHandle = mId;
8241
8242 switch (event) {
8243 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008244 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008245 case AUDIO_INPUT_CONFIG_CHANGED:
8246 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008247 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008248 case AUDIO_OUTPUT_CONFIG_CHANGED:
8249 desc->mPatch = mPatch;
8250 desc->mChannelMask = mChannelMask;
8251 desc->mSamplingRate = mSampleRate;
8252 desc->mFormat = mFormat;
8253 desc->mFrameCount = mFrameCount;
8254 desc->mFrameCountHAL = mFrameCount;
8255 desc->mLatency = 0;
8256 break;
8257
8258 case AUDIO_INPUT_CLOSED:
8259 case AUDIO_OUTPUT_CLOSED:
8260 default:
8261 break;
8262 }
8263 mAudioFlinger->ioConfigChanged(event, desc, pid);
8264}
8265
8266status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8267 audio_patch_handle_t *handle)
8268{
8269 status_t status = NO_ERROR;
8270
8271 // store new device and send to effects
8272 audio_devices_t type = AUDIO_DEVICE_NONE;
8273 audio_port_handle_t deviceId;
8274 if (isOutput()) {
8275 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8276 type |= patch->sinks[i].ext.device.type;
8277 }
8278 deviceId = patch->sinks[0].id;
8279 } else {
8280 type = patch->sources[0].ext.device.type;
8281 deviceId = patch->sources[0].id;
8282 }
8283
8284 for (size_t i = 0; i < mEffectChains.size(); i++) {
8285 mEffectChains[i]->setDevice_l(type);
8286 }
8287
8288 if (isOutput()) {
8289 mOutDevice = type;
8290 } else {
8291 mInDevice = type;
8292 // store new source and send to effects
8293 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8294 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8295 for (size_t i = 0; i < mEffectChains.size(); i++) {
8296 mEffectChains[i]->setAudioSource_l(mAudioSource);
8297 }
8298 }
8299 }
8300
8301 if (mAudioHwDev->supportsAudioPatches()) {
8302 status = mHalDevice->createAudioPatch(patch->num_sources,
8303 patch->sources,
8304 patch->num_sinks,
8305 patch->sinks,
8306 handle);
8307 } else {
8308 char *address;
8309 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8310 //FIXME: we only support address on first sink with HAL version < 3.0
8311 address = audio_device_address_to_parameter(
8312 patch->sinks[0].ext.device.type,
8313 patch->sinks[0].ext.device.address);
8314 } else {
8315 address = (char *)calloc(1, 1);
8316 }
8317 AudioParameter param = AudioParameter(String8(address));
8318 free(address);
8319 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8320 if (!isOutput()) {
8321 param.addInt(String8(AudioParameter::keyInputSource),
8322 (int)patch->sinks[0].ext.mix.usecase.source);
8323 }
8324 status = mHalStream->setParameters(param.toString());
8325 *handle = AUDIO_PATCH_HANDLE_NONE;
8326 }
8327
8328 if (isOutput() && mPrevOutDevice != mOutDevice) {
8329 mPrevOutDevice = type;
8330 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008331 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008332 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008333 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008334 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008335 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008336 }
8337 if (!isOutput() && mPrevInDevice != mInDevice) {
8338 mPrevInDevice = type;
8339 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008340 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008341 if (mDeviceId != deviceId && callback != 0) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008342 callback->onRoutingChanged(deviceId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008343 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008344 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008345 }
8346 return status;
8347}
8348
8349status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8350{
8351 status_t status = NO_ERROR;
8352
8353 mInDevice = AUDIO_DEVICE_NONE;
8354
8355 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8356 supportsAudioPatches : false;
8357
8358 if (supportsAudioPatches) {
8359 status = mHalDevice->releaseAudioPatch(handle);
8360 } else {
8361 AudioParameter param;
8362 param.addInt(String8(AudioParameter::keyRouting), 0);
8363 status = mHalStream->setParameters(param.toString());
8364 }
8365 return status;
8366}
8367
8368void AudioFlinger::MmapThread::getAudioPortConfig(struct audio_port_config *config)
8369{
8370 ThreadBase::getAudioPortConfig(config);
8371 if (isOutput()) {
8372 config->role = AUDIO_PORT_ROLE_SOURCE;
8373 config->ext.mix.hw_module = mAudioHwDev->handle();
8374 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8375 } else {
8376 config->role = AUDIO_PORT_ROLE_SINK;
8377 config->ext.mix.hw_module = mAudioHwDev->handle();
8378 config->ext.mix.usecase.source = mAudioSource;
8379 }
8380}
8381
8382status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8383{
8384 audio_session_t session = chain->sessionId();
8385
8386 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8387 // Attach all tracks with same session ID to this chain.
8388 // indicate all active tracks in the chain
8389 for (const sp<MmapTrack> &track : mActiveTracks) {
8390 if (session == track->sessionId()) {
8391 chain->incTrackCnt();
8392 chain->incActiveTrackCnt();
8393 }
8394 }
8395
8396 chain->setThread(this);
8397 chain->setInBuffer(nullptr);
8398 chain->setOutBuffer(nullptr);
8399 chain->syncHalEffectsState();
8400
8401 mEffectChains.add(chain);
8402 checkSuspendOnAddEffectChain_l(chain);
8403 return NO_ERROR;
8404}
8405
8406size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8407{
8408 audio_session_t session = chain->sessionId();
8409
8410 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8411
8412 for (size_t i = 0; i < mEffectChains.size(); i++) {
8413 if (chain == mEffectChains[i]) {
8414 mEffectChains.removeAt(i);
8415 // detach all active tracks from the chain
8416 // detach all tracks with same session ID from this chain
8417 for (const sp<MmapTrack> &track : mActiveTracks) {
8418 if (session == track->sessionId()) {
8419 chain->decActiveTrackCnt();
8420 chain->decTrackCnt();
8421 }
8422 }
8423 break;
8424 }
8425 }
8426 return mEffectChains.size();
8427}
8428
8429// hasAudioSession_l() must be called with ThreadBase::mLock held
8430uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8431{
8432 uint32_t result = 0;
8433 if (getEffectChain_l(sessionId) != 0) {
8434 result = EFFECT_SESSION;
8435 }
8436
8437 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8438 sp<MmapTrack> track = mActiveTracks[i];
8439 if (sessionId == track->sessionId()) {
8440 result |= TRACK_SESSION;
8441 if (track->isFastTrack()) {
8442 result |= FAST_SESSION;
8443 }
8444 break;
8445 }
8446 }
8447
8448 return result;
8449}
8450
8451void AudioFlinger::MmapThread::threadLoop_standby()
8452{
8453 mHalStream->standby();
8454}
8455
8456void AudioFlinger::MmapThread::threadLoop_exit()
8457{
Phil Burk7dce7282017-09-27 13:51:41 -07008458 // Do not call callback->onTearDown() because it is redundant for thread exit
8459 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008460}
8461
8462status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8463{
8464 return BAD_VALUE;
8465}
8466
8467bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8468{
8469 return false;
8470}
8471
8472status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8473 const effect_descriptor_t *desc, audio_session_t sessionId)
8474{
8475 // No global effect sessions on mmap threads
8476 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8477 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8478 desc->name, mThreadName);
8479 return BAD_VALUE;
8480 }
8481
8482 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8483 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8484 desc->name);
8485 return BAD_VALUE;
8486 }
8487 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008488 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8489 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490 return BAD_VALUE;
8491 }
8492
8493 // Only allow effects without processing load or latency
8494 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8495 return BAD_VALUE;
8496 }
8497
8498 return NO_ERROR;
8499
8500}
8501
8502void AudioFlinger::MmapThread::checkInvalidTracks_l()
8503{
8504 for (const sp<MmapTrack> &track : mActiveTracks) {
8505 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008506 sp<MmapStreamCallback> callback = mCallback.promote();
8507 if (callback != 0) {
8508 callback->onTearDown();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008509 }
8510 break;
8511 }
8512 }
8513}
8514
8515void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8516{
8517 dumpInternals(fd, args);
8518 dumpTracks(fd, args);
8519 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008520 dprintf(fd, " Local log:\n");
8521 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008522}
8523
8524void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8525{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008526 dumpBase(fd, args);
8527
8528 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8529 mAttr.content_type, mAttr.usage, mAttr.source);
8530 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8531 if (mActiveTracks.size() == 0) {
8532 dprintf(fd, " No active clients\n");
8533 }
8534}
8535
8536void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8537{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008538 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008539 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008540 dprintf(fd, " %zu Tracks\n", numtracks);
8541 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008542 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008543 result.append(prefix);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008544 MmapTrack::appendDumpHeader(result);
8545 for (size_t i = 0; i < numtracks ; ++i) {
8546 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008547 result.append(prefix);
8548 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008549 }
8550 } else {
8551 dprintf(fd, "\n");
8552 }
8553 write(fd, result.string(), result.size());
8554}
8555
8556AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8557 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8558 AudioHwDevice *hwDev, AudioStreamOut *output,
8559 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8560 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8561 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008562 mStreamVolume(1.0),
8563 mStreamMute(false),
8564 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8565 mNoCallbackWarningCount(0),
8566 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008567{
8568 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8569 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8570 mMasterVolume = audioFlinger->masterVolume_l();
8571 mMasterMute = audioFlinger->masterMute_l();
8572 if (mAudioHwDev) {
8573 if (mAudioHwDev->canSetMasterVolume()) {
8574 mMasterVolume = 1.0;
8575 }
8576
8577 if (mAudioHwDev->canSetMasterMute()) {
8578 mMasterMute = false;
8579 }
8580 }
8581}
8582
8583void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8584 audio_stream_type_t streamType,
8585 audio_session_t sessionId,
8586 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008587 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008588 audio_port_handle_t portId)
8589{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008590 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008591 mStreamType = streamType;
8592}
8593
8594AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8595{
8596 Mutex::Autolock _l(mLock);
8597 AudioStreamOut *output = mOutput;
8598 mOutput = NULL;
8599 return output;
8600}
8601
8602void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8603{
8604 Mutex::Autolock _l(mLock);
8605 // Don't apply master volume in SW if our HAL can do it for us.
8606 if (mAudioHwDev &&
8607 mAudioHwDev->canSetMasterVolume()) {
8608 mMasterVolume = 1.0;
8609 } else {
8610 mMasterVolume = value;
8611 }
8612}
8613
8614void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8615{
8616 Mutex::Autolock _l(mLock);
8617 // Don't apply master mute in SW if our HAL can do it for us.
8618 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8619 mMasterMute = false;
8620 } else {
8621 mMasterMute = muted;
8622 }
8623}
8624
8625void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8626{
8627 Mutex::Autolock _l(mLock);
8628 if (stream == mStreamType) {
8629 mStreamVolume = value;
8630 broadcast_l();
8631 }
8632}
8633
8634float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8635{
8636 Mutex::Autolock _l(mLock);
8637 if (stream == mStreamType) {
8638 return mStreamVolume;
8639 }
8640 return 0.0f;
8641}
8642
8643void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8644{
8645 Mutex::Autolock _l(mLock);
8646 if (stream == mStreamType) {
8647 mStreamMute= muted;
8648 broadcast_l();
8649 }
8650}
8651
8652void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8653{
8654 Mutex::Autolock _l(mLock);
8655 if (streamType == mStreamType) {
8656 for (const sp<MmapTrack> &track : mActiveTracks) {
8657 track->invalidate();
8658 }
8659 broadcast_l();
8660 }
8661}
8662
8663void AudioFlinger::MmapPlaybackThread::processVolume_l()
8664{
8665 float volume;
8666
8667 if (mMasterMute || mStreamMute) {
8668 volume = 0;
8669 } else {
8670 volume = mMasterVolume * mStreamVolume;
8671 }
8672
8673 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008674
8675 // Convert volumes from float to 8.24
8676 uint32_t vol = (uint32_t)(volume * (1 << 24));
8677
8678 // Delegate volume control to effect in track effect chain if needed
8679 // only one effect chain can be present on DirectOutputThread, so if
8680 // there is one, the track is connected to it
8681 if (!mEffectChains.isEmpty()) {
8682 mEffectChains[0]->setVolume_l(&vol, &vol);
8683 volume = (float)vol / (1 << 24);
8684 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008685 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008686 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8687 mHalVolFloat = volume; // HW volume control worked, so update value.
8688 mNoCallbackWarningCount = 0;
8689 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008690 sp<MmapStreamCallback> callback = mCallback.promote();
8691 if (callback != 0) {
8692 int channelCount;
8693 if (isOutput()) {
8694 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8695 } else {
8696 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8697 }
8698 Vector<float> values;
8699 for (int i = 0; i < channelCount; i++) {
8700 values.add(volume);
8701 }
8702 callback->onVolumeChanged(mChannelMask, values);
Phil Burk56ecf3e2018-03-12 15:38:17 -07008703 mHalVolFloat = volume; // SW volume control worked, so update value.
8704 mNoCallbackWarningCount = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008705 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008706 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8707 ALOGW("Could not set MMAP stream volume: no volume callback!");
8708 mNoCallbackWarningCount++;
8709 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008710 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008711 }
8712 }
8713}
8714
Kevin Rocard069c2712018-03-29 19:09:14 -07008715void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8716{
8717 if (mOutput == nullptr || mOutput->stream == nullptr ||
8718 !mActiveTracks.readAndClearHasChanged()) {
8719 return;
8720 }
8721 StreamOutHalInterface::SourceMetadata metadata;
8722 for (const sp<MmapTrack> &track : mActiveTracks) {
8723 // No track is invalid as this is called after prepareTrack_l in the same critical section
8724 metadata.tracks.push_back({
8725 .usage = track->attributes().usage,
8726 .content_type = track->attributes().content_type,
8727 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8728 });
8729 }
8730 mOutput->stream->updateSourceMetadata(metadata);
8731}
8732
Eric Laurent6acd1d42017-01-04 14:23:29 -08008733void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8734{
8735 if (!mMasterMute) {
8736 char value[PROPERTY_VALUE_MAX];
8737 if (property_get("ro.audio.silent", value, "0") > 0) {
8738 char *endptr;
8739 unsigned long ul = strtoul(value, &endptr, 0);
8740 if (*endptr == '\0' && ul != 0) {
8741 ALOGD("Silence is golden");
8742 // The setprop command will not allow a property to be changed after
8743 // the first time it is set, so we don't have to worry about un-muting.
8744 setMasterMute_l(true);
8745 }
8746 }
8747 }
8748}
8749
8750void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8751{
8752 MmapThread::dumpInternals(fd, args);
8753
Glenn Kastend3bb6452016-12-05 18:14:37 -08008754 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8755 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008756 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8757}
8758
8759AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8760 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8761 AudioHwDevice *hwDev, AudioStreamIn *input,
8762 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8763 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8764 mInput(input)
8765{
8766 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8767 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8768}
8769
8770AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8771{
8772 Mutex::Autolock _l(mLock);
8773 AudioStreamIn *input = mInput;
8774 mInput = NULL;
8775 return input;
8776}
Kevin Rocard069c2712018-03-29 19:09:14 -07008777
8778void AudioFlinger::MmapCaptureThread::updateMetadata_l()
8779{
8780 if (mInput == nullptr || mInput->stream == nullptr ||
8781 !mActiveTracks.readAndClearHasChanged()) {
8782 return;
8783 }
8784 StreamInHalInterface::SinkMetadata metadata;
8785 for (const sp<MmapTrack> &track : mActiveTracks) {
8786 // No track is invalid as this is called after prepareTrack_l in the same critical section
8787 metadata.tracks.push_back({
8788 .source = track->attributes().source,
8789 .gain = 1, // capture tracks do not have volumes
8790 });
8791 }
8792 mInput->stream->updateSinkMetadata(metadata);
8793}
8794
Glenn Kasten63238ef2015-03-02 15:50:29 -08008795} // namespace android