blob: 70af5c6916c0dc3faa1bd8a98508f6245fd8b3c8 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080026#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080027#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070030#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070031#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080032#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070033#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080034#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080035#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036
37#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070038#include <private/android_filesystem_config.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080039#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080041#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070042#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070043#include <system/audio_effects/effect_ns.h>
44#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070045#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046
47// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070048#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <media/nbaio/AudioStreamOutSink.h>
50#include <media/nbaio/MonoPipe.h>
51#include <media/nbaio/MonoPipeReader.h>
52#include <media/nbaio/Pipe.h>
53#include <media/nbaio/PipeReader.h>
54#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080055#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056
57#include <powermanager/PowerManager.h>
58
Kevin Rocard7588ff42018-01-08 11:11:30 -080059#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070060#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080061
Eric Laurent81784c32012-11-19 14:55:58 -080062#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080063#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070064#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070065#include <mediautils/SchedulingPolicyService.h>
66#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080067
Eric Laurent81784c32012-11-19 14:55:58 -080068#ifdef ADD_BATTERY_DATA
69#include <media/IMediaPlayerService.h>
70#include <media/IMediaDeathNotifier.h>
71#endif
72
Eric Laurent81784c32012-11-19 14:55:58 -080073#ifdef DEBUG_CPU_USAGE
74#include <cpustats/CentralTendencyStatistics.h>
75#include <cpustats/ThreadCpuUsage.h>
76#endif
77
Glenn Kastenc05b8d72016-03-24 09:48:17 -070078#include "AutoPark.h"
79
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080080#include <pthread.h>
81#include "TypedLogger.h"
82
Eric Laurent81784c32012-11-19 14:55:58 -080083// ----------------------------------------------------------------------------
84
85// Note: the following macro is used for extremely verbose logging message. In
86// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
87// 0; but one side effect of this is to turn all LOGV's as well. Some messages
88// are so verbose that we want to suppress them even when we have ALOG_ASSERT
89// turned on. Do not uncomment the #def below unless you really know what you
90// are doing and want to see all of the extremely verbose messages.
91//#define VERY_VERY_VERBOSE_LOGGING
92#ifdef VERY_VERY_VERBOSE_LOGGING
93#define ALOGVV ALOGV
94#else
95#define ALOGVV(a...) do { } while(0)
96#endif
97
Andy Hung6770c6f2015-04-07 13:43:36 -070098// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -070099#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700100template <typename T>
101static inline T min(const T& a, const T& b)
102{
103 return a < b ? a : b;
104}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700105
Eric Laurent81784c32012-11-19 14:55:58 -0800106namespace android {
107
108// retry counts for buffer fill timeout
109// 50 * ~20msecs = 1 second
110static const int8_t kMaxTrackRetries = 50;
111static const int8_t kMaxTrackStartupRetries = 50;
112// allow less retry attempts on direct output thread.
113// direct outputs can be a scarce resource in audio hardware and should
114// be released as quickly as possible.
115static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700116
Eric Laurent51716182016-02-29 18:00:56 -0800117
Eric Laurent81784c32012-11-19 14:55:58 -0800118
119// don't warn about blocked writes or record buffer overflows more often than this
120static const nsecs_t kWarningThrottleNs = seconds(5);
121
122// RecordThread loop sleep time upon application overrun or audio HAL read error
123static const int kRecordThreadSleepUs = 5000;
124
Eric Laurent10351942014-05-08 18:49:52 -0700125// maximum time to wait in sendConfigEvent_l() for a status to be received
126static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800127
128// minimum sleep time for the mixer thread loop when tracks are active but in underrun
129static const uint32_t kMinThreadSleepTimeUs = 5000;
130// maximum divider applied to the active sleep time in the mixer thread loop
131static const uint32_t kMaxThreadSleepTimeShift = 2;
132
Andy Hung09a50072014-02-27 14:30:47 -0800133// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700134// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800135static const uint32_t kMinNormalSinkBufferSizeMs = 20;
136// maximum normal sink buffer size
137static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800138
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700139// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
140// FIXME This should be based on experimentally observed scheduling jitter
141static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
142
Eric Laurent972a1732013-09-04 09:42:59 -0700143// Offloaded output thread standby delay: allows track transition without going to standby
144static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
145
Eric Laurent51716182016-02-29 18:00:56 -0800146// Direct output thread minimum sleep time in idle or active(underrun) state
147static const nsecs_t kDirectMinSleepTimeUs = 10000;
148
Glenn Kasten1b291842016-07-18 14:55:21 -0700149// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
150// balance between power consumption and latency, and allows threads to be scheduled reliably
151// by the CFS scheduler.
152// FIXME Express other hardcoded references to 20ms with references to this constant and move
153// it appropriately.
154#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800155
Eric Laurent81784c32012-11-19 14:55:58 -0800156// Whether to use fast mixer
157static const enum {
158 FastMixer_Never, // never initialize or use: for debugging only
159 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
160 // normal mixer multiplier is 1
161 FastMixer_Static, // initialize if needed, then use all the time if initialized,
162 // multiplier is calculated based on min & max normal mixer buffer size
163 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
164 // multiplier is calculated based on min & max normal mixer buffer size
165 // FIXME for FastMixer_Dynamic:
166 // Supporting this option will require fixing HALs that can't handle large writes.
167 // For example, one HAL implementation returns an error from a large write,
168 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
169 // We could either fix the HAL implementations, or provide a wrapper that breaks
170 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
171} kUseFastMixer = FastMixer_Static;
172
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700173// Whether to use fast capture
174static const enum {
175 FastCapture_Never, // never initialize or use: for debugging only
176 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
177 FastCapture_Static, // initialize if needed, then use all the time if initialized
178} kUseFastCapture = FastCapture_Static;
179
Eric Laurent81784c32012-11-19 14:55:58 -0800180// Priorities for requestPriority
181static const int kPriorityAudioApp = 2;
182static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
Glenn Kastenea38ee72016-04-18 11:08:01 -0700185// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
186// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
187// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700188
189// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800190static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800191
Glenn Kasten03490092014-05-27 12:30:54 -0700192// The minimum and maximum allowed values
193static const int kFastTrackMultiplierMin = 1;
194static const int kFastTrackMultiplierMax = 2;
195
196// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
197static int sFastTrackMultiplier = kFastTrackMultiplier;
198
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700199// See Thread::readOnlyHeap().
200// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
201// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
202// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700203static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// ----------------------------------------------------------------------------
206
Glenn Kasten03490092014-05-27 12:30:54 -0700207static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
208
209static void sFastTrackMultiplierInit()
210{
211 char value[PROPERTY_VALUE_MAX];
212 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
213 char *endptr;
214 unsigned long ul = strtoul(value, &endptr, 0);
215 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
216 sFastTrackMultiplier = (int) ul;
217 }
218 }
219}
220
221// ----------------------------------------------------------------------------
222
Eric Laurent81784c32012-11-19 14:55:58 -0800223#ifdef ADD_BATTERY_DATA
224// To collect the amplifier usage
225static void addBatteryData(uint32_t params) {
226 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
227 if (service == NULL) {
228 // it already logged
229 return;
230 }
231
232 service->addBatteryData(params);
233}
234#endif
235
Andy Hung3f0c9022016-01-15 17:49:46 -0800236// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
237struct {
238 // call when you acquire a partial wakelock
239 void acquire(const sp<IBinder> &wakeLockToken) {
240 pthread_mutex_lock(&mLock);
241 if (wakeLockToken.get() == nullptr) {
242 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
243 } else {
244 if (mCount == 0) {
245 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
246 }
247 ++mCount;
248 }
249 pthread_mutex_unlock(&mLock);
250 }
251
252 // call when you release a partial wakelock.
253 void release(const sp<IBinder> &wakeLockToken) {
254 if (wakeLockToken.get() == nullptr) {
255 return;
256 }
257 pthread_mutex_lock(&mLock);
258 if (--mCount < 0) {
259 ALOGE("negative wakelock count");
260 mCount = 0;
261 }
262 pthread_mutex_unlock(&mLock);
263 }
264
265 // retrieves the boottime timebase offset from monotonic.
266 int64_t getBoottimeOffset() {
267 pthread_mutex_lock(&mLock);
268 int64_t boottimeOffset = mBoottimeOffset;
269 pthread_mutex_unlock(&mLock);
270 return boottimeOffset;
271 }
272
273 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
274 // and the selected timebase.
275 // Currently only TIMEBASE_BOOTTIME is allowed.
276 //
277 // This only needs to be called upon acquiring the first partial wakelock
278 // after all other partial wakelocks are released.
279 //
280 // We do an empirical measurement of the offset rather than parsing
281 // /proc/timer_list since the latter is not a formal kernel ABI.
282 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
283 int clockbase;
284 switch (timebase) {
285 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
286 clockbase = SYSTEM_TIME_BOOTTIME;
287 break;
288 default:
289 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
290 break;
291 }
292 // try three times to get the clock offset, choose the one
293 // with the minimum gap in measurements.
294 const int tries = 3;
295 nsecs_t bestGap, measured;
296 for (int i = 0; i < tries; ++i) {
297 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
298 const nsecs_t tbase = systemTime(clockbase);
299 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
300 const nsecs_t gap = tmono2 - tmono;
301 if (i == 0 || gap < bestGap) {
302 bestGap = gap;
303 measured = tbase - ((tmono + tmono2) >> 1);
304 }
305 }
306
307 // to avoid micro-adjusting, we don't change the timebase
308 // unless it is significantly different.
309 //
310 // Assumption: It probably takes more than toleranceNs to
311 // suspend and resume the device.
312 static int64_t toleranceNs = 10000; // 10 us
313 if (llabs(*offset - measured) > toleranceNs) {
314 ALOGV("Adjusting timebase offset old: %lld new: %lld",
315 (long long)*offset, (long long)measured);
316 *offset = measured;
317 }
318 }
319
320 pthread_mutex_t mLock;
321 int32_t mCount;
322 int64_t mBoottimeOffset;
323} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800324
325// ----------------------------------------------------------------------------
326// CPU Stats
327// ----------------------------------------------------------------------------
328
329class CpuStats {
330public:
331 CpuStats();
332 void sample(const String8 &title);
333#ifdef DEBUG_CPU_USAGE
334private:
335 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
336 CentralTendencyStatistics mWcStats; // statistics on thread CPU usage in wall clock ns
337
338 CentralTendencyStatistics mHzStats; // statistics on thread CPU usage in cycles
339
340 int mCpuNum; // thread's current CPU number
341 int mCpukHz; // frequency of thread's current CPU in kHz
342#endif
343};
344
345CpuStats::CpuStats()
346#ifdef DEBUG_CPU_USAGE
347 : mCpuNum(-1), mCpukHz(-1)
348#endif
349{
350}
351
Glenn Kasten0f11b512014-01-31 16:18:54 -0800352void CpuStats::sample(const String8 &title
353#ifndef DEBUG_CPU_USAGE
354 __unused
355#endif
356 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800357#ifdef DEBUG_CPU_USAGE
358 // get current thread's delta CPU time in wall clock ns
359 double wcNs;
360 bool valid = mCpuUsage.sampleAndEnable(wcNs);
361
362 // record sample for wall clock statistics
363 if (valid) {
364 mWcStats.sample(wcNs);
365 }
366
367 // get the current CPU number
368 int cpuNum = sched_getcpu();
369
370 // get the current CPU frequency in kHz
371 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
372
373 // check if either CPU number or frequency changed
374 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
375 mCpuNum = cpuNum;
376 mCpukHz = cpukHz;
377 // ignore sample for purposes of cycles
378 valid = false;
379 }
380
381 // if no change in CPU number or frequency, then record sample for cycle statistics
382 if (valid && mCpukHz > 0) {
383 double cycles = wcNs * cpukHz * 0.000001;
384 mHzStats.sample(cycles);
385 }
386
387 unsigned n = mWcStats.n();
388 // mCpuUsage.elapsed() is expensive, so don't call it every loop
389 if ((n & 127) == 1) {
390 long long elapsed = mCpuUsage.elapsed();
391 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
392 double perLoop = elapsed / (double) n;
393 double perLoop100 = perLoop * 0.01;
394 double perLoop1k = perLoop * 0.001;
395 double mean = mWcStats.mean();
396 double stddev = mWcStats.stddev();
397 double minimum = mWcStats.minimum();
398 double maximum = mWcStats.maximum();
399 double meanCycles = mHzStats.mean();
400 double stddevCycles = mHzStats.stddev();
401 double minCycles = mHzStats.minimum();
402 double maxCycles = mHzStats.maximum();
403 mCpuUsage.resetElapsed();
404 mWcStats.reset();
405 mHzStats.reset();
406 ALOGD("CPU usage for %s over past %.1f secs\n"
407 " (%u mixer loops at %.1f mean ms per loop):\n"
408 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
409 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
410 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
411 title.string(),
412 elapsed * .000000001, n, perLoop * .000001,
413 mean * .001,
414 stddev * .001,
415 minimum * .001,
416 maximum * .001,
417 mean / perLoop100,
418 stddev / perLoop100,
419 minimum / perLoop100,
420 maximum / perLoop100,
421 meanCycles / perLoop1k,
422 stddevCycles / perLoop1k,
423 minCycles / perLoop1k,
424 maxCycles / perLoop1k);
425
426 }
427 }
428#endif
429};
430
431// ----------------------------------------------------------------------------
432// ThreadBase
433// ----------------------------------------------------------------------------
434
Glenn Kasten97b7b752014-09-28 13:04:24 -0700435// static
436const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
437{
438 switch (type) {
439 case MIXER:
440 return "MIXER";
441 case DIRECT:
442 return "DIRECT";
443 case DUPLICATING:
444 return "DUPLICATING";
445 case RECORD:
446 return "RECORD";
447 case OFFLOAD:
448 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800449 case MMAP:
450 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700451 default:
452 return "unknown";
453 }
454}
455
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700456std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800457{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700458 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800459 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700460 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800461 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700462 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800463 }
464 return result;
465}
466
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700467std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800468{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700469 std::string result;
470 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800471 return result;
472}
473
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700474std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700475{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700476 std::string result;
477 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700478 return result;
479}
480
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800481const char *sourceToString(audio_source_t source)
482{
483 switch (source) {
484 case AUDIO_SOURCE_DEFAULT: return "default";
485 case AUDIO_SOURCE_MIC: return "mic";
486 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
487 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
488 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
489 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
490 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
491 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
492 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800493 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800494 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
495 case AUDIO_SOURCE_HOTWORD: return "hotword";
496 default: return "unknown";
497 }
498}
499
Eric Laurent81784c32012-11-19 14:55:58 -0800500AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700501 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800502 : Thread(false /*canCallJava*/),
503 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700504 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700505 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800506 // are set by PlaybackThread::readOutputParameters_l() or
507 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700508 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800509 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700510 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
511 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800512 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700513 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800514 mSystemReady(systemReady),
515 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800516{
Eric Laurent296fb132015-05-01 11:38:42 -0700517 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800518}
519
520AudioFlinger::ThreadBase::~ThreadBase()
521{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700522 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700523 mConfigEvents.clear();
524
Eric Laurent81784c32012-11-19 14:55:58 -0800525 // do not lock the mutex in destructor
526 releaseWakeLock_l();
527 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800528 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800529 binder->unlinkToDeath(mDeathRecipient);
530 }
531}
532
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700533status_t AudioFlinger::ThreadBase::readyToRun()
534{
535 status_t status = initCheck();
536 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800537 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700538 } else {
539 ALOGE("No working audio driver found.");
540 }
541 return status;
542}
543
Eric Laurent81784c32012-11-19 14:55:58 -0800544void AudioFlinger::ThreadBase::exit()
545{
546 ALOGV("ThreadBase::exit");
547 // do any cleanup required for exit to succeed
548 preExit();
549 {
550 // This lock prevents the following race in thread (uniprocessor for illustration):
551 // if (!exitPending()) {
552 // // context switch from here to exit()
553 // // exit() calls requestExit(), what exitPending() observes
554 // // exit() calls signal(), which is dropped since no waiters
555 // // context switch back from exit() to here
556 // mWaitWorkCV.wait(...);
557 // // now thread is hung
558 // }
559 AutoMutex lock(mLock);
560 requestExit();
561 mWaitWorkCV.broadcast();
562 }
563 // When Thread::requestExitAndWait is made virtual and this method is renamed to
564 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
565 requestExitAndWait();
566}
567
568status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
569{
Eric Laurent81784c32012-11-19 14:55:58 -0800570 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
571 Mutex::Autolock _l(mLock);
572
Eric Laurent10351942014-05-08 18:49:52 -0700573 return sendSetParameterConfigEvent_l(keyValuePairs);
574}
575
576// sendConfigEvent_l() must be called with ThreadBase::mLock held
577// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
578status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
579{
580 status_t status = NO_ERROR;
581
Eric Laurent72e3f392015-05-20 14:43:50 -0700582 if (event->mRequiresSystemReady && !mSystemReady) {
583 event->mWaitStatus = false;
584 mPendingConfigEvents.add(event);
585 return status;
586 }
Eric Laurent10351942014-05-08 18:49:52 -0700587 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700588 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800589 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700590 mLock.unlock();
591 {
592 Mutex::Autolock _l(event->mLock);
593 while (event->mWaitStatus) {
594 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
595 event->mStatus = TIMED_OUT;
596 event->mWaitStatus = false;
597 }
598 }
599 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800600 }
Eric Laurent10351942014-05-08 18:49:52 -0700601 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800602 return status;
603}
604
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700605void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800606{
607 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700608 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800609}
610
611// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700612void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800613{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700614 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700615 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800616}
617
Mikhail Naganov83f04272017-02-07 10:45:09 -0800618void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700619{
620 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800621 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700622}
623
Eric Laurent81784c32012-11-19 14:55:58 -0800624// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800625void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
626 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800627{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800628 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700629 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800630}
631
Eric Laurent10351942014-05-08 18:49:52 -0700632// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
633status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800634{
Andy Hung2ddee192015-12-18 17:34:44 -0800635 sp<ConfigEvent> configEvent;
636 AudioParameter param(keyValuePair);
637 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700638 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800639 setMasterMono_l(value != 0);
640 if (param.size() == 1) {
641 return NO_ERROR; // should be a solo parameter - we don't pass down
642 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700643 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800644 configEvent = new SetParameterConfigEvent(param.toString());
645 } else {
646 configEvent = new SetParameterConfigEvent(keyValuePair);
647 }
Eric Laurent10351942014-05-08 18:49:52 -0700648 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700649}
650
Eric Laurent1c333e22014-05-20 10:48:17 -0700651status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
652 const struct audio_patch *patch,
653 audio_patch_handle_t *handle)
654{
655 Mutex::Autolock _l(mLock);
656 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
657 status_t status = sendConfigEvent_l(configEvent);
658 if (status == NO_ERROR) {
659 CreateAudioPatchConfigEventData *data =
660 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
661 *handle = data->mHandle;
662 }
663 return status;
664}
665
666status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
667 const audio_patch_handle_t handle)
668{
669 Mutex::Autolock _l(mLock);
670 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
671 return sendConfigEvent_l(configEvent);
672}
673
674
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700675// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700676void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700677{
Eric Laurent10351942014-05-08 18:49:52 -0700678 bool configChanged = false;
679
Eric Laurent81784c32012-11-19 14:55:58 -0800680 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700681 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700682 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800683 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700684 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700685 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700686 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
687 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800688 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700689 true /*asynchronous*/);
690 if (err != 0) {
691 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700692 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700693 }
694 } break;
695 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700696 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700697 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700698 } break;
699 case CFG_EVENT_SET_PARAMETER: {
700 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
701 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
702 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700703 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
704 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700705 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700706 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700707 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700708 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700709 CreateAudioPatchConfigEventData *data =
710 (CreateAudioPatchConfigEventData *)event->mData.get();
711 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700712 const audio_devices_t newDevice = getDevice();
713 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
714 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
715 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700716 } break;
717 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700718 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 ReleaseAudioPatchConfigEventData *data =
720 (ReleaseAudioPatchConfigEventData *)event->mData.get();
721 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700722 const audio_devices_t newDevice = getDevice();
723 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
724 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
725 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700726 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700727 default:
Eric Laurent10351942014-05-08 18:49:52 -0700728 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700729 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800730 }
Eric Laurent10351942014-05-08 18:49:52 -0700731 {
732 Mutex::Autolock _l(event->mLock);
733 if (event->mWaitStatus) {
734 event->mWaitStatus = false;
735 event->mCond.signal();
736 }
737 }
738 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
739 }
740
741 if (configChanged) {
742 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Eric Laurent81784c32012-11-19 14:55:58 -0800744}
745
Marco Nelissenb2208842014-02-07 14:00:50 -0800746String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
747 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700748 const audio_channel_representation_t representation =
749 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700750
751 switch (representation) {
752 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
753 if (output) {
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
756 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
758 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
759 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
760 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
763 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
765 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
766 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
767 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
769 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
770 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
771 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700772 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
773 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700774 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
775 } else {
776 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
780 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
781 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
782 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
783 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
784 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
785 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
786 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
787 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700788 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
789 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
790 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
791 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
792 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
793 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700794 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
795 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
796 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
797 }
798 const int len = s.length();
799 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700800 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700801 s.unlockBuffer(len - 2); // remove trailing ", "
802 }
803 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800804 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700805 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
806 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
807 return s;
808 default:
809 s.appendFormat("unknown mask, representation:%d bits:%#x",
810 representation, audio_channel_mask_get_bits(mask));
811 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800812 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800813}
814
Glenn Kasten0f11b512014-01-31 16:18:54 -0800815void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800816{
817 const size_t SIZE = 256;
818 char buffer[SIZE];
819 String8 result;
820
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800821 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
822 this, mThreadName, getTid(), type(), threadTypeToString(type()));
823
Eric Laurent81784c32012-11-19 14:55:58 -0800824 bool locked = AudioFlinger::dumpTryLock(mLock);
825 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800826 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800827 }
828
Elliott Hughes87cebad2014-05-22 10:14:43 -0700829 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700830 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700831 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700832 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700833 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700834 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700835 dprintf(fd, " Channel count: %u\n", mChannelCount);
836 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800837 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700838 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700839 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700840 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800841 size_t numConfig = mConfigEvents.size();
842 if (numConfig) {
843 for (size_t i = 0; i < numConfig; i++) {
844 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700845 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800850 }
Andy Hung293558a2017-03-21 12:19:20 -0700851 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700852 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
853 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800854 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800855
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700856 // Dump timestamp statistics for the Thread types that support it.
857 if (mType == RECORD
858 || mType == MIXER
859 || mType == DUPLICATING
860 || (mType == DIRECT && audio_is_linear_pcm(mHALFormat))) {
861 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
862 }
863
Eric Laurent81784c32012-11-19 14:55:58 -0800864 if (locked) {
865 mLock.unlock();
866 }
867}
868
869void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
870{
871 const size_t SIZE = 256;
872 char buffer[SIZE];
873 String8 result;
874
Marco Nelissenb2208842014-02-07 14:00:50 -0800875 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000876 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800877 write(fd, buffer, strlen(buffer));
878
Marco Nelissenb2208842014-02-07 14:00:50 -0800879 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800880 sp<EffectChain> chain = mEffectChains[i];
881 if (chain != 0) {
882 chain->dump(fd, args);
883 }
884 }
885}
886
Andy Hungdae27702016-10-31 14:01:16 -0700887void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800888{
889 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700890 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800891}
892
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100893String16 AudioFlinger::ThreadBase::getWakeLockTag()
894{
895 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800896 case MIXER:
897 return String16("AudioMix");
898 case DIRECT:
899 return String16("AudioDirectOut");
900 case DUPLICATING:
901 return String16("AudioDup");
902 case RECORD:
903 return String16("AudioIn");
904 case OFFLOAD:
905 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800906 case MMAP:
907 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800908 default:
909 ALOG_ASSERT(false);
910 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100911 }
912}
913
Andy Hungdae27702016-10-31 14:01:16 -0700914void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800915{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800916 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800917 if (mPowerManager != 0) {
918 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700919 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
920 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700921 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100922 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700923 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700924 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800925 if (status == NO_ERROR) {
926 mWakeLockToken = binder;
927 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800928 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800929 }
Wei Jia3f273d12015-11-24 09:06:49 -0800930
Andy Hung3f0c9022016-01-15 17:49:46 -0800931 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800932 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
933 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800934}
935
936void AudioFlinger::ThreadBase::releaseWakeLock()
937{
938 Mutex::Autolock _l(mLock);
939 releaseWakeLock_l();
940}
941
942void AudioFlinger::ThreadBase::releaseWakeLock_l()
943{
Andy Hung3f0c9022016-01-15 17:49:46 -0800944 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800945 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800946 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800947 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700948 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
949 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800950 }
951 mWakeLockToken.clear();
952 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800953}
954
955void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700956 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800957 // use checkService() to avoid blocking if power service is not up yet
958 sp<IBinder> binder =
959 defaultServiceManager()->checkService(String16("power"));
960 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800961 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800962 } else {
963 mPowerManager = interface_cast<IPowerManager>(binder);
964 binder->linkToDeath(mDeathRecipient);
965 }
966 }
967}
968
Andy Hungd01b0f12016-11-07 16:10:30 -0800969void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800970 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700971
972#if !LOG_NDEBUG
973 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800974 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700975 s << uid << " ";
976 }
977 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
978#endif
979
Andy Hung438e7572015-12-14 15:51:17 -0800980 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
981 if (mSystemReady) {
982 ALOGE("no wake lock to update, but system ready!");
983 } else {
984 ALOGW("no wake lock to update, system not ready yet");
985 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800986 return;
987 }
988 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -0800989 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
990 status_t status = mPowerManager->updateWakeLockUids(
991 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
992 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -0800993 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800994 }
995}
996
Eric Laurent81784c32012-11-19 14:55:58 -0800997void AudioFlinger::ThreadBase::clearPowerManager()
998{
999 Mutex::Autolock _l(mLock);
1000 releaseWakeLock_l();
1001 mPowerManager.clear();
1002}
1003
Glenn Kasten0f11b512014-01-31 16:18:54 -08001004void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001005{
1006 sp<ThreadBase> thread = mThread.promote();
1007 if (thread != 0) {
1008 thread->clearPowerManager();
1009 }
1010 ALOGW("power manager service died !!!");
1011}
1012
Eric Laurent81784c32012-11-19 14:55:58 -08001013void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001014 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001015{
1016 sp<EffectChain> chain = getEffectChain_l(sessionId);
1017 if (chain != 0) {
1018 if (type != NULL) {
1019 chain->setEffectSuspended_l(type, suspend);
1020 } else {
1021 chain->setEffectSuspendedAll_l(suspend);
1022 }
1023 }
1024
1025 updateSuspendedSessions_l(type, suspend, sessionId);
1026}
1027
1028void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1029{
1030 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1031 if (index < 0) {
1032 return;
1033 }
1034
1035 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1036 mSuspendedSessions.valueAt(index);
1037
1038 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001039 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001040 for (int j = 0; j < desc->mRefCount; j++) {
1041 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1042 chain->setEffectSuspendedAll_l(true);
1043 } else {
1044 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1045 desc->mType.timeLow);
1046 chain->setEffectSuspended_l(&desc->mType, true);
1047 }
1048 }
1049 }
1050}
1051
1052void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1053 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001054 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001055{
1056 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1057
1058 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1059
1060 if (suspend) {
1061 if (index >= 0) {
1062 sessionEffects = mSuspendedSessions.valueAt(index);
1063 } else {
1064 mSuspendedSessions.add(sessionId, sessionEffects);
1065 }
1066 } else {
1067 if (index < 0) {
1068 return;
1069 }
1070 sessionEffects = mSuspendedSessions.valueAt(index);
1071 }
1072
1073
1074 int key = EffectChain::kKeyForSuspendAll;
1075 if (type != NULL) {
1076 key = type->timeLow;
1077 }
1078 index = sessionEffects.indexOfKey(key);
1079
1080 sp<SuspendedSessionDesc> desc;
1081 if (suspend) {
1082 if (index >= 0) {
1083 desc = sessionEffects.valueAt(index);
1084 } else {
1085 desc = new SuspendedSessionDesc();
1086 if (type != NULL) {
1087 desc->mType = *type;
1088 }
1089 sessionEffects.add(key, desc);
1090 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1091 }
1092 desc->mRefCount++;
1093 } else {
1094 if (index < 0) {
1095 return;
1096 }
1097 desc = sessionEffects.valueAt(index);
1098 if (--desc->mRefCount == 0) {
1099 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1100 sessionEffects.removeItemsAt(index);
1101 if (sessionEffects.isEmpty()) {
1102 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1103 sessionId);
1104 mSuspendedSessions.removeItem(sessionId);
1105 }
1106 }
1107 }
1108 if (!sessionEffects.isEmpty()) {
1109 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1110 }
1111}
1112
1113void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1114 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001115 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001116{
1117 Mutex::Autolock _l(mLock);
1118 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1119}
1120
1121void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1122 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001123 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001124{
1125 if (mType != RECORD) {
1126 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1127 // another session. This gives the priority to well behaved effect control panels
1128 // and applications not using global effects.
1129 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1130 // global effects
1131 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1132 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1133 }
1134 }
1135
1136 sp<EffectChain> chain = getEffectChain_l(sessionId);
1137 if (chain != 0) {
1138 chain->checkSuspendOnEffectEnabled(effect, enabled);
1139 }
1140}
1141
Eric Laurent4c415062016-06-17 16:14:16 -07001142// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1143status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1144 const effect_descriptor_t *desc, audio_session_t sessionId)
1145{
1146 // No global effect sessions on record threads
1147 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1148 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1149 desc->name, mThreadName);
1150 return BAD_VALUE;
1151 }
1152 // only pre processing effects on record thread
1153 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1154 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1155 desc->name, mThreadName);
1156 return BAD_VALUE;
1157 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001158
1159 // always allow effects without processing load or latency
1160 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1161 return NO_ERROR;
1162 }
1163
Eric Laurent4c415062016-06-17 16:14:16 -07001164 audio_input_flags_t flags = mInput->flags;
1165 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1166 if (flags & AUDIO_INPUT_FLAG_RAW) {
1167 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1168 desc->name, mThreadName);
1169 return BAD_VALUE;
1170 }
1171 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1172 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1173 desc->name, mThreadName);
1174 return BAD_VALUE;
1175 }
1176 }
1177 return NO_ERROR;
1178}
1179
1180// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1181status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1182 const effect_descriptor_t *desc, audio_session_t sessionId)
1183{
1184 // no preprocessing on playback threads
1185 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1186 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1187 " thread %s", desc->name, mThreadName);
1188 return BAD_VALUE;
1189 }
1190
Eric Laurent3e4de772017-07-16 16:55:08 -07001191 // always allow effects without processing load or latency
1192 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1193 return NO_ERROR;
1194 }
1195
Eric Laurent4c415062016-06-17 16:14:16 -07001196 switch (mType) {
1197 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001198#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001199 // Reject any effect on mixer multichannel sinks.
1200 // TODO: fix both format and multichannel issues with effects.
1201 if (mChannelCount != FCC_2) {
1202 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1203 " thread %s", desc->name, mChannelCount, mThreadName);
1204 return BAD_VALUE;
1205 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001206#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001207 audio_output_flags_t flags = mOutput->flags;
1208 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1209 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1210 // global effects are applied only to non fast tracks if they are SW
1211 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1212 break;
1213 }
1214 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1215 // only post processing on output stage session
1216 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1217 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1218 " on output stage session", desc->name);
1219 return BAD_VALUE;
1220 }
1221 } else {
1222 // no restriction on effects applied on non fast tracks
1223 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1224 break;
1225 }
1226 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001227
Eric Laurent4c415062016-06-17 16:14:16 -07001228 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1229 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1230 desc->name);
1231 return BAD_VALUE;
1232 }
1233 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1234 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1235 " in fast mode", desc->name);
1236 return BAD_VALUE;
1237 }
1238 }
1239 } break;
1240 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001241 // nothing actionable on offload threads, if the effect:
1242 // - is offloadable: the effect can be created
1243 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1244 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001245 break;
1246 case DIRECT:
1247 // Reject any effect on Direct output threads for now, since the format of
1248 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1249 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1250 desc->name, mThreadName);
1251 return BAD_VALUE;
1252 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001253#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001254 // Reject any effect on mixer multichannel sinks.
1255 // TODO: fix both format and multichannel issues with effects.
1256 if (mChannelCount != FCC_2) {
1257 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1258 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1259 return BAD_VALUE;
1260 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001261#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001262 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1263 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1264 " thread %s", desc->name, mThreadName);
1265 return BAD_VALUE;
1266 }
1267 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1268 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1269 " DUPLICATING thread %s", desc->name, mThreadName);
1270 return BAD_VALUE;
1271 }
1272 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1273 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1274 " DUPLICATING thread %s", desc->name, mThreadName);
1275 return BAD_VALUE;
1276 }
1277 break;
1278 default:
1279 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1280 }
1281
1282 return NO_ERROR;
1283}
1284
Eric Laurent81784c32012-11-19 14:55:58 -08001285// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1286sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1287 const sp<AudioFlinger::Client>& client,
1288 const sp<IEffectClient>& effectClient,
1289 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001290 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001291 effect_descriptor_t *desc,
1292 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001293 status_t *status,
1294 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001295{
1296 sp<EffectModule> effect;
1297 sp<EffectHandle> handle;
1298 status_t lStatus;
1299 sp<EffectChain> chain;
1300 bool chainCreated = false;
1301 bool effectCreated = false;
1302 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001303 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001304
1305 lStatus = initCheck();
1306 if (lStatus != NO_ERROR) {
1307 ALOGW("createEffect_l() Audio driver not initialized.");
1308 goto Exit;
1309 }
1310
Eric Laurent81784c32012-11-19 14:55:58 -08001311 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1312
1313 { // scope for mLock
1314 Mutex::Autolock _l(mLock);
1315
Eric Laurent4c415062016-06-17 16:14:16 -07001316 lStatus = checkEffectCompatibility_l(desc, sessionId);
1317 if (lStatus != NO_ERROR) {
1318 goto Exit;
1319 }
1320
Eric Laurent81784c32012-11-19 14:55:58 -08001321 // check for existing effect chain with the requested audio session
1322 chain = getEffectChain_l(sessionId);
1323 if (chain == 0) {
1324 // create a new chain for this session
1325 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1326 chain = new EffectChain(this, sessionId);
1327 addEffectChain_l(chain);
1328 chain->setStrategy(getStrategyForSession_l(sessionId));
1329 chainCreated = true;
1330 } else {
1331 effect = chain->getEffectFromDesc_l(desc);
1332 }
1333
1334 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1335
1336 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001337 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001338 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001339 lStatus = AudioSystem::registerEffect(
1340 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001341 if (lStatus != NO_ERROR) {
1342 goto Exit;
1343 }
1344 effectRegistered = true;
1345 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001346 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001347 if (lStatus != NO_ERROR) {
1348 goto Exit;
1349 }
1350 effectCreated = true;
1351
1352 effect->setDevice(mOutDevice);
1353 effect->setDevice(mInDevice);
1354 effect->setMode(mAudioFlinger->getMode());
1355 effect->setAudioSource(mAudioSource);
1356 }
1357 // create effect handle and connect it to effect module
1358 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001359 lStatus = handle->initCheck();
1360 if (lStatus == OK) {
1361 lStatus = effect->addHandle(handle.get());
1362 }
Eric Laurent81784c32012-11-19 14:55:58 -08001363 if (enabled != NULL) {
1364 *enabled = (int)effect->isEnabled();
1365 }
1366 }
1367
1368Exit:
1369 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1370 Mutex::Autolock _l(mLock);
1371 if (effectCreated) {
1372 chain->removeEffect_l(effect);
1373 }
1374 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001375 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001376 }
1377 if (chainCreated) {
1378 removeEffectChain_l(chain);
1379 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001380 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001381 }
1382
Glenn Kasten9156ef32013-08-06 15:39:08 -07001383 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001384 return handle;
1385}
1386
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001387void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1388 bool unpinIfLast)
1389{
1390 bool remove = false;
1391 sp<EffectModule> effect;
1392 {
1393 Mutex::Autolock _l(mLock);
1394
1395 effect = handle->effect().promote();
1396 if (effect == 0) {
1397 return;
1398 }
1399 // restore suspended effects if the disconnected handle was enabled and the last one.
1400 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1401 if (remove) {
1402 removeEffect_l(effect, true);
1403 }
1404 }
1405 if (remove) {
1406 mAudioFlinger->updateOrphanEffectChains(effect);
1407 AudioSystem::unregisterEffect(effect->id());
1408 if (handle->enabled()) {
1409 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1410 }
1411 }
1412}
1413
Glenn Kastend848eb42016-03-08 13:42:11 -08001414sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1415 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001416{
1417 Mutex::Autolock _l(mLock);
1418 return getEffect_l(sessionId, effectId);
1419}
1420
Glenn Kastend848eb42016-03-08 13:42:11 -08001421sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1422 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001423{
1424 sp<EffectChain> chain = getEffectChain_l(sessionId);
1425 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1426}
1427
1428// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1429// PlaybackThread::mLock held
1430status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1431{
1432 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001433 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001434 sp<EffectChain> chain = getEffectChain_l(sessionId);
1435 bool chainCreated = false;
1436
Eric Laurent5baf2af2013-09-12 17:37:00 -07001437 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001438 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001439 this, effect->desc().name, effect->desc().flags);
1440
Eric Laurent81784c32012-11-19 14:55:58 -08001441 if (chain == 0) {
1442 // create a new chain for this session
1443 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1444 chain = new EffectChain(this, sessionId);
1445 addEffectChain_l(chain);
1446 chain->setStrategy(getStrategyForSession_l(sessionId));
1447 chainCreated = true;
1448 }
1449 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1450
1451 if (chain->getEffectFromId_l(effect->id()) != 0) {
1452 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1453 this, effect->desc().name, chain.get());
1454 return BAD_VALUE;
1455 }
1456
Eric Laurent5baf2af2013-09-12 17:37:00 -07001457 effect->setOffloaded(mType == OFFLOAD, mId);
1458
Eric Laurent81784c32012-11-19 14:55:58 -08001459 status_t status = chain->addEffect_l(effect);
1460 if (status != NO_ERROR) {
1461 if (chainCreated) {
1462 removeEffectChain_l(chain);
1463 }
1464 return status;
1465 }
1466
1467 effect->setDevice(mOutDevice);
1468 effect->setDevice(mInDevice);
1469 effect->setMode(mAudioFlinger->getMode());
1470 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001471
Eric Laurent81784c32012-11-19 14:55:58 -08001472 return NO_ERROR;
1473}
1474
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001475void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001476
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001477 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001478 effect_descriptor_t desc = effect->desc();
1479 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1480 detachAuxEffect_l(effect->id());
1481 }
1482
1483 sp<EffectChain> chain = effect->chain().promote();
1484 if (chain != 0) {
1485 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001486 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001487 removeEffectChain_l(chain);
1488 }
1489 } else {
1490 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1491 }
1492}
1493
1494void AudioFlinger::ThreadBase::lockEffectChains_l(
1495 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1496{
1497 effectChains = mEffectChains;
1498 for (size_t i = 0; i < mEffectChains.size(); i++) {
1499 mEffectChains[i]->lock();
1500 }
1501}
1502
1503void AudioFlinger::ThreadBase::unlockEffectChains(
1504 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1505{
1506 for (size_t i = 0; i < effectChains.size(); i++) {
1507 effectChains[i]->unlock();
1508 }
1509}
1510
Glenn Kastend848eb42016-03-08 13:42:11 -08001511sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001512{
1513 Mutex::Autolock _l(mLock);
1514 return getEffectChain_l(sessionId);
1515}
1516
Glenn Kastend848eb42016-03-08 13:42:11 -08001517sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1518 const
Eric Laurent81784c32012-11-19 14:55:58 -08001519{
1520 size_t size = mEffectChains.size();
1521 for (size_t i = 0; i < size; i++) {
1522 if (mEffectChains[i]->sessionId() == sessionId) {
1523 return mEffectChains[i];
1524 }
1525 }
1526 return 0;
1527}
1528
1529void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1530{
1531 Mutex::Autolock _l(mLock);
1532 size_t size = mEffectChains.size();
1533 for (size_t i = 0; i < size; i++) {
1534 mEffectChains[i]->setMode_l(mode);
1535 }
1536}
1537
Mikhail Naganovdc769682018-05-04 15:34:08 -07001538void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001539{
1540 config->type = AUDIO_PORT_TYPE_MIX;
1541 config->ext.mix.handle = mId;
1542 config->sample_rate = mSampleRate;
1543 config->format = mFormat;
1544 config->channel_mask = mChannelMask;
1545 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1546 AUDIO_PORT_CONFIG_FORMAT;
1547}
1548
Eric Laurent72e3f392015-05-20 14:43:50 -07001549void AudioFlinger::ThreadBase::systemReady()
1550{
1551 Mutex::Autolock _l(mLock);
1552 if (mSystemReady) {
1553 return;
1554 }
1555 mSystemReady = true;
1556
1557 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1558 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1559 }
1560 mPendingConfigEvents.clear();
1561}
1562
Andy Hungdae27702016-10-31 14:01:16 -07001563template <typename T>
1564ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1565 ssize_t index = mActiveTracks.indexOf(track);
1566 if (index >= 0) {
1567 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1568 return index;
1569 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001570 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001571 mActiveTracksGeneration++;
1572 mLatestActiveTrack = track;
1573 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001574 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001575 return mActiveTracks.add(track);
1576}
1577
1578template <typename T>
1579ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1580 ssize_t index = mActiveTracks.remove(track);
1581 if (index < 0) {
1582 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1583 return index;
1584 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001585 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001586 mActiveTracksGeneration++;
1587 --mBatteryCounter[track->uid()].second;
1588 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001589 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001590#ifdef TEE_SINK
1591 track->dumpTee(-1 /* fd */, "_REMOVE");
1592#endif
Andy Hungdae27702016-10-31 14:01:16 -07001593 return index;
1594}
1595
1596template <typename T>
1597void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1598 for (const sp<T> &track : mActiveTracks) {
1599 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001600 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001601 }
1602 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001603 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001604 mActiveTracks.clear();
1605 mLatestActiveTrack.clear();
1606 mBatteryCounter.clear();
1607}
1608
1609template <typename T>
1610void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1611 sp<ThreadBase> thread, bool force) {
1612 // Updates ActiveTracks client uids to the thread wakelock.
1613 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1614 thread->updateWakeLockUids_l(getWakeLockUids());
1615 mLastActiveTracksGeneration = mActiveTracksGeneration;
1616 }
1617
1618 // Updates BatteryNotifier uids
1619 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1620 const uid_t uid = it->first;
1621 ssize_t &previous = it->second.first;
1622 ssize_t &current = it->second.second;
1623 if (current > 0) {
1624 if (previous == 0) {
1625 BatteryNotifier::getInstance().noteStartAudio(uid);
1626 }
1627 previous = current;
1628 ++it;
1629 } else if (current == 0) {
1630 if (previous > 0) {
1631 BatteryNotifier::getInstance().noteStopAudio(uid);
1632 }
1633 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1634 } else /* (current < 0) */ {
1635 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1636 }
1637 }
1638}
Eric Laurent83b88082014-06-20 18:31:16 -07001639
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001640template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001641bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1642 const bool hasChanged = mHasChanged;
1643 mHasChanged = false;
1644 return hasChanged;
1645}
1646
1647template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001648void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1649 const char *funcName, const sp<T> &track) const {
1650 if (mLocalLog != nullptr) {
1651 String8 result;
1652 track->appendDump(result, false /* active */);
1653 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1654 }
1655}
1656
Eric Laurent6acd1d42017-01-04 14:23:29 -08001657void AudioFlinger::ThreadBase::broadcast_l()
1658{
1659 // Thread could be blocked waiting for async
1660 // so signal it to handle state changes immediately
1661 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1662 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1663 mSignalPending = true;
1664 mWaitWorkCV.broadcast();
1665}
1666
Eric Laurent81784c32012-11-19 14:55:58 -08001667// ----------------------------------------------------------------------------
1668// Playback
1669// ----------------------------------------------------------------------------
1670
1671AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1672 AudioStreamOut* output,
1673 audio_io_handle_t id,
1674 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001675 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001676 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001677 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001678 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001679 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001680 mMixerBuffer(NULL),
1681 mMixerBufferSize(0),
1682 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1683 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001684 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001685 mEffectBuffer(NULL),
1686 mEffectBufferSize(0),
1687 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1688 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001689 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001690 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001691 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001692 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001693 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001694 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001695 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001696 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001697 mMixerStatus(MIXER_IDLE),
1698 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001699 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001700 mBytesRemaining(0),
1701 mCurrentWriteLength(0),
1702 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001703 mWriteAckSequence(0),
1704 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001705 mScreenState(AudioFlinger::mScreenState),
1706 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001707 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001708 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1709 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001710{
Glenn Kastend7dca052015-03-05 16:05:54 -08001711 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1712 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001713
1714 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1715 // it would be safer to explicitly pass initial masterVolume/masterMute as
1716 // parameter.
1717 //
1718 // If the HAL we are using has support for master volume or master mute,
1719 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1720 // and the mute set to false).
1721 mMasterVolume = audioFlinger->masterVolume_l();
1722 mMasterMute = audioFlinger->masterMute_l();
1723 if (mOutput && mOutput->audioHwDev) {
1724 if (mOutput->audioHwDev->canSetMasterVolume()) {
1725 mMasterVolume = 1.0;
1726 }
1727
1728 if (mOutput->audioHwDev->canSetMasterMute()) {
1729 mMasterMute = false;
1730 }
1731 }
1732
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001733 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001734
Eric Laurent223fd5c2014-11-11 13:43:36 -08001735 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001736 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001737 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001738 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001739 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1740 }
Eric Laurent98e38192018-02-15 18:31:53 -08001741 // Audio patch volume is always max
1742 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1743 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001744}
1745
1746AudioFlinger::PlaybackThread::~PlaybackThread()
1747{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001748 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001749 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001750 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001751 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001752}
1753
1754void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1755{
1756 dumpInternals(fd, args);
1757 dumpTracks(fd, args);
1758 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001759 dprintf(fd, " Local log:\n");
1760 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001761}
1762
Glenn Kasten0f11b512014-01-31 16:18:54 -08001763void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001764{
Eric Laurent81784c32012-11-19 14:55:58 -08001765 String8 result;
1766
Marco Nelissenb2208842014-02-07 14:00:50 -08001767 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001768 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1769 const stream_type_t *st = &mStreamTypes[i];
1770 if (i > 0) {
1771 result.appendFormat(", ");
1772 }
1773 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1774 if (st->mute) {
1775 result.append("M");
1776 }
1777 }
1778 result.append("\n");
1779 write(fd, result.string(), result.length());
1780 result.clear();
1781
Eric Laurent81784c32012-11-19 14:55:58 -08001782 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1783 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001784 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001785 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001786
1787 size_t numtracks = mTracks.size();
1788 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001789 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001790 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001791 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001792 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001793 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001794 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001795 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001796 for (size_t i = 0; i < numtracks; ++i) {
1797 sp<Track> track = mTracks[i];
1798 if (track != 0) {
1799 bool active = mActiveTracks.indexOf(track) >= 0;
1800 if (active) {
1801 numactiveseen++;
1802 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001803 result.append(prefix);
1804 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001805 }
1806 }
1807 } else {
1808 result.append("\n");
1809 }
1810 if (numactiveseen != numactive) {
1811 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001812 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001813 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001814 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001815 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001816 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001817 sp<Track> track = mActiveTracks[i];
1818 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001819 result.append(prefix);
1820 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001821 }
1822 }
1823 }
1824
1825 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001826}
1827
1828void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1829{
Glenn Kasten44182c22015-03-05 17:12:23 -08001830 dumpBase(fd, args);
1831
Elliott Hughes87cebad2014-05-22 10:14:43 -07001832 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001833 dprintf(fd, " Last write occurred (msecs): %llu\n",
1834 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001835 dprintf(fd, " Total writes: %d\n", mNumWrites);
1836 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1837 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1838 dprintf(fd, " Suspend count: %d\n", mSuspended);
1839 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1840 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1841 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1842 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001843 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001844 AudioStreamOut *output = mOutput;
1845 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001846 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1847 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001848 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1849 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1850 if (mPipeSink.get() != nullptr) {
1851 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1852 }
1853 if (output != nullptr) {
1854 dprintf(fd, " Hal stream dump:\n");
1855 (void)output->stream->dump(fd);
1856 }
Eric Laurent81784c32012-11-19 14:55:58 -08001857}
1858
1859// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001860
1861void AudioFlinger::PlaybackThread::onFirstRef()
1862{
Glenn Kastend7dca052015-03-05 16:05:54 -08001863 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001864}
1865
1866// ThreadBase virtuals
1867void AudioFlinger::PlaybackThread::preExit()
1868{
1869 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001870 // FIXME this is using hard-coded strings but in the future, this functionality will be
1871 // converted to use audio HAL extensions required to support tunneling
1872 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1873 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001874}
1875
1876// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1877sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1878 const sp<AudioFlinger::Client>& client,
1879 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001880 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001881 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001882 audio_format_t format,
1883 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001884 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001885 size_t *pNotificationFrameCount,
1886 uint32_t notificationsPerBuffer,
1887 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001888 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001889 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001890 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001891 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001892 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001893 status_t *status,
1894 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001895{
Glenn Kasten74935e42013-12-19 08:56:45 -08001896 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001897 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001898 sp<Track> track;
1899 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001900 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001901 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001902 uint32_t sampleRate;
1903
1904 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1905 lStatus = BAD_VALUE;
1906 goto Exit;
1907 }
Eric Laurent21da6472017-11-09 16:29:26 -08001908
1909 if (*pSampleRate == 0) {
1910 *pSampleRate = mSampleRate;
1911 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001912 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001913
1914 // special case for FAST flag considered OK if fast mixer is present
1915 if (hasFastMixer()) {
1916 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1917 }
1918
1919 // Check if requested flags are compatible with output stream flags
1920 if ((*flags & outputFlags) != *flags) {
1921 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1922 *flags, outputFlags);
1923 *flags = (audio_output_flags_t)(*flags & outputFlags);
1924 }
Eric Laurent81784c32012-11-19 14:55:58 -08001925
Eric Laurent81784c32012-11-19 14:55:58 -08001926 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001927 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001928 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001929 // PCM data
1930 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001931 // TODO: extract as a data library function that checks that a computationally
1932 // expensive downmixer is not required: isFastOutputChannelConversion()
Andy Hung9a592762014-07-21 21:56:01 -07001933 (channelMask == mChannelMask ||
Andy Hung1f439e12015-05-19 12:57:41 -07001934 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1935 (channelMask == AUDIO_CHANNEL_OUT_MONO
1936 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001937 // hardware sample rate
1938 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001939 // normal mixer has an associated fast mixer
1940 hasFastMixer() &&
1941 // there are sufficient fast track slots available
1942 (mFastTrackAvailMask != 0)
1943 // FIXME test that MixerThread for this fast track has a capable output HAL
1944 // FIXME add a permission test also?
1945 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001946 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1947 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001948 // read the fast track multiplier property the first time it is needed
1949 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1950 if (ok != 0) {
1951 ALOGE("%s pthread_once failed: %d", __func__, ok);
1952 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001953 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001954 }
Eric Laurent4c415062016-06-17 16:14:16 -07001955
1956 // check compatibility with audio effects.
1957 { // scope for mLock
1958 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001959 for (audio_session_t session : {
1960 AUDIO_SESSION_OUTPUT_STAGE,
1961 AUDIO_SESSION_OUTPUT_MIX,
1962 sessionId,
1963 }) {
1964 sp<EffectChain> chain = getEffectChain_l(session);
1965 if (chain.get() != nullptr) {
1966 audio_output_flags_t old = *flags;
1967 chain->checkOutputFlagCompatibility(flags);
1968 if (old != *flags) {
1969 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1970 (int)session, (int)old, (int)*flags);
1971 }
Eric Laurent4c415062016-06-17 16:14:16 -07001972 }
1973 }
1974 }
Eric Laurent122f7e72016-06-29 11:53:29 -07001975 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07001976 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
1977 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08001978 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001979 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
1980 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07001981 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08001982 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08001983 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08001984 audio_is_linear_pcm(format),
1985 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07001986 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08001987 }
1988 }
Eric Laurent21da6472017-11-09 16:29:26 -08001989
1990 if (!audio_has_proportional_frames(format)) {
1991 if (sharedBuffer != 0) {
1992 // Same comment as below about ignoring frameCount parameter for set()
1993 frameCount = sharedBuffer->size();
1994 } else if (frameCount == 0) {
1995 frameCount = mNormalFrameCount;
1996 }
1997 if (notificationFrameCount != frameCount) {
1998 notificationFrameCount = frameCount;
1999 }
2000 } else if (sharedBuffer != 0) {
2001 // FIXME: Ensure client side memory buffers need
2002 // not have additional alignment beyond sample
2003 // (e.g. 16 bit stereo accessed as 32 bit frame).
2004 size_t alignment = audio_bytes_per_sample(format);
2005 if (alignment & 1) {
2006 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2007 alignment = 1;
2008 }
2009 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2010 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2011 if (channelCount > 1) {
2012 // More than 2 channels does not require stronger alignment than stereo
2013 alignment <<= 1;
2014 }
2015 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2016 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2017 sharedBuffer->pointer(), channelCount);
2018 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002019 goto Exit;
2020 }
Eric Laurent21da6472017-11-09 16:29:26 -08002021
2022 // When initializing a shared buffer AudioTrack via constructors,
2023 // there's no frameCount parameter.
2024 // But when initializing a shared buffer AudioTrack via set(),
2025 // there _is_ a frameCount parameter. We silently ignore it.
2026 frameCount = sharedBuffer->size() / frameSize;
2027 } else {
2028 size_t minFrameCount = 0;
2029 // For fast tracks we try to respect the application's request for notifications per buffer.
2030 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2031 if (notificationsPerBuffer > 0) {
2032 // Avoid possible arithmetic overflow during multiplication.
2033 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2034 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2035 notificationsPerBuffer, mFrameCount);
2036 } else {
2037 minFrameCount = mFrameCount * notificationsPerBuffer;
2038 }
2039 }
2040 } else {
2041 // For normal PCM streaming tracks, update minimum frame count.
2042 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2043 // cover audio hardware latency.
2044 // This is probably too conservative, but legacy application code may depend on it.
2045 // If you change this calculation, also review the start threshold which is related.
2046 uint32_t latencyMs = latency_l();
2047 if (latencyMs == 0) {
2048 ALOGE("Error when retrieving output stream latency");
2049 lStatus = UNKNOWN_ERROR;
2050 goto Exit;
2051 }
2052
2053 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2054 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2055
Eric Laurent81784c32012-11-19 14:55:58 -08002056 }
Eric Laurent21da6472017-11-09 16:29:26 -08002057 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002058 frameCount = minFrameCount;
2059 }
Eric Laurent81784c32012-11-19 14:55:58 -08002060 }
Eric Laurent21da6472017-11-09 16:29:26 -08002061
2062 // Make sure that application is notified with sufficient margin before underrun.
2063 // The client can divide the AudioTrack buffer into sub-buffers,
2064 // and expresses its desire to server as the notification frame count.
2065 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2066 size_t maxNotificationFrames;
2067 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2068 // notify every HAL buffer, regardless of the size of the track buffer
2069 maxNotificationFrames = mFrameCount;
2070 } else {
2071 // For normal tracks, use at least double-buffering if no sample rate conversion,
2072 // or at least triple-buffering if there is sample rate conversion
2073 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2074 maxNotificationFrames = frameCount / nBuffering;
2075 // If client requested a fast track but this was denied, then use the smaller maximum.
2076 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2077 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2078 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2079 maxNotificationFrames = maxNotificationFramesFastDenied;
2080 }
2081 }
2082 }
2083 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2084 if (notificationFrameCount == 0) {
2085 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2086 maxNotificationFrames, frameCount);
2087 } else {
2088 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2089 notificationFrameCount, maxNotificationFrames, frameCount);
2090 }
2091 notificationFrameCount = maxNotificationFrames;
2092 }
2093 }
2094
Glenn Kasten74935e42013-12-19 08:56:45 -08002095 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002096 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002097
Glenn Kastenc3df8382014-03-13 15:05:25 -07002098 switch (mType) {
2099
2100 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002101 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002102 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002103 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2104 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002105 sampleRate, format, channelMask, mOutput, mFormat);
2106 lStatus = BAD_VALUE;
2107 goto Exit;
2108 }
2109 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002110 break;
2111
2112 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002113 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002114 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2115 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002116 sampleRate, format, channelMask, mOutput, mFormat);
2117 lStatus = BAD_VALUE;
2118 goto Exit;
2119 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002120 break;
2121
2122 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002123 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002124 ALOGE("createTrack_l() Bad parameter: format %#x \""
2125 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002126 format, mOutput, mFormat);
2127 lStatus = BAD_VALUE;
2128 goto Exit;
2129 }
Andy Hungcd044842014-08-07 11:04:34 -07002130 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002131 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2132 lStatus = BAD_VALUE;
2133 goto Exit;
2134 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002135 break;
2136
Eric Laurent81784c32012-11-19 14:55:58 -08002137 }
2138
2139 lStatus = initCheck();
2140 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002141 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002142 goto Exit;
2143 }
2144
2145 { // scope for mLock
2146 Mutex::Autolock _l(mLock);
2147
2148 // all tracks in same audio session must share the same routing strategy otherwise
2149 // conflicts will happen when tracks are moved from one output to another by audio policy
2150 // manager
2151 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2152 for (size_t i = 0; i < mTracks.size(); ++i) {
2153 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002154 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002155 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2156 if (sessionId == t->sessionId() && strategy != actual) {
2157 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2158 strategy, actual);
2159 lStatus = BAD_VALUE;
2160 goto Exit;
2161 }
2162 }
2163 }
2164
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002165 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002166 channelMask, frameCount,
2167 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002168 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002169
Glenn Kasten03003332013-08-06 15:40:54 -07002170 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2171 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002172 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002173 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002174 goto Exit;
2175 }
2176 mTracks.add(track);
2177
2178 sp<EffectChain> chain = getEffectChain_l(sessionId);
2179 if (chain != 0) {
2180 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2181 track->setMainBuffer(chain->inBuffer());
2182 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2183 chain->incTrackCnt();
2184 }
2185
Eric Laurent05067782016-06-01 18:27:28 -07002186 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002187 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2188 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2189 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002190 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002191 }
2192 }
2193
2194 lStatus = NO_ERROR;
2195
2196Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002197 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002198 return track;
2199}
2200
Andy Hung1bc088a2018-02-09 15:57:31 -08002201template<typename T>
2202ssize_t AudioFlinger::PlaybackThread::Tracks<T>::add(const sp<T> &track)
2203{
2204 const ssize_t index = mTracks.add(track);
2205 if (index >= 0) {
2206 // set name for track when adding.
2207 int name;
2208 if (mUnusedTrackNames.empty()) {
2209 name = mTracks.size() - 1; // new name {0 ... size-1}.
2210 } else {
2211 // reuse smallest name for deleted track.
2212 auto it = mUnusedTrackNames.begin();
2213 name = *it;
2214 (void)mUnusedTrackNames.erase(it);
2215 }
2216 track->setName(name);
2217 } else {
2218 LOG_ALWAYS_FATAL("cannot add track");
2219 }
2220 return index;
2221}
2222
2223template<typename T>
2224ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2225{
2226 const int name = track->name();
2227 const ssize_t index = mTracks.remove(track);
2228 if (index >= 0) {
2229 // invalidate name when removing from mTracks.
2230 LOG_ALWAYS_FATAL_IF(name < 0, "invalid name %d for track on mTracks", name);
2231
2232 if (mSaveDeletedTrackNames) {
2233 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
2234 // Instead, we add to mDeletedTrackNames which is solely used for mAudioMixer update,
2235 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
2236 mDeletedTrackNames.emplace(name);
2237 }
2238
2239 mUnusedTrackNames.emplace(name);
2240 track->setName(T::TRACK_NAME_PENDING);
2241 } else {
2242 LOG_ALWAYS_FATAL_IF(name >= 0,
2243 "valid name %d for track not in mTracks (returned %zd)", name, index);
2244 }
2245 return index;
2246}
2247
Eric Laurent81784c32012-11-19 14:55:58 -08002248uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2249{
2250 return latency;
2251}
2252
2253uint32_t AudioFlinger::PlaybackThread::latency() const
2254{
2255 Mutex::Autolock _l(mLock);
2256 return latency_l();
2257}
2258uint32_t AudioFlinger::PlaybackThread::latency_l() const
2259{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002260 uint32_t latency;
2261 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2262 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002263 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002264 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002265}
2266
2267void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2268{
2269 Mutex::Autolock _l(mLock);
2270 // Don't apply master volume in SW if our HAL can do it for us.
2271 if (mOutput && mOutput->audioHwDev &&
2272 mOutput->audioHwDev->canSetMasterVolume()) {
2273 mMasterVolume = 1.0;
2274 } else {
2275 mMasterVolume = value;
2276 }
2277}
2278
2279void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2280{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002281 if (isDuplicating()) {
2282 return;
2283 }
Eric Laurent81784c32012-11-19 14:55:58 -08002284 Mutex::Autolock _l(mLock);
2285 // Don't apply master mute in SW if our HAL can do it for us.
2286 if (mOutput && mOutput->audioHwDev &&
2287 mOutput->audioHwDev->canSetMasterMute()) {
2288 mMasterMute = false;
2289 } else {
2290 mMasterMute = muted;
2291 }
2292}
2293
2294void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2295{
2296 Mutex::Autolock _l(mLock);
2297 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002298 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002299}
2300
2301void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2302{
2303 Mutex::Autolock _l(mLock);
2304 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002305 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002306}
2307
2308float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2309{
2310 Mutex::Autolock _l(mLock);
2311 return mStreamTypes[stream].volume;
2312}
2313
2314// addTrack_l() must be called with ThreadBase::mLock held
2315status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2316{
2317 status_t status = ALREADY_EXISTS;
2318
Eric Laurent81784c32012-11-19 14:55:58 -08002319 if (mActiveTracks.indexOf(track) < 0) {
2320 // the track is newly added, make sure it fills up all its
2321 // buffers before playing. This is to ensure the client will
2322 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002323 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002324 TrackBase::track_state state = track->mState;
2325 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002326 status = AudioSystem::startOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002327 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002328 mLock.lock();
2329 // abort track was stopped/paused while we released the lock
2330 if (state != track->mState) {
2331 if (status == NO_ERROR) {
2332 mLock.unlock();
Eric Laurente83b55d2014-11-14 10:06:21 -08002333 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002334 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002335 mLock.lock();
2336 }
2337 return INVALID_OPERATION;
2338 }
2339 // abort if start is rejected by audio policy manager
2340 if (status != NO_ERROR) {
2341 return PERMISSION_DENIED;
2342 }
2343#ifdef ADD_BATTERY_DATA
2344 // to track the speaker usage
2345 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2346#endif
2347 }
2348
Eric Laurent51716182016-02-29 18:00:56 -08002349 // set retry count for buffer fill
2350 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002351 if (track->isStopping_1()) {
2352 track->mRetryCount = kMaxTrackStopRetriesOffload;
2353 } else {
2354 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2355 }
2356 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002357 } else {
2358 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002359 track->mFillingUpStatus =
2360 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002361 }
2362
Eric Laurent81784c32012-11-19 14:55:58 -08002363 track->mResetDone = false;
2364 track->mPresentationCompleteFrames = 0;
2365 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002366 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2367 if (chain != 0) {
2368 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2369 track->sessionId());
2370 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002371 }
2372
2373 status = NO_ERROR;
2374 }
2375
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002376 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002377 return status;
2378}
2379
Eric Laurentbfb1b832013-01-07 09:53:42 -08002380bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002381{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002382 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002383 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002384 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2385 track->mState = TrackBase::STOPPED;
2386 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002387 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002388 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002389 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002390 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002391
2392 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002393}
2394
2395void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2396{
2397 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002398
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002399 String8 result;
2400 track->appendDump(result, false /* active */);
2401 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002402
Eric Laurent81784c32012-11-19 14:55:58 -08002403 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002404 if (track->isFastTrack()) {
2405 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002406 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002407 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2408 mFastTrackAvailMask |= 1 << index;
2409 // redundant as track is about to be destroyed, for dumpsys only
2410 track->mFastIndex = -1;
2411 }
2412 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2413 if (chain != 0) {
2414 chain->decTrackCnt();
2415 }
2416}
2417
2418String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2419{
Eric Laurent81784c32012-11-19 14:55:58 -08002420 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002421 String8 out_s8;
2422 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2423 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002424 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002425 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002426}
2427
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002428void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002429 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2430 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002431
Eric Laurent73e26b62015-04-27 16:55:58 -07002432 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002433
2434 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002435 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002436 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002437 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002438 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002439 desc->mChannelMask = mChannelMask;
2440 desc->mSamplingRate = mSampleRate;
2441 desc->mFormat = mFormat;
2442 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002443 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002444 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002445 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002446 break;
2447
Eric Laurent73e26b62015-04-27 16:55:58 -07002448 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002449 default:
2450 break;
2451 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002452 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002453}
2454
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002455void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002456{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002457 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002458}
2459
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002460void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002461{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002462 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002463}
2464
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002465void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002466{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002467 mCallbackThread->setAsyncError();
2468}
2469
Eric Laurent3b4529e2013-09-05 18:09:19 -07002470void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002471{
2472 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002473 // reject out of sequence requests
2474 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2475 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002476 mWaitWorkCV.signal();
2477 }
2478}
2479
Eric Laurent3b4529e2013-09-05 18:09:19 -07002480void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481{
2482 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002483 // reject out of sequence requests
2484 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
2485 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486 mWaitWorkCV.signal();
2487 }
2488}
2489
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002490void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002491{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002492 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002493 mSampleRate = mOutput->getSampleRate();
2494 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002495 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002496 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002497 }
Andy Hung9a592762014-07-21 21:56:01 -07002498 if ((mType == MIXER || mType == DUPLICATING)
2499 && !isValidPcmSinkChannelMask(mChannelMask)) {
2500 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2501 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002502 }
Andy Hunge5412692014-05-16 11:25:07 -07002503 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002504
2505 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002506 status_t result = mOutput->stream->getFormat(&mHALFormat);
2507 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002508 // Get format from the shim, which will be different than the HAL format
2509 // if playing compressed audio over HDMI passthrough.
2510 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002511 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002512 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002513 }
Andy Hung6146c082014-03-18 11:56:15 -07002514 if ((mType == MIXER || mType == DUPLICATING)
2515 && !isValidPcmSinkFormat(mFormat)) {
2516 LOG_FATAL("HAL format %#x not supported for mixed output",
2517 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002518 }
Phil Burk062e67a2015-02-11 13:40:50 -08002519 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002520 result = mOutput->stream->getBufferSize(&mBufferSize);
2521 LOG_ALWAYS_FATAL_IF(result != OK,
2522 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002523 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002524 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002525 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002526 mFrameCount);
2527 }
2528
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002529 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2530 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002531 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002532 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002533 }
2534 }
2535
Eric Laurentd1f69b02014-12-15 14:33:13 -08002536 mHwSupportsPause = false;
2537 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002538 bool supportsPause = false, supportsResume = false;
2539 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2540 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002541 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002542 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002543 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002544 } else if (supportsResume) {
2545 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002546 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002547 }
2548 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002549 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2550 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2551 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002552
Andy Hungfbfc3952015-01-15 13:33:51 -08002553 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2554 // For best precision, we use float instead of the associated output
2555 // device format (typically PCM 16 bit).
2556
2557 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2558 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2559 mBufferSize = mFrameSize * mFrameCount;
2560
2561 // TODO: We currently use the associated output device channel mask and sample rate.
2562 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2563 // (if a valid mask) to avoid premature downmix.
2564 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2565 // instead of the output device sample rate to avoid loss of high frequency information.
2566 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2567 }
2568
Andy Hung09a50072014-02-27 14:30:47 -08002569 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002570 double multiplier = 1.0;
2571 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2572 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002573 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2574 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002575
Eric Laurent81784c32012-11-19 14:55:58 -08002576 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2577 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2578 maxNormalFrameCount = maxNormalFrameCount & ~15;
2579 if (maxNormalFrameCount < minNormalFrameCount) {
2580 maxNormalFrameCount = minNormalFrameCount;
2581 }
2582 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2583 if (multiplier <= 1.0) {
2584 multiplier = 1.0;
2585 } else if (multiplier <= 2.0) {
2586 if (2 * mFrameCount <= maxNormalFrameCount) {
2587 multiplier = 2.0;
2588 } else {
2589 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2590 }
2591 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002592 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002593 }
2594 }
2595 mNormalFrameCount = multiplier * mFrameCount;
2596 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002597 if (mType == MIXER || mType == DUPLICATING) {
2598 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2599 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002600 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002601 mNormalFrameCount);
2602
Andy Hung08fb1742015-05-31 23:22:10 -07002603 // Check if we want to throttle the processing to no more than 2x normal rate
2604 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002605 mThreadThrottleTimeMs = 0;
2606 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002607 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2608
Andy Hung010a1a12014-03-13 13:57:33 -07002609 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2610 // Originally this was int16_t[] array, need to remove legacy implications.
2611 free(mSinkBuffer);
2612 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002613 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2614 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2615 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002616 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002617
Andy Hung69aed5f2014-02-25 17:24:40 -08002618 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2619 // drives the output.
2620 free(mMixerBuffer);
2621 mMixerBuffer = NULL;
2622 if (mMixerBufferEnabled) {
2623 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // also valid: AUDIO_FORMAT_PCM_16_BIT.
2624 mMixerBufferSize = mNormalFrameCount * mChannelCount
2625 * audio_bytes_per_sample(mMixerBufferFormat);
2626 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2627 }
Andy Hung98ef9782014-03-04 14:46:50 -08002628 free(mEffectBuffer);
2629 mEffectBuffer = NULL;
2630 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002631 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002632 mEffectBufferSize = mNormalFrameCount * mChannelCount
2633 * audio_bytes_per_sample(mEffectBufferFormat);
2634 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2635 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002636
Eric Laurent81784c32012-11-19 14:55:58 -08002637 // force reconfiguration of effect chains and engines to take new buffer size and audio
2638 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002639 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002640 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2641 // matter.
2642 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2643 Vector< sp<EffectChain> > effectChains = mEffectChains;
2644 for (size_t i = 0; i < effectChains.size(); i ++) {
2645 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2646 }
2647}
2648
Kevin Rocard069c2712018-03-29 19:09:14 -07002649void AudioFlinger::PlaybackThread::updateMetadata_l()
2650{
Kevin Rocard12381092018-04-11 09:19:59 -07002651 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2652 return; // That should not happen
2653 }
2654 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2655 for (const sp<Track> &track : mActiveTracks) {
2656 // Do not short-circuit as all hasChanged states must be reset
2657 // as all the metadata are going to be sent
2658 hasChanged |= track->readAndClearHasChanged();
2659 }
2660 if (!hasChanged) {
2661 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002662 }
2663 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002664 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002665 for (const sp<Track> &track : mActiveTracks) {
2666 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002667 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002668 }
Kevin Rocard12381092018-04-11 09:19:59 -07002669 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002670}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002671
Kevin Rocard12381092018-04-11 09:19:59 -07002672void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2673 const StreamOutHalInterface::SourceMetadata& metadata)
2674{
2675 mOutput->stream->updateSourceMetadata(metadata);
2676};
2677
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002678status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002679{
2680 if (halFrames == NULL || dspFrames == NULL) {
2681 return BAD_VALUE;
2682 }
2683 Mutex::Autolock _l(mLock);
2684 if (initCheck() != NO_ERROR) {
2685 return INVALID_OPERATION;
2686 }
Andy Hung818e7a32016-02-16 18:08:07 -08002687 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002688 *halFrames = framesWritten;
2689
2690 if (isSuspended()) {
2691 // return an estimation of rendered frames when the output is suspended
2692 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002693 *dspFrames = (uint32_t)
2694 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002695 return NO_ERROR;
2696 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002697 status_t status;
2698 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002699 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002700 *dspFrames = (size_t)frames;
2701 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002702 }
2703}
2704
Eric Laurent4c415062016-06-17 16:14:16 -07002705// hasAudioSession_l() must be called with ThreadBase::mLock held
2706uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002707{
Eric Laurent81784c32012-11-19 14:55:58 -08002708 uint32_t result = 0;
2709 if (getEffectChain_l(sessionId) != 0) {
2710 result = EFFECT_SESSION;
2711 }
2712
2713 for (size_t i = 0; i < mTracks.size(); ++i) {
2714 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002715 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002716 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002717 if (track->isFastTrack()) {
2718 result |= FAST_SESSION;
2719 }
Eric Laurent81784c32012-11-19 14:55:58 -08002720 break;
2721 }
2722 }
2723
2724 return result;
2725}
2726
Glenn Kastend848eb42016-03-08 13:42:11 -08002727uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002728{
2729 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2730 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2731 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2732 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2733 }
2734 for (size_t i = 0; i < mTracks.size(); i++) {
2735 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002736 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002737 return AudioSystem::getStrategyForStream(track->streamType());
2738 }
2739 }
2740 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2741}
2742
2743
Phil Burk062e67a2015-02-11 13:40:50 -08002744AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002745{
2746 Mutex::Autolock _l(mLock);
2747 return mOutput;
2748}
2749
Phil Burk062e67a2015-02-11 13:40:50 -08002750AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002751{
2752 Mutex::Autolock _l(mLock);
2753 AudioStreamOut *output = mOutput;
2754 mOutput = NULL;
2755 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2756 // must push a NULL and wait for ack
2757 mOutputSink.clear();
2758 mPipeSink.clear();
2759 mNormalSink.clear();
2760 return output;
2761}
2762
2763// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002764sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002765{
2766 if (mOutput == NULL) {
2767 return NULL;
2768 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002769 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002770}
2771
2772uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2773{
2774 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2775}
2776
2777status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2778{
2779 if (!isValidSyncEvent(event)) {
2780 return BAD_VALUE;
2781 }
2782
2783 Mutex::Autolock _l(mLock);
2784
2785 for (size_t i = 0; i < mTracks.size(); ++i) {
2786 sp<Track> track = mTracks[i];
2787 if (event->triggerSession() == track->sessionId()) {
2788 (void) track->setSyncEvent(event);
2789 return NO_ERROR;
2790 }
2791 }
2792
2793 return NAME_NOT_FOUND;
2794}
2795
2796bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2797{
2798 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2799}
2800
2801void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2802 const Vector< sp<Track> >& tracksToRemove)
2803{
2804 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07002805 if (count > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08002806 for (size_t i = 0 ; i < count ; i++) {
2807 const sp<Track>& track = tracksToRemove.itemAt(i);
Eric Laurent83b88082014-06-20 18:31:16 -07002808 if (track->isExternalTrack()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002809 AudioSystem::stopOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002810 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002811#ifdef ADD_BATTERY_DATA
2812 // to track the speaker usage
2813 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
2814#endif
2815 if (track->isTerminated()) {
Eric Laurente83b55d2014-11-14 10:06:21 -08002816 AudioSystem::releaseOutput(mId, track->streamType(),
Glenn Kastend848eb42016-03-08 13:42:11 -08002817 track->sessionId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002818 }
Eric Laurent81784c32012-11-19 14:55:58 -08002819 }
2820 }
2821 }
Eric Laurent81784c32012-11-19 14:55:58 -08002822}
2823
2824void AudioFlinger::PlaybackThread::checkSilentMode_l()
2825{
2826 if (!mMasterMute) {
2827 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002828 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2829 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2830 return;
2831 }
Eric Laurent81784c32012-11-19 14:55:58 -08002832 if (property_get("ro.audio.silent", value, "0") > 0) {
2833 char *endptr;
2834 unsigned long ul = strtoul(value, &endptr, 0);
2835 if (*endptr == '\0' && ul != 0) {
2836 ALOGD("Silence is golden");
2837 // The setprop command will not allow a property to be changed after
2838 // the first time it is set, so we don't have to worry about un-muting.
2839 setMasterMute_l(true);
2840 }
2841 }
2842 }
2843}
2844
2845// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002846ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002847{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002848 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002849 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002850 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002851 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002852
2853 // If an NBAIO sink is present, use it to write the normal mixer's submix
2854 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002855
Andy Hung010a1a12014-03-13 13:57:33 -07002856 const size_t count = mBytesRemaining / mFrameSize;
2857
Simon Wilson2d590962012-11-29 15:18:50 -08002858 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002859 // update the setpoint when AudioFlinger::mScreenState changes
2860 uint32_t screenState = AudioFlinger::mScreenState;
2861 if (screenState != mScreenState) {
2862 mScreenState = screenState;
2863 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2864 if (pipe != NULL) {
2865 pipe->setAvgFrames((mScreenState & 1) ?
2866 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2867 }
2868 }
Andy Hung010a1a12014-03-13 13:57:33 -07002869 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002870 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002871 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002872 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002873#ifdef TEE_SINK
2874 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2875#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002876 } else {
2877 bytesWritten = framesWritten;
2878 }
2879 // otherwise use the HAL / AudioStreamOut directly
2880 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002882
Eric Laurentbfb1b832013-01-07 09:53:42 -08002883 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002884 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2885 mWriteAckSequence += 2;
2886 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002888 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002889 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002890 // FIXME We should have an implementation of timestamps for direct output threads.
2891 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002892 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002893
Eric Laurentbfb1b832013-01-07 09:53:42 -08002894 if (mUseAsyncWrite &&
2895 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2896 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002897 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002898 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002899 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 }
Eric Laurent81784c32012-11-19 14:55:58 -08002901 }
2902
Eric Laurent81784c32012-11-19 14:55:58 -08002903 mNumWrites++;
2904 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002905 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002906 return bytesWritten;
2907}
2908
2909void AudioFlinger::PlaybackThread::threadLoop_drain()
2910{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002911 bool supportsDrain = false;
2912 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2914 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002915 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2916 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002918 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002920 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002921 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002922 }
2923}
2924
2925void AudioFlinger::PlaybackThread::threadLoop_exit()
2926{
Eric Laurent275e8e92014-11-30 15:14:47 -08002927 {
2928 Mutex::Autolock _l(mLock);
2929 for (size_t i = 0; i < mTracks.size(); i++) {
2930 sp<Track> track = mTracks[i];
2931 track->invalidate();
2932 }
Andy Hungdae27702016-10-31 14:01:16 -07002933 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2934 // After we exit there are no more track changes sent to BatteryNotifier
2935 // because that requires an active threadLoop.
2936 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2937 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002938 }
Eric Laurent81784c32012-11-19 14:55:58 -08002939}
2940
2941/*
2942The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002943 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002944 - mActiveSleepTimeUs from activeSleepTimeUs()
2945 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002946 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2947 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002948 - maxPeriod from frame count and sample rate (MIXER only)
2949
2950The parameters that affect these derived values are:
2951 - frame count
2952 - frame size
2953 - sample rate
2954 - device type: A2DP or not
2955 - device latency
2956 - format: PCM or not
2957 - active sleep time
2958 - idle sleep time
2959*/
2960
2961void AudioFlinger::PlaybackThread::cacheParameters_l()
2962{
Andy Hung25c2dac2014-02-27 14:56:00 -08002963 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002964 mActiveSleepTimeUs = activeSleepTimeUs();
2965 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08002966
2967 // make sure standby delay is not too short when connected to an A2DP sink to avoid
2968 // truncating audio when going to standby.
2969 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
2970 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
2971 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
2972 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
2973 }
2974 }
Eric Laurent81784c32012-11-19 14:55:58 -08002975}
2976
Eric Laurent13084622016-05-17 10:51:49 -07002977bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08002978{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002979 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08002980 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07002981 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002982 size_t size = mTracks.size();
2983 for (size_t i = 0; i < size; i++) {
2984 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07002985 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08002986 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07002987 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08002988 }
2989 }
Eric Laurent13084622016-05-17 10:51:49 -07002990 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002991}
2992
Haynes Mathew George05317d22016-05-03 16:34:26 -07002993void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
2994{
2995 Mutex::Autolock _l(mLock);
2996 invalidateTracks_l(streamType);
2997}
2998
Eric Laurent81784c32012-11-19 14:55:58 -08002999status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3000{
Glenn Kastend848eb42016-03-08 13:42:11 -08003001 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003002 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003003 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003004 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3005 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3006 &halInBuffer);
3007 if (result != OK) return result;
3008 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003009 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003010 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003011 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003012 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003013 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003014 if (mType != DIRECT) {
3015 size_t numSamples = mNormalFrameCount * mChannelCount;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003016 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003017 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003018 &halInBuffer);
3019 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003020#ifdef FLOAT_EFFECT_CHAIN
3021 buffer = halInBuffer->audioBuffer()->f32;
3022#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003023 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003024#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003025 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3026 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003027 }
3028
3029 // Attach all tracks with same session ID to this chain.
3030 for (size_t i = 0; i < mTracks.size(); ++i) {
3031 sp<Track> track = mTracks[i];
3032 if (session == track->sessionId()) {
3033 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3034 buffer);
3035 track->setMainBuffer(buffer);
3036 chain->incTrackCnt();
3037 }
3038 }
3039
3040 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003041 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003042 if (session == track->sessionId()) {
3043 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3044 chain->incActiveTrackCnt();
3045 }
3046 }
3047 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003048 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003049 chain->setInBuffer(halInBuffer);
3050 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003051 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003052 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003053 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3054 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003055 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003056 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003057 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003058 // Effect chain for other sessions are inserted at beginning of effect
3059 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003060 // sessions is not important.
3061 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3062 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3063 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003064 size_t size = mEffectChains.size();
3065 size_t i = 0;
3066 for (i = 0; i < size; i++) {
3067 if (mEffectChains[i]->sessionId() < session) {
3068 break;
3069 }
3070 }
3071 mEffectChains.insertAt(chain, i);
3072 checkSuspendOnAddEffectChain_l(chain);
3073
3074 return NO_ERROR;
3075}
3076
3077size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3078{
Glenn Kastend848eb42016-03-08 13:42:11 -08003079 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003080
3081 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3082
3083 for (size_t i = 0; i < mEffectChains.size(); i++) {
3084 if (chain == mEffectChains[i]) {
3085 mEffectChains.removeAt(i);
3086 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003087 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003088 if (session == track->sessionId()) {
3089 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3090 chain.get(), session);
3091 chain->decActiveTrackCnt();
3092 }
3093 }
3094
3095 // detach all tracks with same session ID from this chain
3096 for (size_t i = 0; i < mTracks.size(); ++i) {
3097 sp<Track> track = mTracks[i];
3098 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003099 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003100 chain->decTrackCnt();
3101 }
3102 }
3103 break;
3104 }
3105 }
3106 return mEffectChains.size();
3107}
3108
3109status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003110 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003111{
3112 Mutex::Autolock _l(mLock);
3113 return attachAuxEffect_l(track, EffectId);
3114}
3115
3116status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003117 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003118{
3119 status_t status = NO_ERROR;
3120
3121 if (EffectId == 0) {
3122 track->setAuxBuffer(0, NULL);
3123 } else {
3124 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3125 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3126 if (effect != 0) {
3127 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3128 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3129 } else {
3130 status = INVALID_OPERATION;
3131 }
3132 } else {
3133 status = BAD_VALUE;
3134 }
3135 }
3136 return status;
3137}
3138
3139void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3140{
3141 for (size_t i = 0; i < mTracks.size(); ++i) {
3142 sp<Track> track = mTracks[i];
3143 if (track->auxEffectId() == effectId) {
3144 attachAuxEffect_l(track, 0);
3145 }
3146 }
3147}
3148
3149bool AudioFlinger::PlaybackThread::threadLoop()
3150{
Glenn Kasten388d5712017-04-07 14:38:41 -07003151 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003152
Eric Laurent81784c32012-11-19 14:55:58 -08003153 Vector< sp<Track> > tracksToRemove;
3154
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003155 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003156 nsecs_t lastWriteFinished = -1; // time last server write completed
3157 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003158
3159 // MIXER
3160 nsecs_t lastWarning = 0;
3161
3162 // DUPLICATING
3163 // FIXME could this be made local to while loop?
3164 writeFrames = 0;
3165
3166 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003167 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003168
3169 if (mType == MIXER) {
3170 sleepTimeShift = 0;
3171 }
3172
3173 CpuStats cpuStats;
3174 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3175
3176 acquireWakeLock();
3177
Glenn Kasteneef598c2017-04-03 14:41:13 -07003178 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3179 // thread associated with this PlaybackThread.
3180 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3181 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003182 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3183 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003184 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003185 const char *logString = NULL;
3186
rago1bb90822017-05-02 18:31:48 -07003187 // Estimated time for next buffer to be written to hal. This is used only on
3188 // suspended mode (for now) to help schedule the wait time until next iteration.
3189 nsecs_t timeLoopNextNs = 0;
3190
Eric Laurent664539d2013-09-23 18:24:31 -07003191 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003192
Eric Laurent81784c32012-11-19 14:55:58 -08003193 while (!exitPending())
3194 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003195 // Log merge requests are performed during AudioFlinger binder transactions, but
3196 // that does not cover audio playback. It's requested here for that reason.
3197 mAudioFlinger->requestLogMerge();
3198
Eric Laurent81784c32012-11-19 14:55:58 -08003199 cpuStats.sample(myName);
3200
3201 Vector< sp<EffectChain> > effectChains;
3202
Eric Laurent81784c32012-11-19 14:55:58 -08003203 { // scope for mLock
3204
3205 Mutex::Autolock _l(mLock);
3206
Eric Laurent021cf962014-05-13 10:18:14 -07003207 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003208
Glenn Kasteneef598c2017-04-03 14:41:13 -07003209 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003210 if (logString != NULL) {
3211 mNBLogWriter->logTimestamp();
3212 mNBLogWriter->log(logString);
3213 logString = NULL;
3214 }
3215
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003216 // Collect timestamp statistics for the Playback Thread types that support it.
3217 if (mType == MIXER
3218 || mType == DUPLICATING
3219 || (mType == DIRECT && audio_is_linear_pcm(mHALFormat))) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003220 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003221 // and associate with the sink frames written out. We need
3222 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003223 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003224 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003225 if (mStandby) {
3226 mTimestampVerifier.discontinuity();
3227 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3228 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3229 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3230 mSampleRate);
Andy Hung818e7a32016-02-16 18:08:07 -08003231 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003232 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003233
3234 // We keep track of the last valid kernel position in case we are in underrun
3235 // and the normal mixer period is the same as the fast mixer period, or there
3236 // is some error from the HAL.
3237 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3238 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3239 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3240 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3241 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3242
3243 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3244 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3245 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3246 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003247 }
3248
3249 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3250 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003251 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003252 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003253 }
3254
Andy Hung818e7a32016-02-16 18:08:07 -08003255 // copy over kernel info
3256 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003257 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3258 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003259 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3260 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003261 } else {
3262 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003263 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003264
Andy Hungc54b1ff2016-02-23 14:07:07 -08003265 // mFramesWritten for non-offloaded tracks are contiguous
3266 // even after standby() is called. This is useful for the track frame
3267 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003268 bool serverLocationUpdate = false;
3269 if (mFramesWritten != lastFramesWritten) {
3270 serverLocationUpdate = true;
3271 lastFramesWritten = mFramesWritten;
3272 }
3273 // Only update timestamps if there is a meaningful change.
3274 // Either the kernel timestamp must be valid or we have written something.
3275 if (kernelLocationUpdate || serverLocationUpdate) {
3276 if (serverLocationUpdate) {
3277 // use the time before we called the HAL write - it is a bit more accurate
3278 // to when the server last read data than the current time here.
3279 //
3280 // If we haven't written anything, mLastWriteTime will be -1
3281 // and we use systemTime().
3282 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3283 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3284 ? systemTime() : mLastWriteTime;
3285 }
Andy Hungdae27702016-10-31 14:01:16 -07003286
3287 for (const sp<Track> &t : mActiveTracks) {
3288 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003289 t->updateTrackFrameInfo(
3290 t->mAudioTrackServerProxy->framesReleased(),
3291 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003292 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003293 mTimestamp);
3294 }
Andy Hunge10393e2015-06-12 13:59:33 -07003295 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003296 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003297 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003298#if 0
3299 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003300 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003301 timespec ts;
3302 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003303 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003304 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003305 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003306 }
3307 ++z;
3308#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003309 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 if (mSignalPending) {
3311 // A signal was raised while we were unlocked
3312 mSignalPending = false;
3313 } else if (waitingAsyncCallback_l()) {
3314 if (exitPending()) {
3315 break;
3316 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003317 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003318 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003319 releaseWakeLock_l();
3320 released = true;
3321 }
Andy Hung10cbff12017-02-21 17:30:14 -08003322
3323 const int64_t waitNs = computeWaitTimeNs_l();
3324 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3325 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3326 if (status == TIMED_OUT) {
3327 mSignalPending = true; // if timeout recheck everything
3328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003329 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003330 if (released) {
3331 acquireWakeLock_l();
3332 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003333 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3334 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003335
3336 continue;
3337 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003338 if ((!mActiveTracks.size() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003339 isSuspended()) {
3340 // put audio hardware into standby after short delay
3341 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003342
3343 threadLoop_standby();
3344
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003345 // This is where we go into standby
3346 if (!mStandby) {
3347 LOG_AUDIO_STATE();
3348 }
Eric Laurent81784c32012-11-19 14:55:58 -08003349 mStandby = true;
3350 }
3351
3352 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
3353 // we're about to wait, flush the binder command buffer
3354 IPCThreadState::self()->flushCommands();
3355
3356 clearOutputTracks();
3357
3358 if (exitPending()) {
3359 break;
3360 }
3361
3362 releaseWakeLock_l();
3363 // wait until we have something to do...
3364 ALOGV("%s going to sleep", myName.string());
3365 mWaitWorkCV.wait(mLock);
3366 ALOGV("%s waking up", myName.string());
3367 acquireWakeLock_l();
3368
3369 mMixerStatus = MIXER_IDLE;
3370 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3371 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003372 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003373 checkSilentMode_l();
3374
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003375 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3376 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003377 if (mType == MIXER) {
3378 sleepTimeShift = 0;
3379 }
3380
3381 continue;
3382 }
3383 }
Eric Laurent81784c32012-11-19 14:55:58 -08003384 // mMixerStatusIgnoringFastTracks is also updated internally
3385 mMixerStatus = prepareTracks_l(&tracksToRemove);
3386
Andy Hungdae27702016-10-31 14:01:16 -07003387 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003388
Kevin Rocard069c2712018-03-29 19:09:14 -07003389 updateMetadata_l();
3390
Eric Laurent81784c32012-11-19 14:55:58 -08003391 // prevent any changes in effect chain list and in each effect chain
3392 // during mixing and effect process as the audio buffers could be deleted
3393 // or modified if an effect is created or deleted
3394 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003395 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003396
Eric Laurentbfb1b832013-01-07 09:53:42 -08003397 if (mBytesRemaining == 0) {
3398 mCurrentWriteLength = 0;
3399 if (mMixerStatus == MIXER_TRACKS_READY) {
3400 // threadLoop_mix() sets mCurrentWriteLength
3401 threadLoop_mix();
3402 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3403 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003404 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003405 // must be written to HAL
3406 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003407 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003408 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003409 }
3410 }
Andy Hung98ef9782014-03-04 14:46:50 -08003411 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003412 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003413 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3414 // or mSinkBuffer (if there are no effects).
3415 //
3416 // This is done pre-effects computation; if effects change to
3417 // support higher precision, this needs to move.
3418 //
3419 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003420 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003421 if (mMixerBufferValid) {
3422 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3423 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3424
Andy Hung2ddee192015-12-18 17:34:44 -08003425 // mono blend occurs for mixer threads only (not direct or offloaded)
3426 // and is handled here if we're going directly to the sink.
3427 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003428 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3429 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003430 }
3431
Andy Hung98ef9782014-03-04 14:46:50 -08003432 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
3433 mNormalFrameCount * mChannelCount);
3434 }
3435
Eric Laurentbfb1b832013-01-07 09:53:42 -08003436 mBytesRemaining = mCurrentWriteLength;
3437 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003438 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3439 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3440 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3441 mBytesWritten += mBytesRemaining;
3442 mFramesWritten += framesRemaining;
3443 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003444 mBytesRemaining = 0;
3445 }
Eric Laurent81784c32012-11-19 14:55:58 -08003446
Eric Laurentbfb1b832013-01-07 09:53:42 -08003447 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003448 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003449 for (size_t i = 0; i < effectChains.size(); i ++) {
3450 effectChains[i]->process_l();
3451 }
Eric Laurent81784c32012-11-19 14:55:58 -08003452 }
3453 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003454 // Process effect chains for offloaded thread even if no audio
3455 // was read from audio track: process only updates effect state
3456 // and thus does have to be synchronized with audio writes but may have
3457 // to be called while waiting for async write callback
3458 if (mType == OFFLOAD) {
3459 for (size_t i = 0; i < effectChains.size(); i ++) {
3460 effectChains[i]->process_l();
3461 }
3462 }
Eric Laurent81784c32012-11-19 14:55:58 -08003463
Andy Hung98ef9782014-03-04 14:46:50 -08003464 // Only if the Effects buffer is enabled and there is data in the
3465 // Effects buffer (buffer valid), we need to
3466 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003467 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003468 if (mEffectBufferValid) {
3469 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003470
3471 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003472 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3473 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003474 }
3475
Andy Hung98ef9782014-03-04 14:46:50 -08003476 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3477 mNormalFrameCount * mChannelCount);
3478 }
3479
Eric Laurent81784c32012-11-19 14:55:58 -08003480 // enable changes in effect chain
3481 unlockEffectChains(effectChains);
3482
Eric Laurentbfb1b832013-01-07 09:53:42 -08003483 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003484 // mSleepTimeUs == 0 means we must write to audio hardware
3485 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003486 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003487 // We save lastWriteFinished here, as previousLastWriteFinished,
3488 // for throttling. On thread start, previousLastWriteFinished will be
3489 // set to -1, which properly results in no throttling after the first write.
3490 nsecs_t previousLastWriteFinished = lastWriteFinished;
3491 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003492 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003493 // FIXME rewrite to reduce number of system calls
3494 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003495 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003496 lastWriteFinished = systemTime();
3497 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003498 if (ret < 0) {
3499 mBytesRemaining = 0;
3500 } else {
3501 mBytesWritten += ret;
3502 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003503 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003504 }
3505 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3506 (mMixerStatus == MIXER_DRAIN_ALL)) {
3507 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003508 }
Andy Hung08fb1742015-05-31 23:22:10 -07003509 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003510 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003511 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003512 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003513 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003514 ATRACE_NAME("underrun");
3515 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003516 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003517 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003518 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519 }
Andy Hung08fb1742015-05-31 23:22:10 -07003520
3521 if (mThreadThrottle
3522 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3523 && ret > 0) { // we wrote something
3524 // Limit MixerThread data processing to no more than twice the
3525 // expected processing rate.
3526 //
3527 // This helps prevent underruns with NuPlayer and other applications
3528 // which may set up buffers that are close to the minimum size, or use
3529 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3530 //
3531 // The throttle smooths out sudden large data drains from the device,
3532 // e.g. when it comes out of standby, which often causes problems with
3533 // (1) mixer threads without a fast mixer (which has its own warm-up)
3534 // (2) minimum buffer sized tracks (even if the track is full,
3535 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003536 //
3537 // Total time spent in last processing cycle equals time spent in
3538 // 1. threadLoop_write, as well as time spent in
3539 // 2. threadLoop_mix (significant for heavy mixing, especially
3540 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003541
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003542 // it's OK if deltaMs (and deltaNs) is an overestimate.
3543 nsecs_t deltaNs;
3544 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3545 __builtin_sub_overflow(
3546 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3547 const int32_t deltaMs = deltaNs / 1000000;
3548
Ivan Lozanoea04d392017-11-07 14:37:07 -08003549 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003550 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3551 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003552 // notify of throttle start on verbose log
3553 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3554 "mixer(%p) throttle begin:"
3555 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003556 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003557 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003558 // Throttle must be attributed to the previous mixer loop's write time
3559 // to allow back-to-back throttling.
3560 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003561 } else {
3562 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3563 if (diff > 0) {
3564 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003565 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003566 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3567 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003568 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003569 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3570 }
Andy Hung08fb1742015-05-31 23:22:10 -07003571 }
3572 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 }
Eric Laurent81784c32012-11-19 14:55:58 -08003574
Eric Laurentbfb1b832013-01-07 09:53:42 -08003575 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003576 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003577 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003578 // suspended requires accurate metering of sleep time.
3579 if (isSuspended()) {
3580 // advance by expected sleepTime
3581 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3582 const nsecs_t nowNs = systemTime();
3583
3584 // compute expected next time vs current time.
3585 // (negative deltas are treated as delays).
3586 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3587 if (deltaNs < -kMaxNextBufferDelayNs) {
3588 // Delays longer than the max allowed trigger a reset.
3589 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3590 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3591 timeLoopNextNs = nowNs + deltaNs;
3592 } else if (deltaNs < 0) {
3593 // Delays within the max delay allowed: zero the delta/sleepTime
3594 // to help the system catch up in the next iteration(s)
3595 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3596 deltaNs = 0;
3597 }
3598 // update sleep time (which is >= 0)
3599 mSleepTimeUs = deltaNs / 1000;
3600 }
Eric Laurente93cc032016-05-05 10:15:10 -07003601 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3602 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003603 }
Glenn Kastene7754022014-10-31 12:11:26 -07003604 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003605 }
Eric Laurent81784c32012-11-19 14:55:58 -08003606 }
3607
3608 // Finally let go of removed track(s), without the lock held
3609 // since we can't guarantee the destructors won't acquire that
3610 // same lock. This will also mutate and push a new fast mixer state.
3611 threadLoop_removeTracks(tracksToRemove);
3612 tracksToRemove.clear();
3613
3614 // FIXME I don't understand the need for this here;
3615 // it was in the original code but maybe the
3616 // assignment in saveOutputTracks() makes this unnecessary?
3617 clearOutputTracks();
3618
3619 // Effect chains will be actually deleted here if they were removed from
3620 // mEffectChains list during mixing or effects processing
3621 effectChains.clear();
3622
3623 // FIXME Note that the above .clear() is no longer necessary since effectChains
3624 // is now local to this block, but will keep it for now (at least until merge done).
3625 }
3626
Eric Laurentbfb1b832013-01-07 09:53:42 -08003627 threadLoop_exit();
3628
Eric Laurentcf817a22014-08-04 20:36:31 -07003629 if (!mStandby) {
3630 threadLoop_standby();
3631 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003632 }
3633
3634 releaseWakeLock();
3635
3636 ALOGV("Thread %p type %d exiting", this, mType);
3637 return false;
3638}
3639
Eric Laurentbfb1b832013-01-07 09:53:42 -08003640// removeTracks_l() must be called with ThreadBase::mLock held
3641void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3642{
3643 size_t count = tracksToRemove.size();
Glenn Kasten34fca342013-08-13 09:48:14 -07003644 if (count > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003645 for (size_t i=0 ; i<count ; i++) {
3646 const sp<Track>& track = tracksToRemove.itemAt(i);
3647 mActiveTracks.remove(track);
3648 ALOGV("removeTracks_l removing track on session %d", track->sessionId());
3649 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3650 if (chain != 0) {
3651 ALOGV("stopping track on chain %p for session Id: %d", chain.get(),
3652 track->sessionId());
3653 chain->decActiveTrackCnt();
3654 }
3655 if (track->isTerminated()) {
3656 removeTrack_l(track);
3657 }
3658 }
3659 }
3660
3661}
Eric Laurent81784c32012-11-19 14:55:58 -08003662
Eric Laurentaccc1472013-09-20 09:36:34 -07003663status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3664{
3665 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003666 ExtendedTimestamp ets;
3667 status_t status = mNormalSink->getTimestamp(ets);
3668 if (status == NO_ERROR) {
3669 status = ets.getBestTimestamp(&timestamp);
3670 }
3671 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003672 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003673 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003674 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003675 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003676 timestamp.mPosition = (uint32_t)position64;
3677 return NO_ERROR;
3678 }
3679 }
3680 return INVALID_OPERATION;
3681}
Eric Laurent1c333e22014-05-20 10:48:17 -07003682
Eric Laurent054d9d32015-04-24 08:48:48 -07003683status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3684 audio_patch_handle_t *handle)
3685{
Andy Hungf60abce2016-08-26 11:37:54 -07003686 status_t status;
3687 if (property_get_bool("af.patch_park", false /* default_value */)) {
3688 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3689 // or if HAL does not properly lock against access.
3690 AutoPark<FastMixer> park(mFastMixer);
3691 status = PlaybackThread::createAudioPatch_l(patch, handle);
3692 } else {
3693 status = PlaybackThread::createAudioPatch_l(patch, handle);
3694 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003695 return status;
3696}
3697
Eric Laurent1c333e22014-05-20 10:48:17 -07003698status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3699 audio_patch_handle_t *handle)
3700{
3701 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003702
3703 // store new device and send to effects
3704 audio_devices_t type = AUDIO_DEVICE_NONE;
3705 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3706 type |= patch->sinks[i].ext.device.type;
3707 }
3708
3709#ifdef ADD_BATTERY_DATA
3710 // when changing the audio output device, call addBatteryData to notify
3711 // the change
3712 if (mOutDevice != type) {
3713 uint32_t params = 0;
3714 // check whether speaker is on
3715 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3716 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003717 }
3718
Eric Laurent054d9d32015-04-24 08:48:48 -07003719 audio_devices_t deviceWithoutSpeaker
3720 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3721 // check if any other device (except speaker) is on
3722 if (type & deviceWithoutSpeaker) {
3723 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3724 }
3725
3726 if (params != 0) {
3727 addBatteryData(params);
3728 }
3729 }
3730#endif
3731
3732 for (size_t i = 0; i < mEffectChains.size(); i++) {
3733 mEffectChains[i]->setDevice_l(type);
3734 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003735
3736 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3737 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
3738 bool configChanged = mPrevOutDevice != type;
Eric Laurent054d9d32015-04-24 08:48:48 -07003739 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003740 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003741
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003742 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003743 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3744 status = hwDevice->createAudioPatch(patch->num_sources,
3745 patch->sources,
3746 patch->num_sinks,
3747 patch->sinks,
3748 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003749 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003750 char *address;
3751 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3752 //FIXME: we only support address on first sink with HAL version < 3.0
3753 address = audio_device_address_to_parameter(
3754 patch->sinks[0].ext.device.type,
3755 patch->sinks[0].ext.device.address);
3756 } else {
3757 address = (char *)calloc(1, 1);
3758 }
3759 AudioParameter param = AudioParameter(String8(address));
3760 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003761 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003762 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003763 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003765 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003766 mPrevOutDevice = type;
Eric Laurente8726fe2015-06-26 09:39:24 -07003767 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3768 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003769 return status;
3770}
3771
Eric Laurent054d9d32015-04-24 08:48:48 -07003772status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3773{
Andy Hungf60abce2016-08-26 11:37:54 -07003774 status_t status;
3775 if (property_get_bool("af.patch_park", false /* default_value */)) {
3776 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3777 // or if HAL does not properly lock against access.
3778 AutoPark<FastMixer> park(mFastMixer);
3779 status = PlaybackThread::releaseAudioPatch_l(handle);
3780 } else {
3781 status = PlaybackThread::releaseAudioPatch_l(handle);
3782 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003783 return status;
3784}
3785
Eric Laurent1c333e22014-05-20 10:48:17 -07003786status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3787{
3788 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003789
3790 mOutDevice = AUDIO_DEVICE_NONE;
3791
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003792 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003793 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3794 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003795 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003796 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003797 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003798 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003799 }
3800 return status;
3801}
3802
Eric Laurent83b88082014-06-20 18:31:16 -07003803void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3804{
3805 Mutex::Autolock _l(mLock);
3806 mTracks.add(track);
3807}
3808
3809void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3810{
3811 Mutex::Autolock _l(mLock);
3812 destroyTrack_l(track);
3813}
3814
Mikhail Naganovdc769682018-05-04 15:34:08 -07003815void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003816{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003817 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003818 config->role = AUDIO_PORT_ROLE_SOURCE;
3819 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3820 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003821 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3822 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3823 config->flags.output = mOutput->flags;
3824 }
Eric Laurent83b88082014-06-20 18:31:16 -07003825}
3826
Eric Laurent81784c32012-11-19 14:55:58 -08003827// ----------------------------------------------------------------------------
3828
3829AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07003830 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
3831 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08003832 // mAudioMixer below
3833 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08003834 mFastMixerFutex(0),
3835 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08003836 // mOutputSink below
3837 // mPipeSink below
3838 // mNormalSink below
3839{
3840 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003841 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003842 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003843 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
3844 mNormalFrameCount);
3845 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
3846
Andy Hungfbfc3952015-01-15 13:33:51 -08003847 if (type == DUPLICATING) {
3848 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
3849 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
3850 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
3851 return;
3852 }
Eric Laurent81784c32012-11-19 14:55:58 -08003853 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07003854 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08003855 size_t numCounterOffers = 0;
Glenn Kastenf69f9862014-03-07 08:37:57 -08003856 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003857#if !LOG_NDEBUG
3858 ssize_t index =
3859#else
3860 (void)
3861#endif
3862 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003863 ALOG_ASSERT(index == 0);
3864
3865 // initialize fast mixer depending on configuration
3866 bool initFastMixer;
3867 switch (kUseFastMixer) {
3868 case FastMixer_Never:
3869 initFastMixer = false;
3870 break;
3871 case FastMixer_Always:
3872 initFastMixer = true;
3873 break;
3874 case FastMixer_Static:
3875 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08003876 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
3877 // where the period is less than an experimentally determined threshold that can be
3878 // scheduled reliably with CFS. However, the BT A2DP HAL is
3879 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
3880 initFastMixer = mFrameCount < mNormalFrameCount
3881 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003882 break;
3883 }
Andy Hungfda69402017-02-15 14:33:12 -08003884 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
3885 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
3886 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003887 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07003888 audio_format_t fastMixerFormat;
3889 if (mMixerBufferEnabled && mEffectBufferEnabled) {
3890 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
3891 } else {
3892 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
3893 }
3894 if (mFormat != fastMixerFormat) {
3895 // change our Sink format to accept our intermediate precision
3896 mFormat = fastMixerFormat;
3897 free(mSinkBuffer);
3898 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3899 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
3900 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
3901 }
Eric Laurent81784c32012-11-19 14:55:58 -08003902
3903 // create a MonoPipe to connect our submix to FastMixer
3904 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07003905
Andy Hung1258c1a2014-05-23 21:22:17 -07003906 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003907 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07003908 format.mFormat = fastMixerFormat;
3909 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
3910
Eric Laurent81784c32012-11-19 14:55:58 -08003911 // This pipe depth compensates for scheduling latency of the normal mixer thread.
3912 // When it wakes up after a maximum latency, it runs a few cycles quickly before
3913 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
3914 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
3915 const NBAIO_Format offers[1] = {format};
3916 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07003917#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07003918 ssize_t index =
3919#else
3920 (void)
3921#endif
3922 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08003923 ALOG_ASSERT(index == 0);
3924 monoPipe->setAvgFrames((mScreenState & 1) ?
3925 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3926 mPipeSink = monoPipe;
3927
Eric Laurent81784c32012-11-19 14:55:58 -08003928 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07003929 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003930 FastMixerStateQueue *sq = mFastMixer->sq();
3931#ifdef STATE_QUEUE_DUMP
3932 sq->setObserverDump(&mStateQueueObserverDump);
3933 sq->setMutatorDump(&mStateQueueMutatorDump);
3934#endif
3935 FastMixerState *state = sq->begin();
3936 FastTrack *fastTrack = &state->mFastTracks[0];
3937 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
3938 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
3939 fastTrack->mVolumeProvider = NULL;
Andy Hunge8a1ced2014-05-09 15:02:21 -07003940 fastTrack->mChannelMask = mChannelMask; // mPipeSink channel mask for audio to FastMixer
3941 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
Eric Laurent81784c32012-11-19 14:55:58 -08003942 fastTrack->mGeneration++;
3943 state->mFastTracksGen++;
3944 state->mTrackMask = 1;
3945 // fast mixer will use the HAL output sink
3946 state->mOutputSink = mOutputSink.get();
3947 state->mOutputSinkGen++;
3948 state->mFrameCount = mFrameCount;
3949 state->mCommand = FastMixerState::COLD_IDLE;
3950 // already done in constructor initialization list
3951 //mFastMixerFutex = 0;
3952 state->mColdFutexAddr = &mFastMixerFutex;
3953 state->mColdGen++;
3954 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08003955 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
3956 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08003957 sq->end();
3958 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
3959
3960 // start the fast mixer
3961 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
3962 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003963 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08003964 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08003965
3966#ifdef AUDIO_WATCHDOG
3967 // create and start the watchdog
3968 mAudioWatchdog = new AudioWatchdog();
3969 mAudioWatchdog->setDump(&mAudioWatchdogDump);
3970 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
3971 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07003972 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08003973#endif
Andy Hung8946a282018-04-19 20:04:56 -07003974 } else {
3975#ifdef TEE_SINK
3976 // Only use the MixerThread tee if there is no FastMixer.
3977 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
3978 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
3979#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003980 }
3981
3982 switch (kUseFastMixer) {
3983 case FastMixer_Never:
3984 case FastMixer_Dynamic:
3985 mNormalSink = mOutputSink;
3986 break;
3987 case FastMixer_Always:
3988 mNormalSink = mPipeSink;
3989 break;
3990 case FastMixer_Static:
3991 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
3992 break;
3993 }
3994}
3995
3996AudioFlinger::MixerThread::~MixerThread()
3997{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07003998 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08003999 FastMixerStateQueue *sq = mFastMixer->sq();
4000 FastMixerState *state = sq->begin();
4001 if (state->mCommand == FastMixerState::COLD_IDLE) {
4002 int32_t old = android_atomic_inc(&mFastMixerFutex);
4003 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004004 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004005 }
4006 }
4007 state->mCommand = FastMixerState::EXIT;
4008 sq->end();
4009 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4010 mFastMixer->join();
4011 // Though the fast mixer thread has exited, it's state queue is still valid.
4012 // We'll use that extract the final state which contains one remaining fast track
4013 // corresponding to our sub-mix.
4014 state = sq->begin();
4015 ALOG_ASSERT(state->mTrackMask == 1);
4016 FastTrack *fastTrack = &state->mFastTracks[0];
4017 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4018 delete fastTrack->mBufferProvider;
4019 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004020 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004021#ifdef AUDIO_WATCHDOG
4022 if (mAudioWatchdog != 0) {
4023 mAudioWatchdog->requestExit();
4024 mAudioWatchdog->requestExitAndWait();
4025 mAudioWatchdog.clear();
4026 }
4027#endif
4028 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004029 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004030 delete mAudioMixer;
4031}
4032
4033
4034uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4035{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004036 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004037 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4038 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4039 }
4040 return latency;
4041}
4042
4043
4044void AudioFlinger::MixerThread::threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove)
4045{
4046 PlaybackThread::threadLoop_removeTracks(tracksToRemove);
4047}
4048
Eric Laurentbfb1b832013-01-07 09:53:42 -08004049ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004050{
4051 // FIXME we should only do one push per cycle; confirm this is true
4052 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004053 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004054 FastMixerStateQueue *sq = mFastMixer->sq();
4055 FastMixerState *state = sq->begin();
4056 if (state->mCommand != FastMixerState::MIX_WRITE &&
4057 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4058 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004059
4060 // FIXME workaround for first HAL write being CPU bound on some devices
4061 ATRACE_BEGIN("write");
4062 mOutput->write((char *)mSinkBuffer, 0);
4063 ATRACE_END();
4064
Eric Laurent81784c32012-11-19 14:55:58 -08004065 int32_t old = android_atomic_inc(&mFastMixerFutex);
4066 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004067 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004068 }
4069#ifdef AUDIO_WATCHDOG
4070 if (mAudioWatchdog != 0) {
4071 mAudioWatchdog->resume();
4072 }
4073#endif
4074 }
4075 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004076#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004077 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004078 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004079#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004080 sq->end();
4081 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4082 if (kUseFastMixer == FastMixer_Dynamic) {
4083 mNormalSink = mPipeSink;
4084 }
4085 } else {
4086 sq->end(false /*didModify*/);
4087 }
4088 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004089 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004090}
4091
4092void AudioFlinger::MixerThread::threadLoop_standby()
4093{
4094 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004095 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004096 FastMixerStateQueue *sq = mFastMixer->sq();
4097 FastMixerState *state = sq->begin();
4098 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004099 // Report any frames trapped in the Monopipe
4100 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4101 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4102 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4103 "monoPipeWritten:%lld monoPipeLeft:%lld",
4104 (long long)mFramesWritten, (long long)mSuspendedFrames,
4105 (long long)mPipeSink->framesWritten(), pipeFrames);
4106 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4107
Eric Laurent81784c32012-11-19 14:55:58 -08004108 state->mCommand = FastMixerState::COLD_IDLE;
4109 state->mColdFutexAddr = &mFastMixerFutex;
4110 state->mColdGen++;
4111 mFastMixerFutex = 0;
4112 sq->end();
4113 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4114 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4115 if (kUseFastMixer == FastMixer_Dynamic) {
4116 mNormalSink = mOutputSink;
4117 }
4118#ifdef AUDIO_WATCHDOG
4119 if (mAudioWatchdog != 0) {
4120 mAudioWatchdog->pause();
4121 }
4122#endif
4123 } else {
4124 sq->end(false /*didModify*/);
4125 }
4126 }
4127 PlaybackThread::threadLoop_standby();
4128}
4129
Eric Laurentbfb1b832013-01-07 09:53:42 -08004130bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4131{
4132 return false;
4133}
4134
4135bool AudioFlinger::PlaybackThread::shouldStandby_l()
4136{
4137 return !mStandby;
4138}
4139
4140bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4141{
4142 Mutex::Autolock _l(mLock);
4143 return waitingAsyncCallback_l();
4144}
4145
Eric Laurent81784c32012-11-19 14:55:58 -08004146// shared by MIXER and DIRECT, overridden by DUPLICATING
4147void AudioFlinger::PlaybackThread::threadLoop_standby()
4148{
4149 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004150 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004152 // discard any pending drain or write ack by incrementing sequence
4153 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4154 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004156 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4157 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004158 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004159 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004160}
4161
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004162void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4163{
4164 ALOGV("signal playback thread");
4165 broadcast_l();
4166}
4167
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004168void AudioFlinger::PlaybackThread::onAsyncError()
4169{
4170 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4171 invalidateTracks((audio_stream_type_t)i);
4172 }
4173}
4174
Eric Laurent81784c32012-11-19 14:55:58 -08004175void AudioFlinger::MixerThread::threadLoop_mix()
4176{
Eric Laurent81784c32012-11-19 14:55:58 -08004177 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004178 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004179 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004180 // increase sleep time progressively when application underrun condition clears.
4181 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4182 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4183 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004184 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004185 sleepTimeShift--;
4186 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004187 mSleepTimeUs = 0;
4188 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004189 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004190
Eric Laurent81784c32012-11-19 14:55:58 -08004191}
4192
4193void AudioFlinger::MixerThread::threadLoop_sleepTime()
4194{
4195 // If no tracks are ready, sleep once for the duration of an output
4196 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004197 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004198 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004199 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4200 // Using the Monopipe availableToWrite, we estimate the
4201 // sleep time to retry for more data (before we underrun).
4202 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4203 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4204 const size_t pipeFrames = monoPipe->maxFrames();
4205 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4206 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4207 const size_t framesDelay = std::min(
4208 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4209 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4210 pipeFrames, framesLeft, framesDelay);
4211 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4212 } else {
4213 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4214 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4215 mSleepTimeUs = kMinThreadSleepTimeUs;
4216 }
4217 // reduce sleep time in case of consecutive application underruns to avoid
4218 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4219 // duration we would end up writing less data than needed by the audio HAL if
4220 // the condition persists.
4221 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4222 sleepTimeShift++;
4223 }
Eric Laurent81784c32012-11-19 14:55:58 -08004224 }
4225 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004226 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004227 }
4228 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004229 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4230 // before effects processing or output.
4231 if (mMixerBufferValid) {
4232 memset(mMixerBuffer, 0, mMixerBufferSize);
4233 } else {
4234 memset(mSinkBuffer, 0, mSinkBufferSize);
4235 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004236 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004237 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4238 "anticipated start");
4239 }
4240 // TODO add standby time extension fct of effect tail
4241}
4242
4243// prepareTracks_l() must be called with ThreadBase::mLock held
4244AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4245 Vector< sp<Track> > *tracksToRemove)
4246{
Andy Hung1bc088a2018-02-09 15:57:31 -08004247 // clean up deleted track names in AudioMixer before allocating new tracks
4248 (void)mTracks.processDeletedTrackNames([this](int name) {
4249 // for each name, destroy it in the AudioMixer
4250 if (mAudioMixer->exists(name)) {
4251 mAudioMixer->destroy(name);
4252 }
4253 });
4254 mTracks.clearDeletedTrackNames();
Eric Laurent81784c32012-11-19 14:55:58 -08004255
4256 mixer_state mixerStatus = MIXER_IDLE;
4257 // find out which tracks need to be processed
4258 size_t count = mActiveTracks.size();
4259 size_t mixedTracks = 0;
4260 size_t tracksWithEffect = 0;
4261 // counts only _active_ fast tracks
4262 size_t fastTracks = 0;
4263 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4264
4265 float masterVolume = mMasterVolume;
4266 bool masterMute = mMasterMute;
4267
4268 if (masterMute) {
4269 masterVolume = 0;
4270 }
4271 // Delegate master volume control to effect in output mix effect chain if needed
4272 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4273 if (chain != 0) {
4274 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4275 chain->setVolume_l(&v, &v);
4276 masterVolume = (float)((v + (1 << 23)) >> 24);
4277 chain.clear();
4278 }
4279
4280 // prepare a new state to push
4281 FastMixerStateQueue *sq = NULL;
4282 FastMixerState *state = NULL;
4283 bool didModify = false;
4284 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004285 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004286 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004287 sq = mFastMixer->sq();
4288 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004289 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004290 }
4291
Andy Hung69aed5f2014-02-25 17:24:40 -08004292 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004293 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004294
Andy Hungbd3b2b02018-05-21 10:53:11 -07004295 // DeferredOperations handles statistics after setting mixerStatus.
4296 class DeferredOperations {
4297 public:
4298 DeferredOperations(mixer_state *mixerStatus)
4299 : mMixerStatus(mixerStatus) { }
4300
4301 // when leaving scope, tally frames properly.
4302 ~DeferredOperations() {
4303 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4304 // because that is when the underrun occurs.
4305 // We do not distinguish between FastTracks and NormalTracks here.
4306 if (*mMixerStatus == MIXER_TRACKS_READY) {
4307 for (const auto &underrun : mUnderrunFrames) {
4308 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4309 underrun.second);
4310 }
4311 }
4312 }
4313
4314 // tallyUnderrunFrames() is called to update the track counters
4315 // with the number of underrun frames for a particular mixer period.
4316 // We defer tallying until we know the final mixer status.
4317 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4318 mUnderrunFrames.emplace_back(track, underrunFrames);
4319 }
4320
4321 private:
4322 const mixer_state * const mMixerStatus;
4323 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4324 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4325
Eric Laurent81784c32012-11-19 14:55:58 -08004326 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004327 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004328
4329 // this const just means the local variable doesn't change
4330 Track* const track = t.get();
4331
4332 // process fast tracks
4333 if (track->isFastTrack()) {
4334
4335 // It's theoretically possible (though unlikely) for a fast track to be created
4336 // and then removed within the same normal mix cycle. This is not a problem, as
4337 // the track never becomes active so it's fast mixer slot is never touched.
4338 // The converse, of removing an (active) track and then creating a new track
4339 // at the identical fast mixer slot within the same normal mix cycle,
4340 // is impossible because the slot isn't marked available until the end of each cycle.
4341 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004342 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004343 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4344 FastTrack *fastTrack = &state->mFastTracks[j];
4345
4346 // Determine whether the track is currently in underrun condition,
4347 // and whether it had a recent underrun.
4348 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4349 FastTrackUnderruns underruns = ftDump->mUnderruns;
4350 uint32_t recentFull = (underruns.mBitFields.mFull -
4351 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4352 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4353 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4354 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4355 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4356 uint32_t recentUnderruns = recentPartial + recentEmpty;
4357 track->mObservedUnderruns = underruns;
4358 // don't count underruns that occur while stopping or pausing
4359 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004360 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004361 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4362 recentUnderruns > 0) {
4363 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004364 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004365 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004366 // Immediately account for FastTrack underruns.
4367 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004368
4369 // This is similar to the state machine for normal tracks,
4370 // with a few modifications for fast tracks.
4371 bool isActive = true;
4372 switch (track->mState) {
4373 case TrackBase::STOPPING_1:
4374 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004375 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004376 track->mState = TrackBase::STOPPING_2;
4377 }
4378 break;
4379 case TrackBase::PAUSING:
4380 // ramp down is not yet implemented
4381 track->setPaused();
4382 break;
4383 case TrackBase::RESUMING:
4384 // ramp up is not yet implemented
4385 track->mState = TrackBase::ACTIVE;
4386 break;
4387 case TrackBase::ACTIVE:
4388 if (recentFull > 0 || recentPartial > 0) {
4389 // track has provided at least some frames recently: reset retry count
4390 track->mRetryCount = kMaxTrackRetries;
4391 }
4392 if (recentUnderruns == 0) {
4393 // no recent underruns: stay active
4394 break;
4395 }
4396 // there has recently been an underrun of some kind
4397 if (track->sharedBuffer() == 0) {
4398 // were any of the recent underruns "empty" (no frames available)?
4399 if (recentEmpty == 0) {
4400 // no, then ignore the partial underruns as they are allowed indefinitely
4401 break;
4402 }
4403 // there has recently been an "empty" underrun: decrement the retry counter
4404 if (--(track->mRetryCount) > 0) {
4405 break;
4406 }
4407 // indicate to client process that the track was disabled because of underrun;
4408 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004409 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004410 // remove from active list, but state remains ACTIVE [confusing but true]
4411 isActive = false;
4412 break;
4413 }
4414 // fall through
4415 case TrackBase::STOPPING_2:
4416 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004417 case TrackBase::STOPPED:
4418 case TrackBase::FLUSHED: // flush() while active
4419 // Check for presentation complete if track is inactive
4420 // We have consumed all the buffers of this track.
4421 // This would be incomplete if we auto-paused on underrun
4422 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004423 uint32_t latency = 0;
4424 status_t result = mOutput->stream->getLatency(&latency);
4425 ALOGE_IF(result != OK,
4426 "Error when retrieving output stream latency: %d", result);
4427 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004428 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004429 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4430 // track stays in active list until presentation is complete
4431 break;
4432 }
4433 }
4434 if (track->isStopping_2()) {
4435 track->mState = TrackBase::STOPPED;
4436 }
4437 if (track->isStopped()) {
4438 // Can't reset directly, as fast mixer is still polling this track
4439 // track->reset();
4440 // So instead mark this track as needing to be reset after push with ack
4441 resetMask |= 1 << i;
4442 }
4443 isActive = false;
4444 break;
4445 case TrackBase::IDLE:
4446 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004447 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004448 }
4449
4450 if (isActive) {
4451 // was it previously inactive?
4452 if (!(state->mTrackMask & (1 << j))) {
4453 ExtendedAudioBufferProvider *eabp = track;
4454 VolumeProvider *vp = track;
4455 fastTrack->mBufferProvider = eabp;
4456 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004457 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004458 fastTrack->mFormat = track->mFormat;
Eric Laurent81784c32012-11-19 14:55:58 -08004459 fastTrack->mGeneration++;
4460 state->mTrackMask |= 1 << j;
4461 didModify = true;
4462 // no acknowledgement required for newly active tracks
4463 }
Kevin Rocard12381092018-04-11 09:19:59 -07004464 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004465 // cache the combined master volume and stream type volume for fast mixer; this
4466 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004467 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004468 proxy->framesReleased()).first;
4469 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004470 * mStreamTypes[track->streamType()].volume
4471 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004472 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004473 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4474 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4475 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4476 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004477 ++fastTracks;
4478 } else {
4479 // was it previously active?
4480 if (state->mTrackMask & (1 << j)) {
4481 fastTrack->mBufferProvider = NULL;
4482 fastTrack->mGeneration++;
4483 state->mTrackMask &= ~(1 << j);
4484 didModify = true;
4485 // If any fast tracks were removed, we must wait for acknowledgement
4486 // because we're about to decrement the last sp<> on those tracks.
4487 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4488 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004489 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4490 // AudioTrack may start (which may not be with a start() but with a write()
4491 // after underrun) and immediately paused or released. In that case the
4492 // FastTrack state hasn't had time to update.
4493 // TODO Remove the ALOGW when this theory is confirmed.
4494 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004495 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4496 j, track->mState, state->mTrackMask, recentUnderruns,
4497 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004498 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004499 }
4500 tracksToRemove->add(track);
4501 // Avoids a misleading display in dumpsys
4502 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4503 }
4504 continue;
4505 }
4506
4507 { // local variable scope to avoid goto warning
4508
4509 audio_track_cblk_t* cblk = track->cblk();
4510
4511 // The first time a track is added we wait
4512 // for all its buffers to be filled before processing it
4513 int name = track->name();
Andy Hung1bc088a2018-02-09 15:57:31 -08004514
4515 // if an active track doesn't exist in the AudioMixer, create it.
4516 if (!mAudioMixer->exists(name)) {
4517 status_t status = mAudioMixer->create(
4518 name,
4519 track->mChannelMask,
4520 track->mFormat,
4521 track->mSessionId);
4522 if (status != OK) {
4523 ALOGW("%s: cannot create track name"
4524 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
4525 __func__, name, track->mChannelMask, track->mFormat, track->mSessionId);
4526 tracksToRemove->add(track);
4527 track->invalidate(); // consider it dead.
4528 continue;
4529 }
4530 }
4531
Eric Laurent81784c32012-11-19 14:55:58 -08004532 // make sure that we have enough frames to mix one full buffer.
4533 // enforce this condition only once to enable draining the buffer in case the client
4534 // app does not call stop() and relies on underrun to stop:
4535 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4536 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004537 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004538 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004539 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004540
4541 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004542 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004543 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4544 // add frames already consumed but not yet released by the resampler
4545 // because mAudioTrackServerProxy->framesReady() will include these frames
4546 desiredFrames += mAudioMixer->getUnreleasedFrames(track->name());
4547
Eric Laurent81784c32012-11-19 14:55:58 -08004548 uint32_t minFrames = 1;
4549 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4550 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004551 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004552 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004553
4554 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004555 if (ATRACE_ENABLED()) {
4556 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004557 std::string traceName("nRdy");
4558 traceName += std::to_string(track->name());
4559 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004560 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004561 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004562 !track->isPaused() && !track->isTerminated())
4563 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004564 ALOGVV("track %d s=%08x [OK] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004565
4566 mixedTracks++;
4567
Andy Hung69aed5f2014-02-25 17:24:40 -08004568 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4569 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004570 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004571 if (track->mainBuffer() != mSinkBuffer &&
4572 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004573 if (mEffectBufferEnabled) {
4574 mEffectBufferValid = true; // Later can set directly.
4575 }
Eric Laurent81784c32012-11-19 14:55:58 -08004576 chain = getEffectChain_l(track->sessionId());
4577 // Delegate volume control to effect in track effect chain if needed
4578 if (chain != 0) {
4579 tracksWithEffect++;
4580 } else {
4581 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on "
4582 "session %d",
4583 name, track->sessionId());
4584 }
4585 }
4586
4587
4588 int param = AudioMixer::VOLUME;
4589 if (track->mFillingUpStatus == Track::FS_FILLED) {
4590 // no ramp for the first volume setting
4591 track->mFillingUpStatus = Track::FS_ACTIVE;
4592 if (track->mState == TrackBase::RESUMING) {
4593 track->mState = TrackBase::ACTIVE;
4594 param = AudioMixer::RAMP_VOLUME;
4595 }
4596 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004597 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004598 // FIXME should not make a decision based on mServer
4599 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004600 // If the track is stopped before the first frame was mixed,
4601 // do not apply ramp
4602 param = AudioMixer::RAMP_VOLUME;
4603 }
4604
4605 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004606 uint32_t vl, vr; // in U8.24 integer format
4607 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004608 // read original volumes with volume control
4609 float typeVolume = mStreamTypes[track->streamType()].volume;
4610 float v = masterVolume * typeVolume;
4611
Glenn Kastene4756fe2012-11-29 13:38:14 -08004612 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004613 vl = vr = 0;
4614 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004615 if (track->isPausing()) {
4616 track->setPaused();
4617 }
4618 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004619 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004620 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004621 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4622 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004623 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004624 if (vlf > GAIN_FLOAT_UNITY) {
4625 ALOGV("Track left volume out of range: %.3g", vlf);
4626 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004627 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004628 if (vrf > GAIN_FLOAT_UNITY) {
4629 ALOGV("Track right volume out of range: %.3g", vrf);
4630 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004631 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004632 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004633 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004634 // now apply the master volume and stream type volume and shaper volume
4635 vlf *= v * vh;
4636 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004637 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004638 // then derive vl and vr as U8.24 versions for the effect chain
4639 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4640 vl = (uint32_t) (scaleto8_24 * vlf);
4641 vr = (uint32_t) (scaleto8_24 * vrf);
4642 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004643 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004644 // send level comes from shared memory and so may be corrupt
4645 if (sendLevel > MAX_GAIN_INT) {
4646 ALOGV("Track send level out of range: %04X", sendLevel);
4647 sendLevel = MAX_GAIN_INT;
4648 }
Andy Hung6be49402014-05-30 10:42:03 -07004649 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4650 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004651 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004652
Kevin Rocard12381092018-04-11 09:19:59 -07004653 track->setFinalVolume((vrf + vlf) / 2.f);
4654
Eric Laurent81784c32012-11-19 14:55:58 -08004655 // Delegate volume control to effect in track effect chain if needed
4656 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4657 // Do not ramp volume if volume is controlled by effect
4658 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004659 // Update remaining floating point volume levels
4660 vlf = (float)vl / (1 << 24);
4661 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004662 track->mHasVolumeController = true;
4663 } else {
4664 // force no volume ramp when volume controller was just disabled or removed
4665 // from effect chain to avoid volume spike
4666 if (track->mHasVolumeController) {
4667 param = AudioMixer::VOLUME;
4668 }
4669 track->mHasVolumeController = false;
4670 }
4671
Eric Laurent7c29ec92017-09-20 17:54:22 -07004672 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4673 // still applied by the mixer.
4674 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4675 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4676 if (v != mLeftVolFloat) {
4677 status_t result = mOutput->stream->setVolume(v, v);
4678 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4679 if (result == OK) {
4680 mLeftVolFloat = v;
4681 }
4682 }
4683 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4684 // remove stream volume contribution from software volume.
4685 if (v != 0.0f && mLeftVolFloat == v) {
4686 vlf = min(1.0f, vlf / v);
4687 vrf = min(1.0f, vrf / v);
4688 vaf = min(1.0f, vaf / v);
4689 }
4690 }
Eric Laurent81784c32012-11-19 14:55:58 -08004691 // XXX: these things DON'T need to be done each time
4692 mAudioMixer->setBufferProvider(name, track);
4693 mAudioMixer->enable(name);
4694
Andy Hung6be49402014-05-30 10:42:03 -07004695 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
4696 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
4697 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004698 mAudioMixer->setParameter(
4699 name,
4700 AudioMixer::TRACK,
4701 AudioMixer::FORMAT, (void *)track->format());
4702 mAudioMixer->setParameter(
4703 name,
4704 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004705 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004706 mAudioMixer->setParameter(
4707 name,
4708 AudioMixer::TRACK,
4709 AudioMixer::MIXER_CHANNEL_MASK, (void *)(uintptr_t)mChannelMask);
Glenn Kastene3aa6592012-12-04 12:22:46 -08004710 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004711 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004712 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004713 if (reqSampleRate == 0) {
4714 reqSampleRate = mSampleRate;
4715 } else if (reqSampleRate > maxSampleRate) {
4716 reqSampleRate = maxSampleRate;
4717 }
Eric Laurent81784c32012-11-19 14:55:58 -08004718 mAudioMixer->setParameter(
4719 name,
4720 AudioMixer::RESAMPLE,
4721 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004722 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004723
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004724 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004725 mAudioMixer->setParameter(
4726 name,
4727 AudioMixer::TIMESTRETCH,
4728 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004729 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004730
Andy Hung69aed5f2014-02-25 17:24:40 -08004731 /*
4732 * Select the appropriate output buffer for the track.
4733 *
Andy Hung98ef9782014-03-04 14:46:50 -08004734 * Tracks with effects go into their own effects chain buffer
4735 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004736 *
4737 * Other tracks can use mMixerBuffer for higher precision
4738 * channel accumulation. If this buffer is enabled
4739 * (mMixerBufferEnabled true), then selected tracks will accumulate
4740 * into it.
4741 *
4742 */
4743 if (mMixerBufferEnabled
4744 && (track->mainBuffer() == mSinkBuffer
4745 || track->mainBuffer() == mMixerBuffer)) {
4746 mAudioMixer->setParameter(
4747 name,
4748 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004749 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004750 mAudioMixer->setParameter(
4751 name,
4752 AudioMixer::TRACK,
4753 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4754 // TODO: override track->mainBuffer()?
4755 mMixerBufferValid = true;
4756 } else {
4757 mAudioMixer->setParameter(
4758 name,
4759 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004760 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004761 mAudioMixer->setParameter(
4762 name,
4763 AudioMixer::TRACK,
4764 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4765 }
Eric Laurent81784c32012-11-19 14:55:58 -08004766 mAudioMixer->setParameter(
4767 name,
4768 AudioMixer::TRACK,
4769 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
4770
4771 // reset retry count
4772 track->mRetryCount = kMaxTrackRetries;
4773
4774 // If one track is ready, set the mixer ready if:
4775 // - the mixer was not ready during previous round OR
4776 // - no other track is not ready
4777 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4778 mixerStatus != MIXER_TRACKS_ENABLED) {
4779 mixerStatus = MIXER_TRACKS_READY;
4780 }
4781 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004782 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004783 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hung08fb1742015-05-31 23:22:10 -07004784 ALOGV("track(%p) underrun, framesReady(%zu) < framesDesired(%zd)",
4785 track, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004786 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004787 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004788 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004789
Eric Laurent81784c32012-11-19 14:55:58 -08004790 // clear effect chain input buffer if an active track underruns to avoid sending
4791 // previous audio buffer again to effects
4792 chain = getEffectChain_l(track->sessionId());
4793 if (chain != 0) {
4794 chain->clearInputBuffer();
4795 }
4796
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004797 ALOGVV("track %d s=%08x [NOT READY] on thread %p", name, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004798 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
4799 track->isStopped() || track->isPaused()) {
4800 // We have consumed all the buffers of this track.
4801 // Remove it from the list of active tracks.
4802 // TODO: use actual buffer filling status instead of latency when available from
4803 // audio HAL
4804 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004805 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004806 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
4807 if (track->isStopped()) {
4808 track->reset();
4809 }
4810 tracksToRemove->add(track);
4811 }
4812 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08004813 // No buffers for this track. Give it a few chances to
4814 // fill a buffer, then remove it from active list.
4815 if (--(track->mRetryCount) <= 0) {
Glenn Kastenc9b2e202013-02-26 11:32:32 -08004816 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004817 tracksToRemove->add(track);
4818 // indicate to client process that the track was disabled because of underrun;
4819 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004820 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004821 // If one track is not ready, mark the mixer also not ready if:
4822 // - the mixer was ready during previous round OR
4823 // - no other track is ready
4824 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
4825 mixerStatus != MIXER_TRACKS_READY) {
4826 mixerStatus = MIXER_TRACKS_ENABLED;
4827 }
4828 }
4829 mAudioMixer->disable(name);
4830 }
4831
4832 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08004833
4834 }
4835
4836 // Push the new FastMixer state if necessary
4837 bool pauseAudioWatchdog = false;
4838 if (didModify) {
4839 state->mFastTracksGen++;
4840 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
4841 if (kUseFastMixer == FastMixer_Dynamic &&
4842 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
4843 state->mCommand = FastMixerState::COLD_IDLE;
4844 state->mColdFutexAddr = &mFastMixerFutex;
4845 state->mColdGen++;
4846 mFastMixerFutex = 0;
4847 if (kUseFastMixer == FastMixer_Dynamic) {
4848 mNormalSink = mOutputSink;
4849 }
4850 // If we go into cold idle, need to wait for acknowledgement
4851 // so that fast mixer stops doing I/O.
4852 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4853 pauseAudioWatchdog = true;
4854 }
Eric Laurent81784c32012-11-19 14:55:58 -08004855 }
4856 if (sq != NULL) {
4857 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08004858 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
4859 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
4860 // when bringing the output sink into standby.)
4861 //
4862 // We will get the latest FastMixer state when we come out of COLD_IDLE.
4863 //
4864 // This occurs with BT suspend when we idle the FastMixer with
4865 // active tracks, which may be added or removed.
4866 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08004867 }
4868#ifdef AUDIO_WATCHDOG
4869 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
4870 mAudioWatchdog->pause();
4871 }
4872#endif
4873
4874 // Now perform the deferred reset on fast tracks that have stopped
4875 while (resetMask != 0) {
4876 size_t i = __builtin_ctz(resetMask);
4877 ALOG_ASSERT(i < count);
4878 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07004879 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004880 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
4881 track->reset();
4882 }
4883
Andy Hung80d03d22018-04-10 10:32:11 -07004884 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
4885 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
4886 // it ceases to be active, to allow safe removal from the AudioMixer at the start
4887 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
4888 // See also the implementation of destroyTrack_l().
4889 for (const auto &track : *tracksToRemove) {
4890 const int name = track->name();
4891 if (mAudioMixer->exists(name)) { // Normal tracks here, fast tracks in FastMixer.
4892 mAudioMixer->setBufferProvider(name, nullptr /* bufferProvider */);
4893 }
4894 }
4895
Eric Laurent81784c32012-11-19 14:55:58 -08004896 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08004897 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08004898
Eric Laurent97d547d2014-09-02 14:45:53 -07004899 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
4900 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07004901 }
4902
4903 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07004904 // as long as there are effects we should clear the effects buffer, to avoid
4905 // passing a non-clean buffer to the effect chain
4906 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07004907 }
Andy Hung69aed5f2014-02-25 17:24:40 -08004908 // sink or mix buffer must be cleared if all tracks are connected to an
4909 // effect chain as in this case the mixer will not write to the sink or mix buffer
4910 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4912 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08004913 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08004914 if (mMixerBufferValid) {
4915 memset(mMixerBuffer, 0, mMixerBufferSize);
4916 // TODO: In testing, mSinkBuffer below need not be cleared because
4917 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
4918 // after mixing.
4919 //
4920 // To enforce this guarantee:
4921 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
4922 // (mixedTracks == 0 && fastTracks > 0))
4923 // must imply MIXER_TRACKS_READY.
4924 // Later, we may clear buffers regardless, and skip much of this logic.
4925 }
Andy Hung98ef9782014-03-04 14:46:50 -08004926 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07004927 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08004928 }
4929
4930 // if any fast tracks, then status is ready
4931 mMixerStatusIgnoringFastTracks = mixerStatus;
4932 if (fastTracks > 0) {
4933 mixerStatus = MIXER_TRACKS_READY;
4934 }
4935 return mixerStatus;
4936}
4937
Eric Laurentad7dd962016-09-22 12:38:37 -07004938// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08004939uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07004940{
4941 uint32_t trackCount = 0;
4942 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08004943 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07004944 trackCount++;
4945 }
4946 }
4947 return trackCount;
4948}
4949
Andy Hung1bc088a2018-02-09 15:57:31 -08004950// isTrackAllowed_l() must be called with ThreadBase::mLock held
4951bool AudioFlinger::MixerThread::isTrackAllowed_l(
4952 audio_channel_mask_t channelMask, audio_format_t format,
4953 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08004954{
Andy Hung1bc088a2018-02-09 15:57:31 -08004955 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
4956 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07004957 }
Andy Hung1bc088a2018-02-09 15:57:31 -08004958 // Check validity as we don't call AudioMixer::create() here.
4959 if (!AudioMixer::isValidFormat(format)) {
4960 ALOGW("%s: invalid format: %#x", __func__, format);
4961 return false;
4962 }
4963 if (!AudioMixer::isValidChannelMask(channelMask)) {
4964 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
4965 return false;
4966 }
4967 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08004968}
4969
Eric Laurent10351942014-05-08 18:49:52 -07004970// checkForNewParameter_l() must be called with ThreadBase::mLock held
4971bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
4972 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08004973{
Eric Laurent81784c32012-11-19 14:55:58 -08004974 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08004975 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004976
Eric Laurent10351942014-05-08 18:49:52 -07004977 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08004978
Glenn Kastenc05b8d72016-03-24 09:48:17 -07004979 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004980
Eric Laurent10351942014-05-08 18:49:52 -07004981 AudioParameter param = AudioParameter(keyValuePair);
4982 int value;
4983 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4984 reconfig = true;
4985 }
4986 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004987 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004988 status = BAD_VALUE;
4989 } else {
4990 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08004991 reconfig = true;
4992 }
Eric Laurent10351942014-05-08 18:49:52 -07004993 }
4994 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07004995 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07004996 status = BAD_VALUE;
4997 } else {
4998 // no need to save value, since it's constant
4999 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005000 }
Eric Laurent10351942014-05-08 18:49:52 -07005001 }
5002 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5003 // do not accept frame count changes if tracks are open as the track buffer
5004 // size depends on frame count and correct behavior would not be guaranteed
5005 // if frame count is changed after track creation
5006 if (!mTracks.isEmpty()) {
5007 status = INVALID_OPERATION;
5008 } else {
5009 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005010 }
Eric Laurent10351942014-05-08 18:49:52 -07005011 }
5012 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005013#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005014 // when changing the audio output device, call addBatteryData to notify
5015 // the change
5016 if (mOutDevice != value) {
5017 uint32_t params = 0;
5018 // check whether speaker is on
5019 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5020 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005021 }
Eric Laurent10351942014-05-08 18:49:52 -07005022
5023 audio_devices_t deviceWithoutSpeaker
5024 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5025 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005026 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005027 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5028 }
5029
5030 if (params != 0) {
5031 addBatteryData(params);
5032 }
5033 }
Eric Laurent81784c32012-11-19 14:55:58 -08005034#endif
5035
Eric Laurent10351942014-05-08 18:49:52 -07005036 // forward device change to effects that have requested to be
5037 // aware of attached audio device.
5038 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005039 a2dpDeviceChanged =
5040 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005041 mOutDevice = value;
5042 for (size_t i = 0; i < mEffectChains.size(); i++) {
5043 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005044 }
5045 }
Eric Laurent10351942014-05-08 18:49:52 -07005046 }
Eric Laurent81784c32012-11-19 14:55:58 -08005047
Eric Laurent10351942014-05-08 18:49:52 -07005048 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005049 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005050 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005051 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005052 mStandby = true;
5053 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005054 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005055 }
Eric Laurent10351942014-05-08 18:49:52 -07005056 if (status == NO_ERROR && reconfig) {
5057 readOutputParameters_l();
5058 delete mAudioMixer;
5059 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005060 for (const auto &track : mTracks) {
5061 const int name = track->name();
5062 status_t status = mAudioMixer->create(
5063 name,
5064 track->mChannelMask,
5065 track->mFormat,
5066 track->mSessionId);
5067 ALOGW_IF(status != NO_ERROR,
5068 "%s: cannot create track name"
5069 " %d, mask %#x, format %#x, sessionId %d in AudioMixer",
5070 __func__,
5071 name, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005072 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005073 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005074 }
Eric Laurent81784c32012-11-19 14:55:58 -08005075 }
5076
Eric Laurent42537be2016-01-08 17:16:42 -08005077 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005078}
5079
5080
5081void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5082{
Eric Laurent81784c32012-11-19 14:55:58 -08005083 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005084 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005085 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005086 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005087 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005088 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005089 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005090 } else {
5091 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005092 }
Eric Laurent81784c32012-11-19 14:55:58 -08005093
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005094 if (hasFastMixer()) {
5095 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5096
5097 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5098 // while we are dumping it. It may be inconsistent, but it won't mutate!
5099 // This is a large object so we place it on the heap.
5100 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
5101 const FastMixerDumpState *copy = new FastMixerDumpState(mFastMixerDumpState);
5102 copy->dump(fd);
5103 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08005104
5105#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005106 // Similar for state queue
5107 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5108 observerCopy.dump(fd);
5109 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5110 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005111#endif
5112
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005113#ifdef AUDIO_WATCHDOG
5114 if (mAudioWatchdog != 0) {
5115 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5116 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5117 wdCopy.dump(fd);
5118 }
5119#endif
5120
5121 } else {
5122 dprintf(fd, " No FastMixer\n");
5123 }
Eric Laurent81784c32012-11-19 14:55:58 -08005124}
5125
5126uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5127{
5128 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5129}
5130
5131uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5132{
5133 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5134}
5135
5136void AudioFlinger::MixerThread::cacheParameters_l()
5137{
5138 PlaybackThread::cacheParameters_l();
5139
5140 // FIXME: Relaxed timing because of a certain device that can't meet latency
5141 // Should be reduced to 2x after the vendor fixes the driver issue
5142 // increase threshold again due to low power audio mode. The way this warning
5143 // threshold is calculated and its usefulness should be reconsidered anyway.
5144 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5145}
5146
5147// ----------------------------------------------------------------------------
5148
5149AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005150 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device, bool systemReady)
5151 : PlaybackThread(audioFlinger, output, id, device, DIRECT, systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08005152{
5153}
5154
Eric Laurentbfb1b832013-01-07 09:53:42 -08005155AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
5156 AudioStreamOut* output, audio_io_handle_t id, uint32_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005157 ThreadBase::type_t type, bool systemReady)
5158 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Andy Hung10cbff12017-02-21 17:30:14 -08005159 , mVolumeShaperActive(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005160{
5161}
5162
Eric Laurent81784c32012-11-19 14:55:58 -08005163AudioFlinger::DirectOutputThread::~DirectOutputThread()
5164{
5165}
5166
Eric Laurent5850c4c2016-11-10 13:04:31 -08005167void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005168{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005169 float left, right;
5170
5171 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5172 left = right = 0;
5173 } else {
5174 float typeVolume = mStreamTypes[track->streamType()].volume;
5175 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005176 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005177
Andy Hung10cbff12017-02-21 17:30:14 -08005178 // Get volumeshaper scaling
5179 std::pair<float /* volume */, bool /* active */>
5180 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005181 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005182 v *= vh.first;
5183 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005184
Glenn Kastenc56f3422014-03-21 17:53:17 -07005185 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5186 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5187 if (left > GAIN_FLOAT_UNITY) {
5188 left = GAIN_FLOAT_UNITY;
5189 }
5190 left *= v;
5191 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5192 if (right > GAIN_FLOAT_UNITY) {
5193 right = GAIN_FLOAT_UNITY;
5194 }
5195 right *= v;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005196 }
5197
5198 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005199 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005200 if (left != mLeftVolFloat || right != mRightVolFloat) {
5201 mLeftVolFloat = left;
5202 mRightVolFloat = right;
5203
5204 // Convert volumes from float to 8.24
5205 uint32_t vl = (uint32_t)(left * (1 << 24));
5206 uint32_t vr = (uint32_t)(right * (1 << 24));
5207
5208 // Delegate volume control to effect in track effect chain if needed
5209 // only one effect chain can be present on DirectOutputThread, so if
5210 // there is one, the track is connected to it
5211 if (!mEffectChains.isEmpty()) {
5212 mEffectChains[0]->setVolume_l(&vl, &vr);
5213 left = (float)vl / (1 << 24);
5214 right = (float)vr / (1 << 24);
5215 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005216 status_t result = mOutput->stream->setVolume(left, right);
5217 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005218 }
5219 }
5220}
5221
Phil Burk43b4dcc2015-06-09 16:53:44 -07005222void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5223{
5224 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005225 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005226
Eric Laurent0f0631e2015-07-06 18:01:25 -07005227 if (previousTrack != 0 && latestTrack != 0) {
5228 if (mType == DIRECT) {
5229 if (previousTrack.get() != latestTrack.get()) {
5230 mFlushPending = true;
5231 }
5232 } else /* mType == OFFLOAD */ {
5233 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5234 mFlushPending = true;
5235 }
5236 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005237 }
5238 PlaybackThread::onAddNewTrack_l();
5239}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005240
Eric Laurent81784c32012-11-19 14:55:58 -08005241AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5242 Vector< sp<Track> > *tracksToRemove
5243)
5244{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005245 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005246 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005247 bool doHwPause = false;
5248 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005249
5250 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005251 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005252 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005253 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005254 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005255 continue;
5256 }
5257
Eric Laurent5850c4c2016-11-10 13:04:31 -08005258 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005259#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005260 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005261#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005262 // Only consider last track started for volume and mixer state control.
5263 // In theory an older track could underrun and restart after the new one starts
5264 // but as we only care about the transition phase between two tracks on a
5265 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005266 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005267 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005268
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005269 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005270 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005271 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005272 doHwPause = true;
5273 mHwPaused = true;
5274 }
5275 tracksToRemove->add(track);
5276 } else if (track->isFlushPending()) {
5277 track->flushAck();
5278 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005279 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005280 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005281 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005282 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005283 if (last) {
5284 mLeftVolFloat = mRightVolFloat = -1.0;
5285 if (mHwPaused) {
5286 doHwResume = true;
5287 mHwPaused = false;
5288 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005289 }
5290 }
5291
Eric Laurent81784c32012-11-19 14:55:58 -08005292 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005293 // for all its buffers to be filled before processing it.
5294 // Allow draining the buffer in case the client
5295 // app does not call stop() and relies on underrun to stop:
5296 // hence the test on (track->mRetryCount > 1).
5297 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005298 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005299 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005300 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005301 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005302 minFrames = mNormalFrameCount;
5303 } else {
5304 minFrames = 1;
5305 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306
Eric Laurentab5cdba2014-06-09 17:22:27 -07005307 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5308 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005309 {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005310 ALOGVV("track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005311
5312 if (track->mFillingUpStatus == Track::FS_FILLED) {
5313 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005314 if (last) {
5315 // make sure processVolume_l() will apply new volume even if 0
5316 mLeftVolFloat = mRightVolFloat = -1.0;
5317 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005318 if (!mHwSupportsPause) {
5319 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005320 }
5321 }
5322
5323 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005324 processVolume_l(track, last);
5325 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005326 sp<Track> previousTrack = mPreviousTrack.promote();
5327 if (previousTrack != 0) {
5328 if (track != previousTrack.get()) {
5329 // Flush any data still being written from last track
5330 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005331 // Invalidate previous track to force a seek when resuming.
5332 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005333 }
5334 }
5335 mPreviousTrack = track;
5336
Eric Laurentd595b7c2013-04-03 17:27:56 -07005337 // reset retry count
5338 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005339 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005340 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005341 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005342 doHwResume = true;
5343 mHwPaused = false;
5344 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005345 }
Eric Laurent81784c32012-11-19 14:55:58 -08005346 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005347 // clear effect chain input buffer if the last active track started underruns
5348 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005349 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005350 mEffectChains[0]->clearInputBuffer();
5351 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005352 if (track->isStopping_1()) {
5353 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005354 if (last && mHwPaused) {
5355 doHwResume = true;
5356 mHwPaused = false;
5357 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005358 }
5359 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5360 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005361 // We have consumed all the buffers of this track.
5362 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005363 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005364 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005365 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5366 } else {
5367 audioHALFrames = 0;
5368 }
5369
Andy Hung818e7a32016-02-16 18:08:07 -08005370 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005371 if (mStandby || !last ||
5372 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005373 if (track->isStopping_2()) {
5374 track->mState = TrackBase::STOPPED;
5375 }
Eric Laurent81784c32012-11-19 14:55:58 -08005376 if (track->isStopped()) {
5377 track->reset();
5378 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005379 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005380 }
5381 } else {
5382 // No buffers for this track. Give it a few chances to
5383 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005384 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005385 if (--(track->mRetryCount) <= 0) {
5386 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005387 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005388 // indicate to client process that the track was disabled because of underrun;
5389 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005390 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005391 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005392 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5393 "minFrames = %u, mFormat = %#x",
5394 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005395 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005396 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005397 doHwPause = true;
5398 mHwPaused = true;
5399 }
Eric Laurent81784c32012-11-19 14:55:58 -08005400 }
5401 }
5402 }
5403 }
5404
Eric Laurentd1f69b02014-12-15 14:33:13 -08005405 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005406 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005407 for (size_t i = 0; i < mTracks.size(); i++) {
5408 if (mTracks[i]->isFlushPending()) {
5409 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005410 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005411 }
5412 }
5413 }
5414
5415 // make sure the pause/flush/resume sequence is executed in the right order.
5416 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5417 // before flush and then resume HW. This can happen in case of pause/flush/resume
5418 // if resume is received before pause is executed.
5419 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005420 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005421 status_t result = mOutput->stream->pause();
5422 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005423 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005424 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005425 flushHw_l();
5426 }
5427 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005428 status_t result = mOutput->stream->resume();
5429 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005430 }
Eric Laurent81784c32012-11-19 14:55:58 -08005431 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005433
5434 return mixerStatus;
5435}
5436
5437void AudioFlinger::DirectOutputThread::threadLoop_mix()
5438{
Eric Laurent81784c32012-11-19 14:55:58 -08005439 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005440 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005441 // output audio to hardware
5442 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005443 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005444 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005445 status_t status = mActiveTrack->getNextBuffer(&buffer);
5446 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005447 // no need to pad with 0 for compressed audio
5448 if (audio_has_proportional_frames(mFormat)) {
5449 memset(curBuf, 0, frameCount * mFrameSize);
5450 }
Eric Laurent81784c32012-11-19 14:55:58 -08005451 break;
5452 }
5453 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5454 frameCount -= buffer.frameCount;
5455 curBuf += buffer.frameCount * mFrameSize;
5456 mActiveTrack->releaseBuffer(&buffer);
5457 }
Andy Hung2098f272014-02-27 14:00:06 -08005458 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005459 mSleepTimeUs = 0;
5460 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005461 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005462}
5463
5464void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5465{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005466 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005467 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005468 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005469 return;
5470 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005471 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005472 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005473 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005474 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005475 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005476 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005477 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005478 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005479 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005480 }
5481}
5482
Eric Laurentd1f69b02014-12-15 14:33:13 -08005483void AudioFlinger::DirectOutputThread::threadLoop_exit()
5484{
5485 {
5486 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005487 for (size_t i = 0; i < mTracks.size(); i++) {
5488 if (mTracks[i]->isFlushPending()) {
5489 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005490 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005491 }
5492 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005493 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005494 flushHw_l();
5495 }
5496 }
5497 PlaybackThread::threadLoop_exit();
5498}
5499
5500// must be called with thread mutex locked
5501bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5502{
5503 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005504 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005505
vivek mehta9cd7ad12016-03-17 00:18:29 -07005506 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5507 return !mStandby;
5508 }
5509
Eric Laurentd1f69b02014-12-15 14:33:13 -08005510 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5511 // after a timeout and we will enter standby then.
5512 if (mTracks.size() > 0) {
5513 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005514 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5515 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005516 }
5517
Eric Laurent5cff4032015-05-26 13:49:58 -07005518 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005519}
5520
Eric Laurent10351942014-05-08 18:49:52 -07005521// checkForNewParameter_l() must be called with ThreadBase::mLock held
5522bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5523 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005524{
5525 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005526 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005527
Eric Laurent10351942014-05-08 18:49:52 -07005528 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005529
Eric Laurent10351942014-05-08 18:49:52 -07005530 AudioParameter param = AudioParameter(keyValuePair);
5531 int value;
5532 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5533 // forward device change to effects that have requested to be
5534 // aware of attached audio device.
5535 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005536 a2dpDeviceChanged =
5537 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005538 mOutDevice = value;
5539 for (size_t i = 0; i < mEffectChains.size(); i++) {
5540 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005541 }
5542 }
Eric Laurent81784c32012-11-19 14:55:58 -08005543 }
Eric Laurent10351942014-05-08 18:49:52 -07005544 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5545 // do not accept frame count changes if tracks are open as the track buffer
5546 // size depends on frame count and correct behavior would not be garantied
5547 // if frame count is changed after track creation
5548 if (!mTracks.isEmpty()) {
5549 status = INVALID_OPERATION;
5550 } else {
5551 reconfig = true;
5552 }
5553 }
5554 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005555 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005556 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005557 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005558 mStandby = true;
5559 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005560 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005561 }
5562 if (status == NO_ERROR && reconfig) {
5563 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005564 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005565 }
5566 }
5567
Eric Laurent42537be2016-01-08 17:16:42 -08005568 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005569}
5570
5571uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5572{
5573 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005574 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005575 time = PlaybackThread::activeSleepTimeUs();
5576 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005577 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005578 }
5579 return time;
5580}
5581
5582uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5583{
5584 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005585 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005586 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5587 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005588 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005589 }
5590 return time;
5591}
5592
5593uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5594{
5595 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005596 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005597 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5598 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005599 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005600 }
5601 return time;
5602}
5603
5604void AudioFlinger::DirectOutputThread::cacheParameters_l()
5605{
5606 PlaybackThread::cacheParameters_l();
5607
5608 // use shorter standby delay as on normal output to release
5609 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005610 // no delay on outputs with HW A/V sync
5611 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005612 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005613 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005614 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005615 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005616 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005617 }
Eric Laurent81784c32012-11-19 14:55:58 -08005618}
5619
Eric Laurente659ef42014-09-29 13:06:46 -07005620void AudioFlinger::DirectOutputThread::flushHw_l()
5621{
Phil Burk062e67a2015-02-11 13:40:50 -08005622 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005623 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005624 mFlushPending = false;
Eric Laurente659ef42014-09-29 13:06:46 -07005625}
5626
Andy Hung10cbff12017-02-21 17:30:14 -08005627int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5628 // If a VolumeShaper is active, we must wake up periodically to update volume.
5629 const int64_t NS_PER_MS = 1000000;
5630 return mVolumeShaperActive ?
5631 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5632}
5633
Eric Laurent81784c32012-11-19 14:55:58 -08005634// ----------------------------------------------------------------------------
5635
Eric Laurentbfb1b832013-01-07 09:53:42 -08005636AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005637 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005638 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005639 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005640 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005641 mDrainSequence(0),
5642 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005643{
5644}
5645
5646AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5647{
5648}
5649
5650void AudioFlinger::AsyncCallbackThread::onFirstRef()
5651{
5652 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5653}
5654
5655bool AudioFlinger::AsyncCallbackThread::threadLoop()
5656{
5657 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005658 uint32_t writeAckSequence;
5659 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005660 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005661
5662 {
5663 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005664 while (!((mWriteAckSequence & 1) ||
5665 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005666 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005667 exitPending())) {
5668 mWaitWorkCV.wait(mLock);
5669 }
5670
Eric Laurentbfb1b832013-01-07 09:53:42 -08005671 if (exitPending()) {
5672 break;
5673 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005674 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5675 mWriteAckSequence, mDrainSequence);
5676 writeAckSequence = mWriteAckSequence;
5677 mWriteAckSequence &= ~1;
5678 drainSequence = mDrainSequence;
5679 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005680 asyncError = mAsyncError;
5681 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005682 }
5683 {
Eric Laurent4de95592013-09-26 15:28:21 -07005684 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5685 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005686 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005687 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005688 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005689 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005690 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005691 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005692 if (asyncError) {
5693 playbackThread->onAsyncError();
5694 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005695 }
5696 }
5697 }
5698 return false;
5699}
5700
5701void AudioFlinger::AsyncCallbackThread::exit()
5702{
5703 ALOGV("AsyncCallbackThread::exit");
5704 Mutex::Autolock _l(mLock);
5705 requestExit();
5706 mWaitWorkCV.broadcast();
5707}
5708
Eric Laurent3b4529e2013-09-05 18:09:19 -07005709void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005710{
5711 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005712 // bit 0 is cleared
5713 mWriteAckSequence = sequence << 1;
5714}
5715
5716void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5717{
5718 Mutex::Autolock _l(mLock);
5719 // ignore unexpected callbacks
5720 if (mWriteAckSequence & 2) {
5721 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005722 mWaitWorkCV.signal();
5723 }
5724}
5725
Eric Laurent3b4529e2013-09-05 18:09:19 -07005726void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005727{
5728 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005729 // bit 0 is cleared
5730 mDrainSequence = sequence << 1;
5731}
5732
5733void AudioFlinger::AsyncCallbackThread::resetDraining()
5734{
5735 Mutex::Autolock _l(mLock);
5736 // ignore unexpected callbacks
5737 if (mDrainSequence & 2) {
5738 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005739 mWaitWorkCV.signal();
5740 }
5741}
5742
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005743void AudioFlinger::AsyncCallbackThread::setAsyncError()
5744{
5745 Mutex::Autolock _l(mLock);
5746 mAsyncError = true;
5747 mWaitWorkCV.signal();
5748}
5749
Eric Laurentbfb1b832013-01-07 09:53:42 -08005750
5751// ----------------------------------------------------------------------------
5752AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005753 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5754 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005755 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5756 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005757{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005758 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005759 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005760 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005761}
5762
Eric Laurentbfb1b832013-01-07 09:53:42 -08005763void AudioFlinger::OffloadThread::threadLoop_exit()
5764{
5765 if (mFlushPending || mHwPaused) {
5766 // If a flush is pending or track was paused, just discard buffered data
5767 flushHw_l();
5768 } else {
5769 mMixerStatus = MIXER_DRAIN_ALL;
5770 threadLoop_drain();
5771 }
Uday Gupta56604aa2014-05-13 11:19:17 -07005772 if (mUseAsyncWrite) {
5773 ALOG_ASSERT(mCallbackThread != 0);
5774 mCallbackThread->exit();
5775 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005776 PlaybackThread::threadLoop_exit();
5777}
5778
5779AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
5780 Vector< sp<Track> > *tracksToRemove
5781)
5782{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005783 size_t count = mActiveTracks.size();
5784
5785 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07005786 bool doHwPause = false;
5787 bool doHwResume = false;
5788
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005789 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07005790
Eric Laurentbfb1b832013-01-07 09:53:42 -08005791 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005792 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005793 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005794#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08005795 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005796#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005797 // Only consider last track started for volume and mixer state control.
5798 // In theory an older track could underrun and restart after the new one starts
5799 // but as we only care about the transition phase between two tracks on a
5800 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005801 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005802 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07005803
Haynes Mathew George7844f672014-01-15 12:32:55 -08005804 if (track->isInvalid()) {
5805 ALOGW("An invalidated track shouldn't be in active list");
5806 tracksToRemove->add(track);
5807 continue;
5808 }
5809
5810 if (track->mState == TrackBase::IDLE) {
5811 ALOGW("An idle track shouldn't be in active list");
5812 continue;
5813 }
5814
Eric Laurentbfb1b832013-01-07 09:53:42 -08005815 if (track->isPausing()) {
5816 track->setPaused();
5817 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07005818 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07005819 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005820 mHwPaused = true;
5821 }
5822 // If we were part way through writing the mixbuffer to
5823 // the HAL we must save this until we resume
5824 // BUG - this will be wrong if a different track is made active,
5825 // in that case we want to discard the pending data in the
5826 // mixbuffer and tell the client to present it again when the
5827 // track is resumed
5828 mPausedWriteLength = mCurrentWriteLength;
5829 mPausedBytesRemaining = mBytesRemaining;
5830 mBytesRemaining = 0; // stop writing
5831 }
5832 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08005833 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005834 if (track->isStopping_1()) {
5835 track->mRetryCount = kMaxTrackStopRetriesOffload;
5836 } else {
5837 track->mRetryCount = kMaxTrackRetriesOffload;
5838 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08005839 track->flushAck();
5840 if (last) {
5841 mFlushPending = true;
5842 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005843 } else if (track->isResumePending()){
5844 track->resumeAck();
5845 if (last) {
5846 if (mPausedBytesRemaining) {
5847 // Need to continue write that was interrupted
5848 mCurrentWriteLength = mPausedWriteLength;
5849 mBytesRemaining = mPausedBytesRemaining;
5850 mPausedBytesRemaining = 0;
5851 }
5852 if (mHwPaused) {
5853 doHwResume = true;
5854 mHwPaused = false;
5855 // threadLoop_mix() will handle the case that we need to
5856 // resume an interrupted write
5857 }
5858 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005859 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005860
Eric Laurent3df841a2016-07-15 15:15:40 -07005861 mLeftVolFloat = mRightVolFloat = -1.0;
5862
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08005863 // Do not handle new data in this iteration even if track->framesReady()
5864 mixerStatus = MIXER_TRACKS_ENABLED;
5865 }
5866 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07005867 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005868 ALOGVV("OffloadThread: track %d s=%08x [OK]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005869 if (track->mFillingUpStatus == Track::FS_FILLED) {
5870 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005871 if (last) {
5872 // make sure processVolume_l() will apply new volume even if 0
5873 mLeftVolFloat = mRightVolFloat = -1.0;
5874 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005875 }
5876
5877 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08005878 sp<Track> previousTrack = mPreviousTrack.promote();
5879 if (previousTrack != 0) {
5880 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08005881 // Flush any data still being written from last track
5882 mBytesRemaining = 0;
5883 if (mPausedBytesRemaining) {
5884 // Last track was paused so we also need to flush saved
5885 // mixbuffer state and invalidate track so that it will
5886 // re-submit that unwritten data when it is next resumed
5887 mPausedBytesRemaining = 0;
5888 // Invalidate is a bit drastic - would be more efficient
5889 // to have a flag to tell client that some of the
5890 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08005891 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005892 }
5893 // flush data already sent to the DSP if changing audio session as audio
5894 // comes from a different source. Also invalidate previous track to force a
5895 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08005896 if (previousTrack->sessionId() != track->sessionId()) {
5897 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08005898 }
5899 }
5900 }
5901 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005902 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07005903 if (track->isStopping_1()) {
5904 track->mRetryCount = kMaxTrackStopRetriesOffload;
5905 } else {
5906 track->mRetryCount = kMaxTrackRetriesOffload;
5907 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08005908 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005909 mixerStatus = MIXER_TRACKS_READY;
5910 }
5911 } else {
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005912 ALOGVV("OffloadThread: track %d s=%08x [NOT READY]", track->name(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005913 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07005914 if (--(track->mRetryCount) <= 0) {
5915 // Hardware buffer can hold a large amount of audio so we must
5916 // wait for all current track's data to drain before we say
5917 // that the track is stopped.
5918 if (mBytesRemaining == 0) {
5919 // Only start draining when all data in mixbuffer
5920 // has been written
5921 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
5922 track->mState = TrackBase::STOPPING_2; // so presentation completes after
5923 // drain do not drain if no data was ever sent to HAL (mStandby == true)
5924 if (last && !mStandby) {
5925 // do not modify drain sequence if we are already draining. This happens
5926 // when resuming from pause after drain.
5927 if ((mDrainSequence & 1) == 0) {
5928 mSleepTimeUs = 0;
5929 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
5930 mixerStatus = MIXER_DRAIN_TRACK;
5931 mDrainSequence += 2;
5932 }
5933 if (mHwPaused) {
5934 // It is possible to move from PAUSED to STOPPING_1 without
5935 // a resume so we must ensure hardware is running
5936 doHwResume = true;
5937 mHwPaused = false;
5938 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005939 }
5940 }
Eric Laurente93cc032016-05-05 10:15:10 -07005941 } else if (last) {
5942 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
5943 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005944 }
5945 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07005946 // Drain has completed or we are in standby, signal presentation complete
5947 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005948 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005949 uint32_t latency = 0;
5950 status_t result = mOutput->stream->getLatency(&latency);
5951 ALOGE_IF(result != OK,
5952 "Error when retrieving output stream latency: %d", result);
5953 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005954 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08005955 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005956 track->presentationComplete(framesWritten, audioHALFrames);
5957 track->reset();
5958 tracksToRemove->add(track);
5959 }
5960 } else {
5961 // No buffers for this track. Give it a few chances to
5962 // fill a buffer, then remove it from active list.
5963 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07005964 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005965 uint64_t position = 0;
5966 struct timespec unused;
5967 // The running check restarts the retry counter at least once.
5968 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
5969 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
5970 running = true;
5971 mOffloadUnderrunPosition = position;
5972 }
5973 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07005974 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
5975 (long long)position, (long long)mOffloadUnderrunPosition);
5976 }
5977 if (running) { // still running, give us more time.
5978 track->mRetryCount = kMaxTrackRetriesOffload;
5979 } else {
5980 ALOGV("OffloadThread: BUFFER TIMEOUT: remove(%d) from active list",
5981 track->name());
5982 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08005983 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07005984 // it will then automatically call start() when data is available
5985 track->disable();
5986 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005987 } else if (last){
5988 mixerStatus = MIXER_TRACKS_ENABLED;
5989 }
5990 }
5991 }
5992 // compute volume for this track
5993 processVolume_l(track, last);
5994 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07005995
Eric Laurentea0fade2013-10-04 16:23:48 -07005996 // make sure the pause/flush/resume sequence is executed in the right order.
5997 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5998 // before flush and then resume HW. This can happen in case of pause/flush/resume
5999 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006000 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006001 status_t result = mOutput->stream->pause();
6002 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006003 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006004 if (mFlushPending) {
6005 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006006 }
Eric Laurentfd477972013-10-25 18:10:40 -07006007 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006008 status_t result = mOutput->stream->resume();
6009 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006010 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006011
Eric Laurentbfb1b832013-01-07 09:53:42 -08006012 // remove all the tracks that need to be...
6013 removeTracks_l(*tracksToRemove);
6014
6015 return mixerStatus;
6016}
6017
Eric Laurentbfb1b832013-01-07 09:53:42 -08006018// must be called with thread mutex locked
6019bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6020{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006021 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6022 mWriteAckSequence, mDrainSequence);
6023 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006024 return true;
6025 }
6026 return false;
6027}
6028
Eric Laurentbfb1b832013-01-07 09:53:42 -08006029bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6030{
6031 Mutex::Autolock _l(mLock);
6032 return waitingAsyncCallback_l();
6033}
6034
6035void AudioFlinger::OffloadThread::flushHw_l()
6036{
Eric Laurente659ef42014-09-29 13:06:46 -07006037 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006038 // Flush anything still waiting in the mixbuffer
6039 mCurrentWriteLength = 0;
6040 mBytesRemaining = 0;
6041 mPausedWriteLength = 0;
6042 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006043 // reset bytes written count to reflect that DSP buffers are empty after flush.
6044 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006045 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006046
Eric Laurentbfb1b832013-01-07 09:53:42 -08006047 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006048 // discard any pending drain or write ack by incrementing sequence
6049 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6050 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006051 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006052 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6053 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006054 }
6055}
6056
Haynes Mathew George05317d22016-05-03 16:34:26 -07006057void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6058{
6059 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006060 if (PlaybackThread::invalidateTracks_l(streamType)) {
6061 mFlushPending = true;
6062 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006063}
6064
Eric Laurentbfb1b832013-01-07 09:53:42 -08006065// ----------------------------------------------------------------------------
6066
Eric Laurent81784c32012-11-19 14:55:58 -08006067AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006068 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006069 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006070 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006071 mWaitTimeMs(UINT_MAX)
6072{
6073 addOutputTrack(mainThread);
6074}
6075
6076AudioFlinger::DuplicatingThread::~DuplicatingThread()
6077{
6078 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6079 mOutputTracks[i]->destroy();
6080 }
6081}
6082
6083void AudioFlinger::DuplicatingThread::threadLoop_mix()
6084{
6085 // mix buffers...
6086 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006087 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006088 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006089 if (mMixerBufferValid) {
6090 memset(mMixerBuffer, 0, mMixerBufferSize);
6091 } else {
6092 memset(mSinkBuffer, 0, mSinkBufferSize);
6093 }
Eric Laurent81784c32012-11-19 14:55:58 -08006094 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006095 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006096 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006097 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006098 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006099}
6100
6101void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6102{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006103 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006104 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006105 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006106 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006107 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006108 }
6109 } else if (mBytesWritten != 0) {
6110 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6111 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006112 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006113 } else {
6114 // flush remaining overflow buffers in output tracks
6115 writeFrames = 0;
6116 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006117 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006118 }
6119}
6120
Eric Laurentbfb1b832013-01-07 09:53:42 -08006121ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006122{
6123 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006124 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6125
6126 // Consider the first OutputTrack for timestamp and frame counting.
6127
6128 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6129 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6130 // we always claim success.
6131 if (i == 0) {
6132 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6133 ALOGD_IF(correction != 0 && writeFrames != 0,
6134 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6135 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6136 mFramesWritten -= correction;
6137 }
6138
6139 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006140 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006141 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006142 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006143}
6144
6145void AudioFlinger::DuplicatingThread::threadLoop_standby()
6146{
6147 // DuplicatingThread implements standby by stopping all tracks
6148 for (size_t i = 0; i < outputTracks.size(); i++) {
6149 outputTracks[i]->stop();
6150 }
6151}
6152
Andy Hung1bc088a2018-02-09 15:57:31 -08006153void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6154{
6155 MixerThread::dumpInternals(fd, args);
6156
6157 std::stringstream ss;
6158 const size_t numTracks = mOutputTracks.size();
6159 ss << " " << numTracks << " OutputTracks";
6160 if (numTracks > 0) {
6161 ss << ":";
6162 for (const auto &track : mOutputTracks) {
6163 const sp<ThreadBase> thread = track->thread().promote();
6164 ss << " (" << track->name() << " : ";
6165 if (thread.get() != nullptr) {
6166 ss << thread.get() << ", " << thread->id();
6167 } else {
6168 ss << "null";
6169 }
6170 ss << ")";
6171 }
6172 }
6173 ss << "\n";
6174 std::string result = ss.str();
6175 write(fd, result.c_str(), result.size());
6176}
6177
Eric Laurent81784c32012-11-19 14:55:58 -08006178void AudioFlinger::DuplicatingThread::saveOutputTracks()
6179{
6180 outputTracks = mOutputTracks;
6181}
6182
6183void AudioFlinger::DuplicatingThread::clearOutputTracks()
6184{
6185 outputTracks.clear();
6186}
6187
6188void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6189{
6190 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006191 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6192 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6193 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6194 const size_t frameCount =
6195 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6196 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6197 // from different OutputTracks and their associated MixerThreads (e.g. one may
6198 // nearly empty and the other may be dropping data).
6199
6200 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006201 this,
6202 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006203 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006204 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006205 frameCount,
6206 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006207 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6208 if (status != NO_ERROR) {
6209 ALOGE("addOutputTrack() initCheck failed %d", status);
6210 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006211 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006212 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6213 mOutputTracks.add(outputTrack);
6214 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6215 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006216}
6217
6218void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6219{
6220 Mutex::Autolock _l(mLock);
6221 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6222 if (mOutputTracks[i]->thread() == thread) {
6223 mOutputTracks[i]->destroy();
6224 mOutputTracks.removeAt(i);
6225 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006226 if (thread->getOutput() == mOutput) {
6227 mOutput = NULL;
6228 }
Eric Laurent81784c32012-11-19 14:55:58 -08006229 return;
6230 }
6231 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006232 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006233}
6234
6235// caller must hold mLock
6236void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6237{
6238 mWaitTimeMs = UINT_MAX;
6239 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6240 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6241 if (strong != 0) {
6242 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6243 if (waitTimeMs < mWaitTimeMs) {
6244 mWaitTimeMs = waitTimeMs;
6245 }
6246 }
6247 }
6248}
6249
6250
6251bool AudioFlinger::DuplicatingThread::outputsReady(
6252 const SortedVector< sp<OutputTrack> > &outputTracks)
6253{
6254 for (size_t i = 0; i < outputTracks.size(); i++) {
6255 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6256 if (thread == 0) {
6257 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6258 outputTracks[i].get());
6259 return false;
6260 }
6261 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6262 // see note at standby() declaration
6263 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6264 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6265 thread.get());
6266 return false;
6267 }
6268 }
6269 return true;
6270}
6271
Kevin Rocard12381092018-04-11 09:19:59 -07006272void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6273 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006274{
Kevin Rocard12381092018-04-11 09:19:59 -07006275 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6276 outputTrack->setMetadatas(metadata.tracks);
6277 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006278}
6279
Eric Laurent81784c32012-11-19 14:55:58 -08006280uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6281{
6282 return (mWaitTimeMs * 1000) / 2;
6283}
6284
6285void AudioFlinger::DuplicatingThread::cacheParameters_l()
6286{
6287 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6288 updateWaitTime_l();
6289
6290 MixerThread::cacheParameters_l();
6291}
6292
Eric Laurent6acd1d42017-01-04 14:23:29 -08006293
Eric Laurent81784c32012-11-19 14:55:58 -08006294// ----------------------------------------------------------------------------
6295// Record
6296// ----------------------------------------------------------------------------
6297
6298AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6299 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006300 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006301 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006302 audio_devices_t inDevice,
6303 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006304 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006305 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006306 mInput(input),
6307 mActiveTracks(&this->mLocalLog),
6308 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006309 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006310 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006311 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6312 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006313 // mFastCapture below
6314 , mFastCaptureFutex(0)
6315 // mInputSource
6316 // mPipeSink
6317 // mPipeSource
6318 , mPipeFramesP2(0)
6319 // mPipeMemory
6320 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006321 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006322 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006323{
Glenn Kastend7dca052015-03-05 16:05:54 -08006324 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6325 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006326
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006327 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006328
6329 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006330 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006331 size_t numCounterOffers = 0;
6332 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006333#if !LOG_NDEBUG
6334 ssize_t index =
6335#else
6336 (void)
6337#endif
6338 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006339 ALOG_ASSERT(index == 0);
6340
6341 // initialize fast capture depending on configuration
6342 bool initFastCapture;
6343 switch (kUseFastCapture) {
6344 case FastCapture_Never:
6345 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006346 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006347 break;
6348 case FastCapture_Always:
6349 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006350 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006351 break;
6352 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006353 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006354 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6355 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6356 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006357 break;
6358 // case FastCapture_Dynamic:
6359 }
6360
6361 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006362 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006363 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006364 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6365 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006366 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006367 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006368 const sp<MemoryDealer> roHeap(readOnlyHeap());
6369 sp<IMemory> pipeMemory;
6370 if ((roHeap == 0) ||
6371 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006372 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6373 ALOGE("not enough memory for pipe buffer size=%zu; "
6374 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6375 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6376 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006377 goto failed;
6378 }
6379 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6380 memset(pipeBuffer, 0, pipeSize);
6381 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6382 const NBAIO_Format offers[1] = {format};
6383 size_t numCounterOffers = 0;
6384 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6385 ALOG_ASSERT(index == 0);
6386 mPipeSink = pipe;
6387 PipeReader *pipeReader = new PipeReader(*pipe);
6388 numCounterOffers = 0;
6389 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6390 ALOG_ASSERT(index == 0);
6391 mPipeSource = pipeReader;
6392 mPipeFramesP2 = pipeFramesP2;
6393 mPipeMemory = pipeMemory;
6394
6395 // create fast capture
6396 mFastCapture = new FastCapture();
6397 FastCaptureStateQueue *sq = mFastCapture->sq();
6398#ifdef STATE_QUEUE_DUMP
6399 // FIXME
6400#endif
6401 FastCaptureState *state = sq->begin();
6402 state->mCblk = NULL;
6403 state->mInputSource = mInputSource.get();
6404 state->mInputSourceGen++;
6405 state->mPipeSink = pipe;
6406 state->mPipeSinkGen++;
6407 state->mFrameCount = mFrameCount;
6408 state->mCommand = FastCaptureState::COLD_IDLE;
6409 // already done in constructor initialization list
6410 //mFastCaptureFutex = 0;
6411 state->mColdFutexAddr = &mFastCaptureFutex;
6412 state->mColdGen++;
6413 state->mDumpState = &mFastCaptureDumpState;
6414#ifdef TEE_SINK
6415 // FIXME
6416#endif
6417 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6418 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6419 sq->end();
6420 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6421
6422 // start the fast capture
6423 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6424 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006425 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006426 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006427#ifdef AUDIO_WATCHDOG
6428 // FIXME
6429#endif
6430
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006431 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006432 }
Andy Hung8946a282018-04-19 20:04:56 -07006433#ifdef TEE_SINK
6434 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6435 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6436#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006437failed: ;
6438
6439 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006440}
6441
Eric Laurent81784c32012-11-19 14:55:58 -08006442AudioFlinger::RecordThread::~RecordThread()
6443{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006444 if (mFastCapture != 0) {
6445 FastCaptureStateQueue *sq = mFastCapture->sq();
6446 FastCaptureState *state = sq->begin();
6447 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6448 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6449 if (old == -1) {
6450 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6451 }
6452 }
6453 state->mCommand = FastCaptureState::EXIT;
6454 sq->end();
6455 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6456 mFastCapture->join();
6457 mFastCapture.clear();
6458 }
6459 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006460 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006461 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006462}
6463
6464void AudioFlinger::RecordThread::onFirstRef()
6465{
Glenn Kastend7dca052015-03-05 16:05:54 -08006466 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006467}
6468
Eric Laurent555530a2017-02-07 18:17:24 -08006469void AudioFlinger::RecordThread::preExit()
6470{
6471 ALOGV(" preExit()");
6472 Mutex::Autolock _l(mLock);
6473 for (size_t i = 0; i < mTracks.size(); i++) {
6474 sp<RecordTrack> track = mTracks[i];
6475 track->invalidate();
6476 }
6477 mActiveTracks.clear();
6478 mStartStopCond.broadcast();
6479}
6480
Eric Laurent81784c32012-11-19 14:55:58 -08006481bool AudioFlinger::RecordThread::threadLoop()
6482{
Eric Laurent81784c32012-11-19 14:55:58 -08006483 nsecs_t lastWarning = 0;
6484
6485 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006486
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006487reacquire_wakelock:
6488 sp<RecordTrack> activeTrack;
6489 {
6490 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006491 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006492 }
6493
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006494 // used to request a deferred sleep, to be executed later while mutex is unlocked
6495 uint32_t sleepUs = 0;
6496
6497 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006498 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006499 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006500
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006501 // activeTracks accumulates a copy of a subset of mActiveTracks
6502 Vector< sp<RecordTrack> > activeTracks;
6503
Glenn Kasten735f45f2014-08-18 15:51:59 -07006504 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006505 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006506
Glenn Kasten735f45f2014-08-18 15:51:59 -07006507 // reference to a fast track which is about to be removed
6508 sp<RecordTrack> fastTrackToRemove;
6509
Eric Laurent81784c32012-11-19 14:55:58 -08006510 { // scope for mLock
6511 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006512
Eric Laurent021cf962014-05-13 10:18:14 -07006513 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006514
Eric Laurent000a4192014-01-29 15:17:32 -08006515 // check exitPending here because checkForNewParameters_l() and
6516 // checkForNewParameters_l() can temporarily release mLock
6517 if (exitPending()) {
6518 break;
6519 }
6520
Eric Laurent5c25d562016-07-13 17:17:45 -07006521 // sleep with mutex unlocked
6522 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006523 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006524 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6525 ATRACE_END();
6526 sleepUs = 0;
6527 continue;
6528 }
6529
Glenn Kasten2b806402013-11-20 16:37:38 -08006530 // if no active track(s), then standby and release wakelock
6531 size_t size = mActiveTracks.size();
6532 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006533 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006534 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006535 releaseWakeLock_l();
6536 ALOGV("RecordThread: loop stopping");
6537 // go to sleep
6538 mWaitWorkCV.wait(mLock);
6539 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006540 goto reacquire_wakelock;
6541 }
6542
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006543 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006544 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006545 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006546
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006547 activeTrack = mActiveTracks[i];
6548 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006549 if (activeTrack->isFastTrack()) {
6550 ALOG_ASSERT(fastTrackToRemove == 0);
6551 fastTrackToRemove = activeTrack;
6552 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006553 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006554 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006555 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006556 continue;
6557 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006558
6559 TrackBase::track_state activeTrackState = activeTrack->mState;
6560 switch (activeTrackState) {
6561
6562 case TrackBase::PAUSING:
6563 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006564 doBroadcast = true;
6565 size--;
6566 continue;
6567
6568 case TrackBase::STARTING_1:
6569 sleepUs = 10000;
6570 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006571 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006572 continue;
6573
6574 case TrackBase::STARTING_2:
6575 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006576 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006577 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006578 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006579 break;
6580
6581 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006582 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006583 break;
6584
6585 case TrackBase::IDLE:
6586 i++;
6587 continue;
6588
6589 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08006590 LOG_ALWAYS_FATAL("Unexpected activeTrackState %d", activeTrackState);
Glenn Kasten9e982352013-08-14 14:39:50 -07006591 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006592
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006593 activeTracks.add(activeTrack);
6594 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006595
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006596 if (activeTrack->isFastTrack()) {
6597 ALOG_ASSERT(!mFastTrackAvail);
6598 ALOG_ASSERT(fastTrack == 0);
6599 fastTrack = activeTrack;
6600 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006601 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006602
Andy Hungdae27702016-10-31 14:01:16 -07006603 mActiveTracks.updatePowerState(this);
6604
Kevin Rocard069c2712018-03-29 19:09:14 -07006605 updateMetadata_l();
6606
Eric Laurent5c25d562016-07-13 17:17:45 -07006607 if (allStopped) {
6608 standbyIfNotAlreadyInStandby();
6609 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006610 if (doBroadcast) {
6611 mStartStopCond.broadcast();
6612 }
6613
6614 // sleep if there are no active tracks to process
6615 if (activeTracks.size() == 0) {
6616 if (sleepUs == 0) {
6617 sleepUs = kRecordThreadSleepUs;
6618 }
6619 continue;
6620 }
6621 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006622
Eric Laurent81784c32012-11-19 14:55:58 -08006623 lockEffectChains_l(effectChains);
6624 }
6625
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006626 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006627
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006628 size_t size = effectChains.size();
6629 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006630 // thread mutex is not locked, but effect chain is locked
6631 effectChains[i]->process_l();
6632 }
6633
Glenn Kasten735f45f2014-08-18 15:51:59 -07006634 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006635 if (mFastCapture != 0) {
6636 FastCaptureStateQueue *sq = mFastCapture->sq();
6637 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006638 bool didModify = false;
6639 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006640 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6641 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6642 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6643 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6644 if (old == -1) {
6645 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6646 }
6647 }
6648 state->mCommand = FastCaptureState::READ_WRITE;
6649#if 0 // FIXME
6650 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006651 FastThreadDumpState::kSamplingNforLowRamDevice :
6652 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006653#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006654 didModify = true;
6655 }
6656 audio_track_cblk_t *cblkOld = state->mCblk;
6657 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6658 if (cblkNew != cblkOld) {
6659 state->mCblk = cblkNew;
6660 // block until acked if removing a fast track
6661 if (cblkOld != NULL) {
6662 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6663 }
6664 didModify = true;
6665 }
6666 sq->end(didModify);
6667 if (didModify) {
6668 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006669#if 0
6670 if (kUseFastCapture == FastCapture_Dynamic) {
6671 mNormalSource = mPipeSource;
6672 }
6673#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006674 }
6675 }
6676
Glenn Kasten735f45f2014-08-18 15:51:59 -07006677 // now run the fast track destructor with thread mutex unlocked
6678 fastTrackToRemove.clear();
6679
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006680 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6681 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6682 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6683 // If destination is non-contiguous, first read past the nominal end of buffer, then
6684 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006685
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006686 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006687 ssize_t framesRead;
6688
6689 // If an NBAIO source is present, use it to read the normal capture's data
6690 if (mPipeSource != 0) {
6691 size_t framesToRead = mBufferSize / mFrameSize;
Glenn Kasten1b291842016-07-18 14:55:21 -07006692 framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006693
6694 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6695 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6696 // we immediately retry the read() to get data and prevent another overflow.
6697 for (int retries = 0; retries <= 2; ++retries) {
6698 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6699 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6700 framesToRead);
6701 if (framesRead != OVERRUN) break;
6702 }
6703
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006704 const ssize_t availableToRead = mPipeSource->availableToRead();
6705 if (availableToRead >= 0) {
6706 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6707 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6708 "more frames to read than fifo size, %zd > %zu",
6709 availableToRead, mPipeFramesP2);
6710 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6711 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6712 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6713 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006714 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6715 }
6716 if (framesRead < 0) {
6717 status_t status = (status_t) framesRead;
6718 switch (status) {
6719 case OVERRUN:
6720 ALOGW("overrun on read from pipe");
6721 framesRead = 0;
6722 break;
6723 case NEGOTIATE:
6724 ALOGE("re-negotiation is needed");
6725 framesRead = -1; // Will cause an attempt to recover.
6726 break;
6727 default:
6728 ALOGE("unknown error %d on read from pipe", status);
6729 break;
6730 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006731 }
6732 // otherwise use the HAL / AudioStreamIn directly
6733 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006734 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006735 size_t bytesRead;
6736 status_t result = mInput->stream->read(
6737 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006738 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006739 if (result < 0) {
6740 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006741 } else {
6742 framesRead = bytesRead / mFrameSize;
6743 }
6744 }
6745
Andy Hung3f0c9022016-01-15 17:49:46 -08006746 // Update server timestamp with server stats
6747 // systemTime() is optional if the hardware supports timestamps.
6748 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
6749 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
6750
6751 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006752 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006753 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006754 if (mStandby) {
6755 mTimestampVerifier.discontinuity();
6756 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR) {
Andy Hung3f0c9022016-01-15 17:49:46 -08006757 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
6758 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
6759 // Note: In general record buffers should tend to be empty in
6760 // a properly running pipeline.
6761 //
6762 // Also, it is not advantageous to call get_presentation_position during the read
6763 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07006764
6765 mTimestampVerifier.add(mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
6766 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
6767 mSampleRate);
6768 } else {
6769 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08006770 }
6771 }
6772 // Use this to track timestamp information
6773 // ALOGD("%s", mTimestamp.toString().c_str());
6774
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006775 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006776 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006777 // Force input into standby so that it tries to recover at next read attempt
6778 inputStandBy();
6779 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006780 }
6781 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006782 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006783 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006784 ALOG_ASSERT(framesRead > 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006785
Andy Hung8946a282018-04-19 20:04:56 -07006786#ifdef TEE_SINK
6787 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
6788#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006789 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006790 {
6791 size_t part1 = mRsmpInFramesP2 - rear;
6792 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07006793 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006794 (framesRead - part1) * mFrameSize);
6795 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006796 }
6797 rear = mRsmpInRear += framesRead;
6798
6799 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006800
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006801 // loop over each active track
6802 for (size_t i = 0; i < size; i++) {
6803 activeTrack = activeTracks[i];
6804
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006805 // skip fast tracks, as those are handled directly by FastCapture
6806 if (activeTrack->isFastTrack()) {
6807 continue;
6808 }
6809
Andy Hung73c02e42015-03-29 01:13:58 -07006810 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07006811 // TODO: Update the activeTrack buffer converter in case of reconfigure.
6812
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006813 enum {
6814 OVERRUN_UNKNOWN,
6815 OVERRUN_TRUE,
6816 OVERRUN_FALSE
6817 } overrun = OVERRUN_UNKNOWN;
6818
6819 // loop over getNextBuffer to handle circular sink
6820 for (;;) {
6821
6822 activeTrack->mSink.frameCount = ~0;
6823 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
6824 size_t framesOut = activeTrack->mSink.frameCount;
6825 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
6826
Andy Hung73c02e42015-03-29 01:13:58 -07006827 // check available frames and handle overrun conditions
6828 // if the record track isn't draining fast enough.
6829 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006830 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07006831 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
6832 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006833 overrun = OVERRUN_TRUE;
6834 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006835 if (framesOut == 0 || framesIn == 0) {
6836 break;
6837 }
6838
Andy Hung6770c6f2015-04-07 13:43:36 -07006839 // Don't allow framesOut to be larger than what is possible with resampling
6840 // from framesIn.
6841 // This isn't strictly necessary but helps limit buffer resizing in
6842 // RecordBufferConverter. TODO: remove when no longer needed.
6843 framesOut = min(framesOut,
6844 destinationFramesPossible(
6845 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07006846
6847 if (activeTrack->isDirect()) {
6848 // No RecordBufferConverter used for compressed formats. Pass
6849 // straight from RecordThread buffer to RecordTrack buffer.
6850 AudioBufferProvider::Buffer buffer;
6851 buffer.frameCount = framesOut;
6852 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
6853 if (status == OK && buffer.frameCount != 0) {
6854 ALOGV_IF(buffer.frameCount != framesOut,
6855 "%s() read less than expected (%zu vs %zu)",
6856 __func__, buffer.frameCount, framesOut);
6857 framesOut = buffer.frameCount;
6858 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount);
6859 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
6860 } else {
6861 framesOut = 0;
6862 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
6863 __func__, status, buffer.frameCount);
6864 }
6865 } else {
6866 // process frames from the RecordThread buffer provider to the RecordTrack
6867 // buffer
6868 framesOut = activeTrack->mRecordBufferConverter->convert(
6869 activeTrack->mSink.raw,
6870 activeTrack->mResamplerBufferProvider,
6871 framesOut);
6872 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006873
6874 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
6875 overrun = OVERRUN_FALSE;
6876 }
6877
6878 if (activeTrack->mFramesToDrop == 0) {
6879 if (framesOut > 0) {
6880 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006881 // Sanitize before releasing if the track has no access to the source data
6882 // An idle UID receives silence from non virtual devices until active
6883 if (activeTrack->isSilenced()) {
6884 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
6885 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006886 activeTrack->releaseBuffer(&activeTrack->mSink);
6887 }
6888 } else {
6889 // FIXME could do a partial drop of framesOut
6890 if (activeTrack->mFramesToDrop > 0) {
6891 activeTrack->mFramesToDrop -= framesOut;
6892 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006893 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006894 }
6895 } else {
6896 activeTrack->mFramesToDrop += framesOut;
6897 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
6898 activeTrack->mSyncStartEvent->isCancelled()) {
6899 ALOGW("Synced record %s, session %d, trigger session %d",
6900 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
6901 activeTrack->sessionId(),
6902 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08006903 activeTrack->mSyncStartEvent->triggerSession() :
6904 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08006905 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006906 }
6907 }
6908 }
6909
6910 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006911 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006912 }
6913 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006914
6915 switch (overrun) {
6916 case OVERRUN_TRUE:
6917 // client isn't retrieving buffers fast enough
6918 if (!activeTrack->setOverflow()) {
6919 nsecs_t now = systemTime();
6920 // FIXME should lastWarning per track?
6921 if ((now - lastWarning) > kWarningThrottleNs) {
6922 ALOGW("RecordThread: buffer overflow");
6923 lastWarning = now;
6924 }
6925 }
6926 break;
6927 case OVERRUN_FALSE:
6928 activeTrack->clearOverflow();
6929 break;
6930 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006931 break;
6932 }
6933
Andy Hung3f0c9022016-01-15 17:49:46 -08006934 // update frame information and push timestamp out
6935 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08006936 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08006937 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
6938 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006939 }
6940
Glenn Kasten3d61bc12014-06-16 10:25:20 -07006941unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08006942 // enable changes in effect chain
6943 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006944 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08006945 }
6946
Glenn Kasten93e471f2013-08-19 08:40:07 -07006947 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08006948
6949 {
6950 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07006951 for (size_t i = 0; i < mTracks.size(); i++) {
6952 sp<RecordTrack> track = mTracks[i];
6953 track->invalidate();
6954 }
Glenn Kasten2b806402013-11-20 16:37:38 -08006955 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006956 mStartStopCond.broadcast();
6957 }
6958
6959 releaseWakeLock();
6960
6961 ALOGV("RecordThread %p exiting", this);
6962 return false;
6963}
6964
Glenn Kasten93e471f2013-08-19 08:40:07 -07006965void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08006966{
6967 if (!mStandby) {
6968 inputStandBy();
6969 mStandby = true;
6970 }
6971}
6972
6973void AudioFlinger::RecordThread::inputStandBy()
6974{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006975 // Idle the fast capture if it's currently running
6976 if (mFastCapture != 0) {
6977 FastCaptureStateQueue *sq = mFastCapture->sq();
6978 FastCaptureState *state = sq->begin();
6979 if (!(state->mCommand & FastCaptureState::IDLE)) {
6980 state->mCommand = FastCaptureState::COLD_IDLE;
6981 state->mColdFutexAddr = &mFastCaptureFutex;
6982 state->mColdGen++;
6983 mFastCaptureFutex = 0;
6984 sq->end();
6985 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
6986 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
6987#if 0
6988 if (kUseFastCapture == FastCapture_Dynamic) {
6989 // FIXME
6990 }
6991#endif
6992#ifdef AUDIO_WATCHDOG
6993 // FIXME
6994#endif
6995 } else {
6996 sq->end(false /*didModify*/);
6997 }
6998 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006999 status_t result = mInput->stream->standby();
7000 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007001
7002 // If going into standby, flush the pipe source.
7003 if (mPipeSource.get() != nullptr) {
7004 const ssize_t flushed = mPipeSource->flush();
7005 if (flushed > 0) {
7006 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7007 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7008 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7009 }
7010 }
Eric Laurent81784c32012-11-19 14:55:58 -08007011}
7012
Glenn Kasten05997e22014-03-13 15:08:33 -07007013// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007014sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007015 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007016 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007017 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007018 audio_format_t format,
7019 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007020 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007021 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007022 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007023 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007024 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007025 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007026 status_t *status,
7027 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
Glenn Kasten74935e42013-12-19 08:56:45 -08007029 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007030 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007031 sp<RecordTrack> track;
7032 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007033 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007034 audio_input_flags_t requestedFlags = *flags;
7035 uint32_t sampleRate;
7036
7037 lStatus = initCheck();
7038 if (lStatus != NO_ERROR) {
7039 ALOGE("createRecordTrack_l() audio driver not initialized");
7040 goto Exit;
7041 }
7042
7043 if (*pSampleRate == 0) {
7044 *pSampleRate = mSampleRate;
7045 }
7046 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007047
7048 // special case for FAST flag considered OK if fast capture is present
7049 if (hasFastCapture()) {
7050 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7051 }
7052
Eric Laurentf14db3c2017-12-08 14:20:36 -08007053 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007054 if ((*flags & inputFlags) != *flags) {
7055 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7056 " input flags (%08x)",
7057 *flags, inputFlags);
7058 *flags = (audio_input_flags_t)(*flags & inputFlags);
7059 }
Eric Laurent81784c32012-11-19 14:55:58 -08007060
Glenn Kasten90e58b12013-07-31 16:16:02 -07007061 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007062 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007063 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007064 // we formerly checked for a callback handler (non-0 tid),
7065 // but that is no longer required for TRANSFER_OBTAIN mode
7066 //
Glenn Kasten74105912014-07-03 12:28:53 -07007067 // frame count is not specified, or is exactly the pipe depth
7068 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007069 // PCM data
7070 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007071 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007072 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007073 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007074 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007075 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007076 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007077 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007078 hasFastCapture() &&
7079 // there are sufficient fast track slots available
7080 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007081 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007082 // check compatibility with audio effects.
7083 Mutex::Autolock _l(mLock);
7084 // Do not accept FAST flag if the session has software effects
7085 sp<EffectChain> chain = getEffectChain_l(sessionId);
7086 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007087 audio_input_flags_t old = *flags;
7088 chain->checkInputFlagCompatibility(flags);
7089 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007090 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7091 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007092 }
7093 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007094 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007095 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7096 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007097 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007098 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7099 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007100 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007101 this, frameCount, mFrameCount, mPipeFramesP2,
7102 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007103 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007104 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007105 }
7106 }
7107
Eric Laurentf14db3c2017-12-08 14:20:36 -08007108 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7109 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7110 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7111 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7112 lStatus = BAD_TYPE;
7113 goto Exit;
7114 }
7115
Glenn Kasten74105912014-07-03 12:28:53 -07007116 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007117 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007118 // fast track: frame count is exactly the pipe depth
7119 frameCount = mPipeFramesP2;
7120 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007121 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007122 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007123 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7124 // or 20 ms if there is a fast capture
7125 // TODO This could be a roundupRatio inline, and const
7126 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7127 * sampleRate + mSampleRate - 1) / mSampleRate;
7128 // minimum number of notification periods is at least kMinNotifications,
7129 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7130 static const size_t kMinNotifications = 3;
7131 static const uint32_t kMinMs = 30;
7132 // TODO This could be a roundupRatio inline
7133 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7134 // TODO This could be a roundupRatio inline
7135 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7136 maxNotificationFrames;
7137 const size_t minFrameCount = maxNotificationFrames *
7138 max(kMinNotifications, minNotificationsByMs);
7139 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007140 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7141 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007142 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007143 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007144 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007145 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007146
7147 { // scope for mLock
7148 Mutex::Autolock _l(mLock);
7149
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007150 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007151 format, channelMask, frameCount,
7152 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007153 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007154
Glenn Kasten03003332013-08-06 15:40:54 -07007155 lStatus = track->initCheck();
7156 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007157 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007158 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007159 goto Exit;
7160 }
7161 mTracks.add(track);
7162
Eric Laurent05067782016-06-01 18:27:28 -07007163 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007164 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7165 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7166 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007167 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007168 }
Eric Laurent81784c32012-11-19 14:55:58 -08007169 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007170
Eric Laurent81784c32012-11-19 14:55:58 -08007171 lStatus = NO_ERROR;
7172
7173Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007174 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007175 return track;
7176}
7177
7178status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7179 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007180 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007181{
7182 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7183 sp<ThreadBase> strongMe = this;
7184 status_t status = NO_ERROR;
7185
7186 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007187 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007188 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007189 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007190 triggerSession,
7191 recordTrack->sessionId(),
7192 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007193 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007194 // Sync event can be cancelled by the trigger session if the track is not in a
7195 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007196 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007197 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007198 } else {
7199 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007200 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007201 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007202 }
7203 }
7204
7205 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007206 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007207 AutoMutex lock(mLock);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007208 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7209 if (recordTrack->mState == TrackBase::PAUSING) {
7210 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007211 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007212 } else {
7213 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007214 }
7215 return status;
7216 }
7217
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007218 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7219 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7220 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007221 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007222 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007223 status_t status = NO_ERROR;
7224 if (recordTrack->isExternalTrack()) {
7225 mLock.unlock();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007226 bool silenced;
Eric Laurentfee19762018-01-29 18:44:13 -08007227 status = AudioSystem::startInput(recordTrack->portId(), &silenced);
Eric Laurent83b88082014-06-20 18:31:16 -07007228 mLock.lock();
7229 // FIXME should verify that recordTrack is still in mActiveTracks
7230 if (status != NO_ERROR) {
7231 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007232 recordTrack->clearSyncStartEvent();
7233 ALOGV("RecordThread::start error %d", status);
7234 return status;
7235 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007236 recordTrack->setSilenced(silenced);
Eric Laurent81784c32012-11-19 14:55:58 -08007237 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007238 // Catch up with current buffer indices if thread is already running.
7239 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7240 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7241 // see previously buffered data before it called start(), but with greater risk of overrun.
7242
Andy Hung73c02e42015-03-29 01:13:58 -07007243 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007244 if (!recordTrack->isDirect()) {
7245 // clear any converter state as new data will be discontinuous
7246 recordTrack->mRecordBufferConverter->reset();
7247 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007248 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007249 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007250 mWaitWorkCV.broadcast();
Glenn Kasten2b806402013-11-20 16:37:38 -08007251 if (mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007252 ALOGV("Record failed to start");
7253 status = BAD_VALUE;
7254 goto startError;
7255 }
Eric Laurent81784c32012-11-19 14:55:58 -08007256 return status;
7257 }
Glenn Kasten7c027242012-12-26 14:43:16 -08007258
Eric Laurent81784c32012-11-19 14:55:58 -08007259startError:
Eric Laurent83b88082014-06-20 18:31:16 -07007260 if (recordTrack->isExternalTrack()) {
Eric Laurentfee19762018-01-29 18:44:13 -08007261 AudioSystem::stopInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007262 }
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007263 recordTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007264 // FIXME I wonder why we do not reset the state here?
Eric Laurent81784c32012-11-19 14:55:58 -08007265 return status;
7266}
7267
Eric Laurent81784c32012-11-19 14:55:58 -08007268void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7269{
7270 sp<SyncEvent> strongEvent = event.promote();
7271
7272 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007273 sp<RefBase> ptr = strongEvent->cookie().promote();
7274 if (ptr != 0) {
7275 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7276 recordTrack->handleSyncStartEvent(strongEvent);
7277 }
Eric Laurent81784c32012-11-19 14:55:58 -08007278 }
7279}
7280
Glenn Kastena8356f62013-07-25 14:37:52 -07007281bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007282 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007283 AutoMutex _l(mLock);
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007284 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007285 return false;
7286 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007287 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007288 recordTrack->mState = TrackBase::PAUSING;
Eric Laurent5c25d562016-07-13 17:17:45 -07007289 // signal thread to stop
7290 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007291 // do not wait for mStartStopCond if exiting
7292 if (exitPending()) {
7293 return true;
7294 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007295 // FIXME incorrect usage of wait: no explicit predicate or loop
Eric Laurent81784c32012-11-19 14:55:58 -08007296 mStartStopCond.wait(mLock);
Glenn Kasten2b806402013-11-20 16:37:38 -08007297 // if we have been restarted, recordTrack is in mActiveTracks here
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007298 if (exitPending() || mActiveTracks.indexOf(recordTrack) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007299 ALOGV("Record stopped OK");
7300 return true;
7301 }
7302 return false;
7303}
7304
Glenn Kasten0f11b512014-01-31 16:18:54 -08007305bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007306{
7307 return false;
7308}
7309
Glenn Kasten0f11b512014-01-31 16:18:54 -08007310status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007311{
7312#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7313 if (!isValidSyncEvent(event)) {
7314 return BAD_VALUE;
7315 }
7316
Glenn Kastend848eb42016-03-08 13:42:11 -08007317 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007318 status_t ret = NAME_NOT_FOUND;
7319
7320 Mutex::Autolock _l(mLock);
7321
7322 for (size_t i = 0; i < mTracks.size(); i++) {
7323 sp<RecordTrack> track = mTracks[i];
7324 if (eventSession == track->sessionId()) {
7325 (void) track->setSyncEvent(event);
7326 ret = NO_ERROR;
7327 }
7328 }
7329 return ret;
7330#else
7331 return BAD_VALUE;
7332#endif
7333}
7334
jiabin653cc0a2018-01-17 17:54:10 -08007335status_t AudioFlinger::RecordThread::getActiveMicrophones(
7336 std::vector<media::MicrophoneInfo>* activeMicrophones)
7337{
7338 ALOGV("RecordThread::getActiveMicrophones");
7339 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007340 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7341 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007342}
7343
Kevin Rocard069c2712018-03-29 19:09:14 -07007344void AudioFlinger::RecordThread::updateMetadata_l()
7345{
7346 if (mInput == nullptr || mInput->stream == nullptr ||
7347 !mActiveTracks.readAndClearHasChanged()) {
7348 return;
7349 }
7350 StreamInHalInterface::SinkMetadata metadata;
7351 for (const sp<RecordTrack> &track : mActiveTracks) {
7352 // No track is invalid as this is called after prepareTrack_l in the same critical section
7353 metadata.tracks.push_back({
7354 .source = track->attributes().source,
7355 .gain = 1, // capture tracks do not have volumes
7356 });
7357 }
7358 mInput->stream->updateSinkMetadata(metadata);
7359}
7360
Eric Laurent81784c32012-11-19 14:55:58 -08007361// destroyTrack_l() must be called with ThreadBase::mLock held
7362void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7363{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364 track->terminate();
7365 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007366 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007367 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007368 removeTrack_l(track);
7369 }
7370}
7371
7372void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7373{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007374 String8 result;
7375 track->appendDump(result, false /* active */);
7376 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7377
Eric Laurent81784c32012-11-19 14:55:58 -08007378 mTracks.remove(track);
7379 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007380 if (track->isFastTrack()) {
7381 ALOG_ASSERT(!mFastTrackAvail);
7382 mFastTrackAvail = true;
7383 }
Eric Laurent81784c32012-11-19 14:55:58 -08007384}
7385
7386void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7387{
7388 dumpInternals(fd, args);
7389 dumpTracks(fd, args);
7390 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007391 dprintf(fd, " Local log:\n");
7392 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007393}
7394
7395void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7396{
Glenn Kasten44182c22015-03-05 17:12:23 -08007397 dumpBase(fd, args);
7398
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007399 AudioStreamIn *input = mInput;
7400 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7401 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7402 input, flags, inputFlagsToString(flags).c_str());
Glenn Kasten44182c22015-03-05 17:12:23 -08007403 if (mActiveTracks.size() == 0) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007404 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007405 }
Andy Hungbfa64962017-06-12 14:43:19 -07007406
7407 if (input != nullptr) {
7408 dprintf(fd, " Hal stream dump:\n");
7409 (void)input->stream->dump(fd);
7410 }
7411
Andy Hung20bd30b2018-06-01 15:39:35 -07007412 const double latencyMs = - mTimestamp.getOutputServerLatencyMs(mSampleRate);
7413 if (latencyMs != 0.) {
7414 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7415 } else {
7416 dprintf(fd, " NormalRecord latency ms: unavail\n");
7417 }
7418
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007419 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007420 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007421
Glenn Kasten2f90c512015-12-02 11:40:09 -08007422 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7423 // while we are dumping it. It may be inconsistent, but it won't mutate!
7424 // This is a large object so we place it on the heap.
7425 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
7426 const FastCaptureDumpState *copy = new FastCaptureDumpState(mFastCaptureDumpState);
7427 copy->dump(fd);
7428 delete copy;
Eric Laurent81784c32012-11-19 14:55:58 -08007429}
7430
Glenn Kasten0f11b512014-01-31 16:18:54 -08007431void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007432{
Eric Laurent81784c32012-11-19 14:55:58 -08007433 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007434 size_t numtracks = mTracks.size();
7435 size_t numactive = mActiveTracks.size();
7436 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007437 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007438 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007439 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007440 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007441 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007442 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007443 for (size_t i = 0; i < numtracks ; ++i) {
7444 sp<RecordTrack> track = mTracks[i];
7445 if (track != 0) {
7446 bool active = mActiveTracks.indexOf(track) >= 0;
7447 if (active) {
7448 numactiveseen++;
7449 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007450 result.append(prefix);
7451 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007452 }
Eric Laurent81784c32012-11-19 14:55:58 -08007453 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007454 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007455 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007456 }
7457
Marco Nelissenb2208842014-02-07 14:00:50 -08007458 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007459 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007460 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007461 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007462 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007463 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007464 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007465 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007466 result.append(prefix);
7467 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007468 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007469 }
Eric Laurent81784c32012-11-19 14:55:58 -08007470
7471 }
7472 write(fd, result.string(), result.size());
7473}
7474
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007475void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7476{
7477 Mutex::Autolock _l(mLock);
7478 for (size_t i = 0; i < mTracks.size() ; i++) {
7479 sp<RecordTrack> track = mTracks[i];
7480 if (track != 0 && track->uid() == uid) {
7481 track->setSilenced(silenced);
7482 }
7483 }
7484}
Andy Hung73c02e42015-03-29 01:13:58 -07007485
7486void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7487{
7488 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7489 RecordThread *recordThread = (RecordThread *) threadBase.get();
7490 mRsmpInFront = recordThread->mRsmpInRear;
7491 mRsmpInUnrel = 0;
7492}
7493
7494void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7495 size_t *framesAvailable, bool *hasOverrun)
7496{
7497 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7498 RecordThread *recordThread = (RecordThread *) threadBase.get();
7499 const int32_t rear = recordThread->mRsmpInRear;
7500 const int32_t front = mRsmpInFront;
7501 const ssize_t filled = rear - front;
7502
7503 size_t framesIn;
7504 bool overrun = false;
7505 if (filled < 0) {
7506 // should not happen, but treat like a massive overrun and re-sync
7507 framesIn = 0;
7508 mRsmpInFront = rear;
7509 overrun = true;
7510 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7511 framesIn = (size_t) filled;
7512 } else {
7513 // client is not keeping up with server, but give it latest data
7514 framesIn = recordThread->mRsmpInFrames;
7515 mRsmpInFront = /* front = */ rear - framesIn;
7516 overrun = true;
7517 }
7518 if (framesAvailable != NULL) {
7519 *framesAvailable = framesIn;
7520 }
7521 if (hasOverrun != NULL) {
7522 *hasOverrun = overrun;
7523 }
7524}
7525
Eric Laurent81784c32012-11-19 14:55:58 -08007526// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007527status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007528 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007529{
Andy Hung73c02e42015-03-29 01:13:58 -07007530 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007531 if (threadBase == 0) {
7532 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007533 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007534 return NOT_ENOUGH_DATA;
7535 }
7536 RecordThread *recordThread = (RecordThread *) threadBase.get();
7537 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007538 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007539 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007540 // FIXME should not be P2 (don't want to increase latency)
7541 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007542 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007543 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007544 front &= recordThread->mRsmpInFramesP2 - 1;
7545 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007546 if (part1 > (size_t) filled) {
7547 part1 = filled;
7548 }
7549 size_t ask = buffer->frameCount;
7550 ALOG_ASSERT(ask > 0);
7551 if (part1 > ask) {
7552 part1 = ask;
7553 }
7554 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007555 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007556 buffer->raw = NULL;
7557 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007558 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007559 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007560 }
7561
Andy Hung57446612015-04-19 23:56:46 -07007562 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007563 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007564 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007565 return NO_ERROR;
7566}
7567
7568// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007569void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7570 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007571{
Glenn Kasten85948432013-08-19 12:09:05 -07007572 size_t stepCount = buffer->frameCount;
7573 if (stepCount == 0) {
7574 return;
7575 }
Andy Hung73c02e42015-03-29 01:13:58 -07007576 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7577 mRsmpInUnrel -= stepCount;
7578 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007579 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007580 buffer->frameCount = 0;
7581}
7582
Eric Laurentd8365c52017-07-16 15:27:05 -07007583void AudioFlinger::RecordThread::checkBtNrec()
7584{
7585 Mutex::Autolock _l(mLock);
7586 checkBtNrec_l();
7587}
7588
7589void AudioFlinger::RecordThread::checkBtNrec_l()
7590{
7591 // disable AEC and NS if the device is a BT SCO headset supporting those
7592 // pre processings
7593 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7594 mAudioFlinger->btNrecIsOff();
7595 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7596 for (size_t i = 0; i < mEffectChains.size(); i++) {
7597 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7598 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7599 }
7600 }
7601}
7602
Andy Hung97a893e2015-03-29 01:03:07 -07007603
Eric Laurent10351942014-05-08 18:49:52 -07007604bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7605 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007606{
7607 bool reconfig = false;
7608
Eric Laurent10351942014-05-08 18:49:52 -07007609 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007610
Eric Laurent10351942014-05-08 18:49:52 -07007611 audio_format_t reqFormat = mFormat;
7612 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007613 // 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 -07007614 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7615
7616 AudioParameter param = AudioParameter(keyValuePair);
7617 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007618
7619 // scope for AutoPark extends to end of method
7620 AutoPark<FastCapture> park(mFastCapture);
7621
Eric Laurent10351942014-05-08 18:49:52 -07007622 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7623 // channel count change can be requested. Do we mandate the first client defines the
7624 // HAL sampling rate and channel count or do we allow changes on the fly?
7625 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7626 samplingRate = value;
7627 reconfig = true;
7628 }
7629 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007630 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007631 status = BAD_VALUE;
7632 } else {
7633 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007634 reconfig = true;
7635 }
Eric Laurent10351942014-05-08 18:49:52 -07007636 }
7637 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7638 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007639 if (!audio_is_input_channel(mask) ||
7640 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007641 status = BAD_VALUE;
7642 } else {
7643 channelMask = mask;
7644 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007645 }
Eric Laurent10351942014-05-08 18:49:52 -07007646 }
7647 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7648 // do not accept frame count changes if tracks are open as the track buffer
7649 // size depends on frame count and correct behavior would not be guaranteed
7650 // if frame count is changed after track creation
7651 if (mActiveTracks.size() > 0) {
7652 status = INVALID_OPERATION;
7653 } else {
7654 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007655 }
Eric Laurent10351942014-05-08 18:49:52 -07007656 }
7657 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7658 // forward device change to effects that have requested to be
7659 // aware of attached audio device.
7660 for (size_t i = 0; i < mEffectChains.size(); i++) {
7661 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007662 }
Eric Laurent81784c32012-11-19 14:55:58 -08007663
Eric Laurent10351942014-05-08 18:49:52 -07007664 // store input device and output device but do not forward output device to audio HAL.
7665 // Note that status is ignored by the caller for output device
7666 // (see AudioFlinger::setParameters()
7667 if (audio_is_output_devices(value)) {
7668 mOutDevice = value;
7669 status = BAD_VALUE;
7670 } else {
7671 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007672 if (value != AUDIO_DEVICE_NONE) {
7673 mPrevInDevice = value;
7674 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007675 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007676 }
Eric Laurent10351942014-05-08 18:49:52 -07007677 }
7678 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7679 mAudioSource != (audio_source_t)value) {
7680 // forward device change to effects that have requested to be
7681 // aware of attached audio device.
7682 for (size_t i = 0; i < mEffectChains.size(); i++) {
7683 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007684 }
Eric Laurent10351942014-05-08 18:49:52 -07007685 mAudioSource = (audio_source_t)value;
7686 }
Glenn Kastene198c362013-08-13 09:13:36 -07007687
Eric Laurent10351942014-05-08 18:49:52 -07007688 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007689 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007690 if (status == INVALID_OPERATION) {
7691 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007692 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007693 }
7694 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007695 if (status == BAD_VALUE) {
7696 uint32_t sRate;
7697 audio_channel_mask_t channelMask;
7698 audio_format_t format;
7699 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
7700 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
7701 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
7702 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
7703 status = NO_ERROR;
7704 }
Eric Laurent81784c32012-11-19 14:55:58 -08007705 }
Eric Laurent10351942014-05-08 18:49:52 -07007706 if (status == NO_ERROR) {
7707 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007708 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08007709 }
7710 }
Eric Laurent81784c32012-11-19 14:55:58 -08007711 }
Eric Laurent10351942014-05-08 18:49:52 -07007712
Eric Laurent81784c32012-11-19 14:55:58 -08007713 return reconfig;
7714}
7715
7716String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
7717{
Eric Laurent81784c32012-11-19 14:55:58 -08007718 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007719 if (initCheck() == NO_ERROR) {
7720 String8 out_s8;
7721 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
7722 return out_s8;
7723 }
Eric Laurent81784c32012-11-19 14:55:58 -08007724 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007725 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08007726}
7727
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007728void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007729 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
7730
7731 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08007732
7733 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07007734 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07007735 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07007736 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07007737 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07007738 desc->mChannelMask = mChannelMask;
7739 desc->mSamplingRate = mSampleRate;
7740 desc->mFormat = mFormat;
7741 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07007742 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07007743 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007744 break;
7745
Eric Laurent73e26b62015-04-27 16:55:58 -07007746 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08007747 default:
7748 break;
7749 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07007750 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08007751}
7752
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007753void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007754{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007755 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
7756 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hunge5412692014-05-16 11:25:07 -07007757 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007758 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d", mChannelCount, FCC_8);
Andy Hung463be252014-07-10 16:56:07 -07007759 mFormat = mHALFormat;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007760 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
7761 result = mInput->stream->getFrameSize(&mFrameSize);
7762 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
7763 result = mInput->stream->getBufferSize(&mBufferSize);
7764 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08007765 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007766 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
7767 "mBufferSize=%lld, mFrameCount=%lld",
7768 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
7769 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007770 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08007771 // 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 -07007772 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08007773 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007774 // A larger value should allow more old data to be read after a track calls start(),
7775 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07007776 //
7777 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08007778 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07007779 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07007780 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07007781 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007782
7783 // TODO optimize audio capture buffer sizes ...
7784 // Here we calculate the size of the sliding buffer used as a source
7785 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
7786 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
7787 // be better to have it derived from the pipe depth in the long term.
7788 // The current value is higher than necessary. However it should not add to latency.
7789
Glenn Kasten85948432013-08-19 12:09:05 -07007790 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07007791 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
7792 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007793 // if posix_memalign fails, will segv here.
7794 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007795
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007796 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
7797 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08007798}
7799
Glenn Kasten5f972c02014-01-13 09:59:31 -08007800uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08007801{
7802 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007803 uint32_t result;
7804 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
7805 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08007806 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007807 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007808}
7809
Eric Laurent4c415062016-06-17 16:14:16 -07007810// hasAudioSession_l() must be called with ThreadBase::mLock held
7811uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08007812{
Eric Laurent81784c32012-11-19 14:55:58 -08007813 uint32_t result = 0;
7814 if (getEffectChain_l(sessionId) != 0) {
7815 result = EFFECT_SESSION;
7816 }
7817
7818 for (size_t i = 0; i < mTracks.size(); ++i) {
7819 if (sessionId == mTracks[i]->sessionId()) {
7820 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07007821 if (mTracks[i]->isFastTrack()) {
7822 result |= FAST_SESSION;
7823 }
Eric Laurent81784c32012-11-19 14:55:58 -08007824 break;
7825 }
7826 }
7827
7828 return result;
7829}
7830
Glenn Kastend848eb42016-03-08 13:42:11 -08007831KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08007832{
Glenn Kastend848eb42016-03-08 13:42:11 -08007833 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08007834 Mutex::Autolock _l(mLock);
7835 for (size_t j = 0; j < mTracks.size(); ++j) {
7836 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08007837 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08007838 if (ids.indexOfKey(sessionId) < 0) {
7839 ids.add(sessionId, true);
7840 }
7841 }
7842 return ids;
7843}
7844
7845AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
7846{
7847 Mutex::Autolock _l(mLock);
7848 AudioStreamIn *input = mInput;
7849 mInput = NULL;
7850 return input;
7851}
7852
7853// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007854sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08007855{
7856 if (mInput == NULL) {
7857 return NULL;
7858 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007859 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08007860}
7861
7862status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
7863{
7864 // only one chain per input thread
7865 if (mEffectChains.size() != 0) {
Eric Laurentaaa44472014-09-12 17:41:50 -07007866 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08007867 return INVALID_OPERATION;
7868 }
7869 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07007870 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08007871 chain->setInBuffer(NULL);
7872 chain->setOutBuffer(NULL);
7873
7874 checkSuspendOnAddEffectChain_l(chain);
7875
Eric Laurent1b928682014-10-02 19:41:47 -07007876 // make sure enabled pre processing effects state is communicated to the HAL as we
7877 // just moved them to a new input stream.
7878 chain->syncHalEffectsState();
7879
Eric Laurent81784c32012-11-19 14:55:58 -08007880 mEffectChains.add(chain);
7881
7882 return NO_ERROR;
7883}
7884
7885size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
7886{
7887 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
7888 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007889 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08007890 chain.get(), mEffectChains.size(), this);
7891 if (mEffectChains.size() == 1) {
7892 mEffectChains.removeAt(0);
7893 }
7894 return 0;
7895}
7896
Eric Laurent1c333e22014-05-20 10:48:17 -07007897status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
7898 audio_patch_handle_t *handle)
7899{
7900 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007901
7902 // store new device and send to effects
7903 mInDevice = patch->sources[0].ext.device.type;
Eric Laurent296fb132015-05-01 11:38:42 -07007904 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07007905 for (size_t i = 0; i < mEffectChains.size(); i++) {
7906 mEffectChains[i]->setDevice_l(mInDevice);
7907 }
7908
Eric Laurentd8365c52017-07-16 15:27:05 -07007909 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07007910
7911 // store new source and send to effects
7912 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
7913 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07007914 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07007915 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07007916 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007917 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007918
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007919 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007920 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7921 status = hwDevice->createAudioPatch(patch->num_sources,
7922 patch->sources,
7923 patch->num_sinks,
7924 patch->sinks,
7925 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007926 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007927 char *address;
7928 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
7929 address = audio_device_address_to_parameter(
7930 patch->sources[0].ext.device.type,
7931 patch->sources[0].ext.device.address);
7932 } else {
7933 address = (char *)calloc(1, 1);
7934 }
7935 AudioParameter param = AudioParameter(String8(address));
7936 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007937 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07007938 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07007939 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07007940 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007941 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07007942 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07007943 }
Eric Laurent054d9d32015-04-24 08:48:48 -07007944
Eric Laurente8726fe2015-06-26 09:39:24 -07007945 if (mInDevice != mPrevInDevice) {
7946 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
7947 mPrevInDevice = mInDevice;
7948 }
Eric Laurent296fb132015-05-01 11:38:42 -07007949
Eric Laurent1c333e22014-05-20 10:48:17 -07007950 return status;
7951}
7952
7953status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
7954{
7955 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07007956
7957 mInDevice = AUDIO_DEVICE_NONE;
7958
Mikhail Naganov9ee05402016-10-13 15:58:17 -07007959 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07007960 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
7961 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07007962 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07007963 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07007964 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007965 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07007966 }
7967 return status;
7968}
7969
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007970void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007971{
7972 Mutex::Autolock _l(mLock);
7973 mTracks.add(record);
7974}
7975
Mikhail Naganov444ecc32018-05-01 17:40:05 -07007976void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07007977{
7978 Mutex::Autolock _l(mLock);
7979 destroyTrack_l(record);
7980}
7981
Mikhail Naganovdc769682018-05-04 15:34:08 -07007982void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07007983{
Mikhail Naganovdc769682018-05-04 15:34:08 -07007984 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07007985 config->role = AUDIO_PORT_ROLE_SINK;
7986 config->ext.mix.hw_module = mInput->audioHwDev->handle();
7987 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07007988 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
7989 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
7990 config->flags.input = mInput->flags;
7991 }
Eric Laurent83b88082014-06-20 18:31:16 -07007992}
Eric Laurent1c333e22014-05-20 10:48:17 -07007993
Eric Laurent6acd1d42017-01-04 14:23:29 -08007994// ----------------------------------------------------------------------------
7995// Mmap
7996// ----------------------------------------------------------------------------
7997
7998AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
7999 : mThread(thread)
8000{
Phil Burk9fabbf82017-08-03 12:02:00 -07008001 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008002}
8003
8004AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8005{
Phil Burk9fabbf82017-08-03 12:02:00 -07008006 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008007}
8008
8009status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8010 struct audio_mmap_buffer_info *info)
8011{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008012 return mThread->createMmapBuffer(minSizeFrames, info);
8013}
8014
8015status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8016{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008017 return mThread->getMmapPosition(position);
8018}
8019
Eric Laurenta54f1282017-07-01 19:39:32 -07008020status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008021 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008022
8023{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008024 return mThread->start(client, handle);
8025}
8026
8027status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8028{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008029 return mThread->stop(handle);
8030}
8031
Eric Laurent18b57012017-02-13 16:23:52 -08008032status_t AudioFlinger::MmapThreadHandle::standby()
8033{
Eric Laurent18b57012017-02-13 16:23:52 -08008034 return mThread->standby();
8035}
8036
Eric Laurent6acd1d42017-01-04 14:23:29 -08008037
8038AudioFlinger::MmapThread::MmapThread(
8039 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8040 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8041 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8042 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008043 mSessionId(AUDIO_SESSION_NONE),
8044 mDeviceId(AUDIO_PORT_HANDLE_NONE), mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008045 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008046 mActiveTracks(&this->mLocalLog),
8047 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8048 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008049{
Eric Laurent18b57012017-02-13 16:23:52 -08008050 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008051 readHalParameters_l();
8052}
8053
8054AudioFlinger::MmapThread::~MmapThread()
8055{
Eric Laurent18b57012017-02-13 16:23:52 -08008056 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008057}
8058
8059void AudioFlinger::MmapThread::onFirstRef()
8060{
8061 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8062}
8063
8064void AudioFlinger::MmapThread::disconnect()
8065{
Eric Laurent331679c2018-04-16 17:03:16 -07008066 ActiveTracks<MmapTrack> activeTracks;
8067 {
8068 Mutex::Autolock _l(mLock);
8069 for (const sp<MmapTrack> &t : mActiveTracks) {
8070 activeTracks.add(t);
8071 }
8072 }
8073 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008074 stop(t->portId());
8075 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008076 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008077 if (isOutput()) {
8078 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
8079 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008080 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008081 }
8082}
8083
8084
8085void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8086 audio_stream_type_t streamType __unused,
8087 audio_session_t sessionId,
8088 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008089 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008090 audio_port_handle_t portId)
8091{
8092 mAttr = *attr;
8093 mSessionId = sessionId;
8094 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008095 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008096 mPortId = portId;
8097}
8098
8099status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8100 struct audio_mmap_buffer_info *info)
8101{
8102 if (mHalStream == 0) {
8103 return NO_INIT;
8104 }
Eric Laurent18b57012017-02-13 16:23:52 -08008105 mStandby = true;
8106 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008107 return mHalStream->createMmapBuffer(minSizeFrames, info);
8108}
8109
8110status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8111{
8112 if (mHalStream == 0) {
8113 return NO_INIT;
8114 }
8115 return mHalStream->getMmapPosition(position);
8116}
8117
Eric Laurent331679c2018-04-16 17:03:16 -07008118status_t AudioFlinger::MmapThread::exitStandby()
8119{
8120 status_t ret = mHalStream->start();
8121 if (ret != NO_ERROR) {
8122 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8123 return ret;
8124 }
8125 mStandby = false;
8126 return NO_ERROR;
8127}
8128
Eric Laurenta54f1282017-07-01 19:39:32 -07008129status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008130 audio_port_handle_t *handle)
8131{
Eric Laurenta54f1282017-07-01 19:39:32 -07008132 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8133 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008134 if (mHalStream == 0) {
8135 return NO_INIT;
8136 }
8137
8138 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008139
Eric Laurenta54f1282017-07-01 19:39:32 -07008140 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008141 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008142 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008143 }
8144
8145 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8146
8147 audio_io_handle_t io = mId;
8148 if (isOutput()) {
8149 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8150 config.sample_rate = mSampleRate;
8151 config.channel_mask = mChannelMask;
8152 config.format = mFormat;
8153 audio_stream_type_t stream = streamType();
8154 audio_output_flags_t flags =
8155 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008156 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008157 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8158 mSessionId,
8159 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008160 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008161 client.clientUid,
8162 &config,
8163 flags,
8164 &deviceId,
8165 &portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008166 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008167 audio_config_base_t config;
8168 config.sample_rate = mSampleRate;
8169 config.channel_mask = mChannelMask;
8170 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008171 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008172 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8173 mSessionId,
8174 client.clientPid,
8175 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008176 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008177 &config,
8178 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8179 &deviceId,
8180 &portId);
8181 }
8182 // APM should not chose a different input or output stream for the same set of attributes
8183 // and audo configuration
8184 if (ret != NO_ERROR || io != mId) {
8185 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8186 __FUNCTION__, ret, io, mId);
8187 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008188 }
8189
Eric Laurent331679c2018-04-16 17:03:16 -07008190 bool silenced = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008191 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008192 ret = AudioSystem::startOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008193 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008194 ret = AudioSystem::startInput(portId, &silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008195 }
8196
Eric Laurent331679c2018-04-16 17:03:16 -07008197 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008198 // abort if start is rejected by audio policy manager
8199 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008200 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008201 if (mActiveTracks.size() != 0) {
Eric Laurent331679c2018-04-16 17:03:16 -07008202 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008203 if (isOutput()) {
Eric Laurenta54f1282017-07-01 19:39:32 -07008204 AudioSystem::releaseOutput(mId, streamType(), mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008205 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008206 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008207 }
Eric Laurent331679c2018-04-16 17:03:16 -07008208 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008209 } else {
8210 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008211 }
8212 return PERMISSION_DENIED;
8213 }
8214
Eric Laurent67f97292018-04-20 18:05:41 -07008215 if (isOutput()) {
8216 // force volume update when a new track is added
8217 mHalVolFloat = -1.0f;
8218 } else if (!silenced) {
Eric Laurent331679c2018-04-16 17:03:16 -07008219 for (const sp<MmapTrack> &track : mActiveTracks) {
8220 if (track->isSilenced_l() && track->uid() != client.clientUid)
8221 track->invalidate();
8222 }
8223 }
8224
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008225 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8226 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008227 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008228
Eric Laurent331679c2018-04-16 17:03:16 -07008229 track->setSilenced_l(silenced);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008230 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008231 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008232 if (chain != 0) {
8233 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8234 chain->incTrackCnt();
8235 chain->incActiveTrackCnt();
8236 }
8237
8238 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008239 broadcast_l();
8240
Eric Laurenta54f1282017-07-01 19:39:32 -07008241 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008242
8243 return NO_ERROR;
8244}
8245
8246status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8247{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008248 ALOGV("%s handle %d", __FUNCTION__, handle);
8249
8250 if (mHalStream == 0) {
8251 return NO_INIT;
8252 }
8253
Eric Laurenta54f1282017-07-01 19:39:32 -07008254 if (handle == mPortId) {
8255 mHalStream->stop();
8256 return NO_ERROR;
8257 }
8258
Eric Laurent331679c2018-04-16 17:03:16 -07008259 Mutex::Autolock _l(mLock);
8260
Eric Laurent6acd1d42017-01-04 14:23:29 -08008261 sp<MmapTrack> track;
8262 for (const sp<MmapTrack> &t : mActiveTracks) {
8263 if (handle == t->portId()) {
8264 track = t;
8265 break;
8266 }
8267 }
8268 if (track == 0) {
8269 return BAD_VALUE;
8270 }
8271
8272 mActiveTracks.remove(track);
8273
Eric Laurent331679c2018-04-16 17:03:16 -07008274 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008275 if (isOutput()) {
8276 AudioSystem::stopOutput(mId, streamType(), track->sessionId());
Eric Laurenta54f1282017-07-01 19:39:32 -07008277 AudioSystem::releaseOutput(mId, streamType(), track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008278 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008279 AudioSystem::stopInput(track->portId());
8280 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008281 }
Eric Laurent331679c2018-04-16 17:03:16 -07008282 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008283
8284 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8285 if (chain != 0) {
8286 chain->decActiveTrackCnt();
8287 chain->decTrackCnt();
8288 }
8289
8290 broadcast_l();
8291
Eric Laurent6acd1d42017-01-04 14:23:29 -08008292 return NO_ERROR;
8293}
8294
Eric Laurent18b57012017-02-13 16:23:52 -08008295status_t AudioFlinger::MmapThread::standby()
8296{
8297 ALOGV("%s", __FUNCTION__);
8298
8299 if (mHalStream == 0) {
8300 return NO_INIT;
8301 }
8302 if (mActiveTracks.size() != 0) {
8303 return INVALID_OPERATION;
8304 }
8305 mHalStream->standby();
8306 mStandby = true;
8307 releaseWakeLock();
8308 return NO_ERROR;
8309}
8310
Eric Laurent6acd1d42017-01-04 14:23:29 -08008311
8312void AudioFlinger::MmapThread::readHalParameters_l()
8313{
8314 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8315 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8316 mFormat = mHALFormat;
8317 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8318 result = mHalStream->getFrameSize(&mFrameSize);
8319 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8320 result = mHalStream->getBufferSize(&mBufferSize);
8321 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8322 mFrameCount = mBufferSize / mFrameSize;
8323}
8324
8325bool AudioFlinger::MmapThread::threadLoop()
8326{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008327 checkSilentMode_l();
8328
8329 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8330
8331 while (!exitPending())
8332 {
8333 Mutex::Autolock _l(mLock);
8334 Vector< sp<EffectChain> > effectChains;
8335
8336 if (mSignalPending) {
8337 // A signal was raised while we were unlocked
8338 mSignalPending = false;
8339 } else {
8340 if (mConfigEvents.isEmpty()) {
8341 // we're about to wait, flush the binder command buffer
8342 IPCThreadState::self()->flushCommands();
8343
8344 if (exitPending()) {
8345 break;
8346 }
8347
Eric Laurent6acd1d42017-01-04 14:23:29 -08008348 // wait until we have something to do...
8349 ALOGV("%s going to sleep", myName.string());
8350 mWaitWorkCV.wait(mLock);
8351 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008352
8353 checkSilentMode_l();
8354
8355 continue;
8356 }
8357 }
8358
8359 processConfigEvents_l();
8360
8361 processVolume_l();
8362
8363 checkInvalidTracks_l();
8364
8365 mActiveTracks.updatePowerState(this);
8366
Kevin Rocard069c2712018-03-29 19:09:14 -07008367 updateMetadata_l();
8368
Eric Laurent6acd1d42017-01-04 14:23:29 -08008369 lockEffectChains_l(effectChains);
8370 for (size_t i = 0; i < effectChains.size(); i ++) {
8371 effectChains[i]->process_l();
8372 }
8373 // enable changes in effect chain
8374 unlockEffectChains(effectChains);
8375 // Effect chains will be actually deleted here if they were removed from
8376 // mEffectChains list during mixing or effects processing
8377 }
8378
8379 threadLoop_exit();
8380
8381 if (!mStandby) {
8382 threadLoop_standby();
8383 mStandby = true;
8384 }
8385
Eric Laurent6acd1d42017-01-04 14:23:29 -08008386 ALOGV("Thread %p type %d exiting", this, mType);
8387 return false;
8388}
8389
8390// checkForNewParameter_l() must be called with ThreadBase::mLock held
8391bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8392 status_t& status)
8393{
8394 AudioParameter param = AudioParameter(keyValuePair);
8395 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008396 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008397 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008398 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008399 // forward device change to effects that have requested to be
8400 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008401 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008402 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008403 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008404 }
8405 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008406 if (audio_is_output_devices(device)) {
8407 mOutDevice = device;
8408 if (!isOutput()) {
8409 sendToHal = false;
8410 }
8411 } else {
8412 mInDevice = device;
8413 if (device != AUDIO_DEVICE_NONE) {
8414 mPrevInDevice = value;
8415 }
8416 // TODO: implement and call checkBtNrec_l();
8417 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008418 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008419 if (sendToHal) {
8420 status = mHalStream->setParameters(keyValuePair);
8421 } else {
8422 status = NO_ERROR;
8423 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008424
8425 return false;
8426}
8427
8428String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8429{
8430 Mutex::Autolock _l(mLock);
8431 String8 out_s8;
8432 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8433 return out_s8;
8434 }
8435 return String8();
8436}
8437
8438void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8439 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8440
8441 desc->mIoHandle = mId;
8442
8443 switch (event) {
8444 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008445 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008446 case AUDIO_INPUT_CONFIG_CHANGED:
8447 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008448 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008449 case AUDIO_OUTPUT_CONFIG_CHANGED:
8450 desc->mPatch = mPatch;
8451 desc->mChannelMask = mChannelMask;
8452 desc->mSamplingRate = mSampleRate;
8453 desc->mFormat = mFormat;
8454 desc->mFrameCount = mFrameCount;
8455 desc->mFrameCountHAL = mFrameCount;
8456 desc->mLatency = 0;
8457 break;
8458
8459 case AUDIO_INPUT_CLOSED:
8460 case AUDIO_OUTPUT_CLOSED:
8461 default:
8462 break;
8463 }
8464 mAudioFlinger->ioConfigChanged(event, desc, pid);
8465}
8466
8467status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8468 audio_patch_handle_t *handle)
8469{
8470 status_t status = NO_ERROR;
8471
8472 // store new device and send to effects
8473 audio_devices_t type = AUDIO_DEVICE_NONE;
8474 audio_port_handle_t deviceId;
8475 if (isOutput()) {
8476 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8477 type |= patch->sinks[i].ext.device.type;
8478 }
8479 deviceId = patch->sinks[0].id;
8480 } else {
8481 type = patch->sources[0].ext.device.type;
8482 deviceId = patch->sources[0].id;
8483 }
8484
8485 for (size_t i = 0; i < mEffectChains.size(); i++) {
8486 mEffectChains[i]->setDevice_l(type);
8487 }
8488
8489 if (isOutput()) {
8490 mOutDevice = type;
8491 } else {
8492 mInDevice = type;
8493 // store new source and send to effects
8494 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8495 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8496 for (size_t i = 0; i < mEffectChains.size(); i++) {
8497 mEffectChains[i]->setAudioSource_l(mAudioSource);
8498 }
8499 }
8500 }
8501
8502 if (mAudioHwDev->supportsAudioPatches()) {
8503 status = mHalDevice->createAudioPatch(patch->num_sources,
8504 patch->sources,
8505 patch->num_sinks,
8506 patch->sinks,
8507 handle);
8508 } else {
8509 char *address;
8510 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8511 //FIXME: we only support address on first sink with HAL version < 3.0
8512 address = audio_device_address_to_parameter(
8513 patch->sinks[0].ext.device.type,
8514 patch->sinks[0].ext.device.address);
8515 } else {
8516 address = (char *)calloc(1, 1);
8517 }
8518 AudioParameter param = AudioParameter(String8(address));
8519 free(address);
8520 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8521 if (!isOutput()) {
8522 param.addInt(String8(AudioParameter::keyInputSource),
8523 (int)patch->sinks[0].ext.mix.usecase.source);
8524 }
8525 status = mHalStream->setParameters(param.toString());
8526 *handle = AUDIO_PATCH_HANDLE_NONE;
8527 }
8528
8529 if (isOutput() && mPrevOutDevice != mOutDevice) {
8530 mPrevOutDevice = type;
8531 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008532 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008533 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008534 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008535 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008536 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008537 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008538 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008539 }
8540 if (!isOutput() && mPrevInDevice != mInDevice) {
8541 mPrevInDevice = type;
8542 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008543 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008544 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008545 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008546 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008547 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008548 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008549 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008550 }
8551 return status;
8552}
8553
8554status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8555{
8556 status_t status = NO_ERROR;
8557
8558 mInDevice = AUDIO_DEVICE_NONE;
8559
8560 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8561 supportsAudioPatches : false;
8562
8563 if (supportsAudioPatches) {
8564 status = mHalDevice->releaseAudioPatch(handle);
8565 } else {
8566 AudioParameter param;
8567 param.addInt(String8(AudioParameter::keyRouting), 0);
8568 status = mHalStream->setParameters(param.toString());
8569 }
8570 return status;
8571}
8572
Mikhail Naganovdc769682018-05-04 15:34:08 -07008573void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008574{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008575 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008576 if (isOutput()) {
8577 config->role = AUDIO_PORT_ROLE_SOURCE;
8578 config->ext.mix.hw_module = mAudioHwDev->handle();
8579 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8580 } else {
8581 config->role = AUDIO_PORT_ROLE_SINK;
8582 config->ext.mix.hw_module = mAudioHwDev->handle();
8583 config->ext.mix.usecase.source = mAudioSource;
8584 }
8585}
8586
8587status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8588{
8589 audio_session_t session = chain->sessionId();
8590
8591 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8592 // Attach all tracks with same session ID to this chain.
8593 // indicate all active tracks in the chain
8594 for (const sp<MmapTrack> &track : mActiveTracks) {
8595 if (session == track->sessionId()) {
8596 chain->incTrackCnt();
8597 chain->incActiveTrackCnt();
8598 }
8599 }
8600
8601 chain->setThread(this);
8602 chain->setInBuffer(nullptr);
8603 chain->setOutBuffer(nullptr);
8604 chain->syncHalEffectsState();
8605
8606 mEffectChains.add(chain);
8607 checkSuspendOnAddEffectChain_l(chain);
8608 return NO_ERROR;
8609}
8610
8611size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8612{
8613 audio_session_t session = chain->sessionId();
8614
8615 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8616
8617 for (size_t i = 0; i < mEffectChains.size(); i++) {
8618 if (chain == mEffectChains[i]) {
8619 mEffectChains.removeAt(i);
8620 // detach all active tracks from the chain
8621 // detach all tracks with same session ID from this chain
8622 for (const sp<MmapTrack> &track : mActiveTracks) {
8623 if (session == track->sessionId()) {
8624 chain->decActiveTrackCnt();
8625 chain->decTrackCnt();
8626 }
8627 }
8628 break;
8629 }
8630 }
8631 return mEffectChains.size();
8632}
8633
8634// hasAudioSession_l() must be called with ThreadBase::mLock held
8635uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8636{
8637 uint32_t result = 0;
8638 if (getEffectChain_l(sessionId) != 0) {
8639 result = EFFECT_SESSION;
8640 }
8641
8642 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8643 sp<MmapTrack> track = mActiveTracks[i];
8644 if (sessionId == track->sessionId()) {
8645 result |= TRACK_SESSION;
8646 if (track->isFastTrack()) {
8647 result |= FAST_SESSION;
8648 }
8649 break;
8650 }
8651 }
8652
8653 return result;
8654}
8655
8656void AudioFlinger::MmapThread::threadLoop_standby()
8657{
8658 mHalStream->standby();
8659}
8660
8661void AudioFlinger::MmapThread::threadLoop_exit()
8662{
Phil Burk7dce7282017-09-27 13:51:41 -07008663 // Do not call callback->onTearDown() because it is redundant for thread exit
8664 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008665}
8666
8667status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8668{
8669 return BAD_VALUE;
8670}
8671
8672bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8673{
8674 return false;
8675}
8676
8677status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8678 const effect_descriptor_t *desc, audio_session_t sessionId)
8679{
8680 // No global effect sessions on mmap threads
8681 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8682 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8683 desc->name, mThreadName);
8684 return BAD_VALUE;
8685 }
8686
8687 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
8688 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
8689 desc->name);
8690 return BAD_VALUE;
8691 }
8692 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08008693 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
8694 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008695 return BAD_VALUE;
8696 }
8697
8698 // Only allow effects without processing load or latency
8699 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
8700 return BAD_VALUE;
8701 }
8702
8703 return NO_ERROR;
8704
8705}
8706
8707void AudioFlinger::MmapThread::checkInvalidTracks_l()
8708{
8709 for (const sp<MmapTrack> &track : mActiveTracks) {
8710 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008711 sp<MmapStreamCallback> callback = mCallback.promote();
8712 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008713 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07008714 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07008715 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07008716 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8717 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
8718 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008719 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008720 }
8721 }
8722}
8723
8724void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
8725{
8726 dumpInternals(fd, args);
8727 dumpTracks(fd, args);
8728 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008729 dprintf(fd, " Local log:\n");
8730 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008731}
8732
8733void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
8734{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008735 dumpBase(fd, args);
8736
8737 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
8738 mAttr.content_type, mAttr.usage, mAttr.source);
8739 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
8740 if (mActiveTracks.size() == 0) {
8741 dprintf(fd, " No active clients\n");
8742 }
8743}
8744
8745void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
8746{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008747 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008748 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008749 dprintf(fd, " %zu Tracks\n", numtracks);
8750 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08008751 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008752 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008753 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008754 for (size_t i = 0; i < numtracks ; ++i) {
8755 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008756 result.append(prefix);
8757 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008758 }
8759 } else {
8760 dprintf(fd, "\n");
8761 }
8762 write(fd, result.string(), result.size());
8763}
8764
8765AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
8766 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8767 AudioHwDevice *hwDev, AudioStreamOut *output,
8768 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8769 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
8770 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008771 mStreamVolume(1.0),
8772 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07008773 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008774{
8775 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
8776 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
8777 mMasterVolume = audioFlinger->masterVolume_l();
8778 mMasterMute = audioFlinger->masterMute_l();
8779 if (mAudioHwDev) {
8780 if (mAudioHwDev->canSetMasterVolume()) {
8781 mMasterVolume = 1.0;
8782 }
8783
8784 if (mAudioHwDev->canSetMasterMute()) {
8785 mMasterMute = false;
8786 }
8787 }
8788}
8789
8790void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
8791 audio_stream_type_t streamType,
8792 audio_session_t sessionId,
8793 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008794 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008795 audio_port_handle_t portId)
8796{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008797 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008798 mStreamType = streamType;
8799}
8800
8801AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
8802{
8803 Mutex::Autolock _l(mLock);
8804 AudioStreamOut *output = mOutput;
8805 mOutput = NULL;
8806 return output;
8807}
8808
8809void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
8810{
8811 Mutex::Autolock _l(mLock);
8812 // Don't apply master volume in SW if our HAL can do it for us.
8813 if (mAudioHwDev &&
8814 mAudioHwDev->canSetMasterVolume()) {
8815 mMasterVolume = 1.0;
8816 } else {
8817 mMasterVolume = value;
8818 }
8819}
8820
8821void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
8822{
8823 Mutex::Autolock _l(mLock);
8824 // Don't apply master mute in SW if our HAL can do it for us.
8825 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
8826 mMasterMute = false;
8827 } else {
8828 mMasterMute = muted;
8829 }
8830}
8831
8832void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
8833{
8834 Mutex::Autolock _l(mLock);
8835 if (stream == mStreamType) {
8836 mStreamVolume = value;
8837 broadcast_l();
8838 }
8839}
8840
8841float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
8842{
8843 Mutex::Autolock _l(mLock);
8844 if (stream == mStreamType) {
8845 return mStreamVolume;
8846 }
8847 return 0.0f;
8848}
8849
8850void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
8851{
8852 Mutex::Autolock _l(mLock);
8853 if (stream == mStreamType) {
8854 mStreamMute= muted;
8855 broadcast_l();
8856 }
8857}
8858
8859void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
8860{
8861 Mutex::Autolock _l(mLock);
8862 if (streamType == mStreamType) {
8863 for (const sp<MmapTrack> &track : mActiveTracks) {
8864 track->invalidate();
8865 }
8866 broadcast_l();
8867 }
8868}
8869
8870void AudioFlinger::MmapPlaybackThread::processVolume_l()
8871{
8872 float volume;
8873
8874 if (mMasterMute || mStreamMute) {
8875 volume = 0;
8876 } else {
8877 volume = mMasterVolume * mStreamVolume;
8878 }
8879
8880 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008881
8882 // Convert volumes from float to 8.24
8883 uint32_t vol = (uint32_t)(volume * (1 << 24));
8884
8885 // Delegate volume control to effect in track effect chain if needed
8886 // only one effect chain can be present on DirectOutputThread, so if
8887 // there is one, the track is connected to it
8888 if (!mEffectChains.isEmpty()) {
8889 mEffectChains[0]->setVolume_l(&vol, &vol);
8890 volume = (float)vol / (1 << 24);
8891 }
Eric Laurentdff774a2017-04-21 15:29:38 -07008892 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07008893 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
8894 mHalVolFloat = volume; // HW volume control worked, so update value.
8895 mNoCallbackWarningCount = 0;
8896 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07008897 sp<MmapStreamCallback> callback = mCallback.promote();
8898 if (callback != 0) {
8899 int channelCount;
8900 if (isOutput()) {
8901 channelCount = audio_channel_count_from_out_mask(mChannelMask);
8902 } else {
8903 channelCount = audio_channel_count_from_in_mask(mChannelMask);
8904 }
8905 Vector<float> values;
8906 for (int i = 0; i < channelCount; i++) {
8907 values.add(volume);
8908 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07008909 mHalVolFloat = volume; // SW volume control worked, so update value.
8910 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07008911 mLock.unlock();
8912 callback->onVolumeChanged(mChannelMask, values);
8913 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008914 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07008915 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
8916 ALOGW("Could not set MMAP stream volume: no volume callback!");
8917 mNoCallbackWarningCount++;
8918 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008919 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008920 }
8921 }
8922}
8923
Kevin Rocard069c2712018-03-29 19:09:14 -07008924void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
8925{
8926 if (mOutput == nullptr || mOutput->stream == nullptr ||
8927 !mActiveTracks.readAndClearHasChanged()) {
8928 return;
8929 }
8930 StreamOutHalInterface::SourceMetadata metadata;
8931 for (const sp<MmapTrack> &track : mActiveTracks) {
8932 // No track is invalid as this is called after prepareTrack_l in the same critical section
8933 metadata.tracks.push_back({
8934 .usage = track->attributes().usage,
8935 .content_type = track->attributes().content_type,
8936 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
8937 });
8938 }
8939 mOutput->stream->updateSourceMetadata(metadata);
8940}
8941
Eric Laurent6acd1d42017-01-04 14:23:29 -08008942void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
8943{
8944 if (!mMasterMute) {
8945 char value[PROPERTY_VALUE_MAX];
8946 if (property_get("ro.audio.silent", value, "0") > 0) {
8947 char *endptr;
8948 unsigned long ul = strtoul(value, &endptr, 0);
8949 if (*endptr == '\0' && ul != 0) {
8950 ALOGD("Silence is golden");
8951 // The setprop command will not allow a property to be changed after
8952 // the first time it is set, so we don't have to worry about un-muting.
8953 setMasterMute_l(true);
8954 }
8955 }
8956 }
8957}
8958
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008959void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
8960{
8961 MmapThread::toAudioPortConfig(config);
8962 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
8963 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8964 config->flags.output = mOutput->flags;
8965 }
8966}
8967
Eric Laurent6acd1d42017-01-04 14:23:29 -08008968void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
8969{
8970 MmapThread::dumpInternals(fd, args);
8971
Glenn Kastend3bb6452016-12-05 18:14:37 -08008972 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
8973 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008974 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
8975}
8976
8977AudioFlinger::MmapCaptureThread::MmapCaptureThread(
8978 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8979 AudioHwDevice *hwDev, AudioStreamIn *input,
8980 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8981 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
8982 mInput(input)
8983{
8984 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
8985 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8986}
8987
Eric Laurent331679c2018-04-16 17:03:16 -07008988status_t AudioFlinger::MmapCaptureThread::exitStandby()
8989{
8990 mInput->stream->setGain(1.0f);
8991 return MmapThread::exitStandby();
8992}
8993
Eric Laurent6acd1d42017-01-04 14:23:29 -08008994AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
8995{
8996 Mutex::Autolock _l(mLock);
8997 AudioStreamIn *input = mInput;
8998 mInput = NULL;
8999 return input;
9000}
Kevin Rocard069c2712018-03-29 19:09:14 -07009001
Eric Laurent331679c2018-04-16 17:03:16 -07009002
9003void AudioFlinger::MmapCaptureThread::processVolume_l()
9004{
9005 bool changed = false;
9006 bool silenced = false;
9007
9008 sp<MmapStreamCallback> callback = mCallback.promote();
9009 if (callback == 0) {
9010 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9011 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9012 mNoCallbackWarningCount++;
9013 }
9014 }
9015
9016 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9017 // track is silenced and unmute otherwise
9018 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9019 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9020 changed = true;
9021 silenced = mActiveTracks[i]->isSilenced_l();
9022 }
9023 }
9024
9025 if (changed) {
9026 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9027 }
9028}
9029
Kevin Rocard069c2712018-03-29 19:09:14 -07009030void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9031{
9032 if (mInput == nullptr || mInput->stream == nullptr ||
9033 !mActiveTracks.readAndClearHasChanged()) {
9034 return;
9035 }
9036 StreamInHalInterface::SinkMetadata metadata;
9037 for (const sp<MmapTrack> &track : mActiveTracks) {
9038 // No track is invalid as this is called after prepareTrack_l in the same critical section
9039 metadata.tracks.push_back({
9040 .source = track->attributes().source,
9041 .gain = 1, // capture tracks do not have volumes
9042 });
9043 }
9044 mInput->stream->updateSinkMetadata(metadata);
9045}
9046
Eric Laurent331679c2018-04-16 17:03:16 -07009047void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9048{
9049 Mutex::Autolock _l(mLock);
9050 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9051 if (mActiveTracks[i]->uid() == uid) {
9052 mActiveTracks[i]->setSilenced_l(silenced);
9053 broadcast_l();
9054 }
9055 }
9056}
9057
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009058void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9059{
9060 MmapThread::toAudioPortConfig(config);
9061 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9062 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9063 config->flags.input = mInput->flags;
9064 }
9065}
9066
Glenn Kasten63238ef2015-03-02 15:50:29 -08009067} // namespace android