blob: dd1eabf9a11f2627b98809f49fb5ab13698d80d4 [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>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
27#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031#include <cutils/properties.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070032#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070033#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080034#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070035#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080036#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080037#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038
39#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070040#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010041#include <audio_utils/Balance.h>
jiabin245cdd92018-12-07 17:55:15 -080042#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080043#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080044#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080045#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070046#include <audio_utils/minifloat.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070047#include <system/audio_effects/effect_ns.h>
48#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080050
51// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070052#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053#include <media/nbaio/AudioStreamOutSink.h>
54#include <media/nbaio/MonoPipe.h>
55#include <media/nbaio/MonoPipeReader.h>
56#include <media/nbaio/Pipe.h>
57#include <media/nbaio/PipeReader.h>
58#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080059#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080060
61#include <powermanager/PowerManager.h>
62
Kevin Rocard7588ff42018-01-08 11:11:30 -080063#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070064#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080065
Eric Laurent81784c32012-11-19 14:55:58 -080066#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080067#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070068#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070069#include <mediautils/SchedulingPolicyService.h>
70#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080071
Eric Laurent81784c32012-11-19 14:55:58 -080072#ifdef ADD_BATTERY_DATA
73#include <media/IMediaPlayerService.h>
74#include <media/IMediaDeathNotifier.h>
75#endif
76
Eric Laurent81784c32012-11-19 14:55:58 -080077#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070078#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080079#include <cpustats/ThreadCpuUsage.h>
80#endif
81
Glenn Kastenc05b8d72016-03-24 09:48:17 -070082#include "AutoPark.h"
83
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080084#include <pthread.h>
85#include "TypedLogger.h"
86
Eric Laurent81784c32012-11-19 14:55:58 -080087// ----------------------------------------------------------------------------
88
89// Note: the following macro is used for extremely verbose logging message. In
90// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
91// 0; but one side effect of this is to turn all LOGV's as well. Some messages
92// are so verbose that we want to suppress them even when we have ALOG_ASSERT
93// turned on. Do not uncomment the #def below unless you really know what you
94// are doing and want to see all of the extremely verbose messages.
95//#define VERY_VERY_VERBOSE_LOGGING
96#ifdef VERY_VERY_VERBOSE_LOGGING
97#define ALOGVV ALOGV
98#else
99#define ALOGVV(a...) do { } while(0)
100#endif
101
Andy Hung6770c6f2015-04-07 13:43:36 -0700102// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700103#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700104template <typename T>
105static inline T min(const T& a, const T& b)
106{
107 return a < b ? a : b;
108}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700109
Eric Laurent81784c32012-11-19 14:55:58 -0800110namespace android {
111
112// retry counts for buffer fill timeout
113// 50 * ~20msecs = 1 second
114static const int8_t kMaxTrackRetries = 50;
115static const int8_t kMaxTrackStartupRetries = 50;
116// allow less retry attempts on direct output thread.
117// direct outputs can be a scarce resource in audio hardware and should
118// be released as quickly as possible.
119static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700120
Eric Laurent51716182016-02-29 18:00:56 -0800121
Eric Laurent81784c32012-11-19 14:55:58 -0800122
123// don't warn about blocked writes or record buffer overflows more often than this
124static const nsecs_t kWarningThrottleNs = seconds(5);
125
126// RecordThread loop sleep time upon application overrun or audio HAL read error
127static const int kRecordThreadSleepUs = 5000;
128
Eric Laurent10351942014-05-08 18:49:52 -0700129// maximum time to wait in sendConfigEvent_l() for a status to be received
130static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800131
132// minimum sleep time for the mixer thread loop when tracks are active but in underrun
133static const uint32_t kMinThreadSleepTimeUs = 5000;
134// maximum divider applied to the active sleep time in the mixer thread loop
135static const uint32_t kMaxThreadSleepTimeShift = 2;
136
Andy Hung09a50072014-02-27 14:30:47 -0800137// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700138// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800139static const uint32_t kMinNormalSinkBufferSizeMs = 20;
140// maximum normal sink buffer size
141static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800142
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700143// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
144// FIXME This should be based on experimentally observed scheduling jitter
145static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
146
Eric Laurent972a1732013-09-04 09:42:59 -0700147// Offloaded output thread standby delay: allows track transition without going to standby
148static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
149
Eric Laurent51716182016-02-29 18:00:56 -0800150// Direct output thread minimum sleep time in idle or active(underrun) state
151static const nsecs_t kDirectMinSleepTimeUs = 10000;
152
Glenn Kasten1b291842016-07-18 14:55:21 -0700153// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
154// balance between power consumption and latency, and allows threads to be scheduled reliably
155// by the CFS scheduler.
156// FIXME Express other hardcoded references to 20ms with references to this constant and move
157// it appropriately.
158#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800159
Eric Laurent81784c32012-11-19 14:55:58 -0800160// Whether to use fast mixer
161static const enum {
162 FastMixer_Never, // never initialize or use: for debugging only
163 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
164 // normal mixer multiplier is 1
165 FastMixer_Static, // initialize if needed, then use all the time if initialized,
166 // multiplier is calculated based on min & max normal mixer buffer size
167 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
168 // multiplier is calculated based on min & max normal mixer buffer size
169 // FIXME for FastMixer_Dynamic:
170 // Supporting this option will require fixing HALs that can't handle large writes.
171 // For example, one HAL implementation returns an error from a large write,
172 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
173 // We could either fix the HAL implementations, or provide a wrapper that breaks
174 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
175} kUseFastMixer = FastMixer_Static;
176
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700177// Whether to use fast capture
178static const enum {
179 FastCapture_Never, // never initialize or use: for debugging only
180 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
181 FastCapture_Static, // initialize if needed, then use all the time if initialized
182} kUseFastCapture = FastCapture_Static;
183
Eric Laurent81784c32012-11-19 14:55:58 -0800184// Priorities for requestPriority
185static const int kPriorityAudioApp = 2;
186static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700187static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800188
Glenn Kastenea38ee72016-04-18 11:08:01 -0700189// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
190// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
191// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700192
193// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800194static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800195
Glenn Kasten03490092014-05-27 12:30:54 -0700196// The minimum and maximum allowed values
197static const int kFastTrackMultiplierMin = 1;
198static const int kFastTrackMultiplierMax = 2;
199
200// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
201static int sFastTrackMultiplier = kFastTrackMultiplier;
202
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700203// See Thread::readOnlyHeap().
204// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
205// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
206// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700207static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700208
Eric Laurent81784c32012-11-19 14:55:58 -0800209// ----------------------------------------------------------------------------
210
Glenn Kasten03490092014-05-27 12:30:54 -0700211static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
212
213static void sFastTrackMultiplierInit()
214{
215 char value[PROPERTY_VALUE_MAX];
216 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
217 char *endptr;
218 unsigned long ul = strtoul(value, &endptr, 0);
219 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
220 sFastTrackMultiplier = (int) ul;
221 }
222 }
223}
224
225// ----------------------------------------------------------------------------
226
Eric Laurent81784c32012-11-19 14:55:58 -0800227#ifdef ADD_BATTERY_DATA
228// To collect the amplifier usage
229static void addBatteryData(uint32_t params) {
230 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
231 if (service == NULL) {
232 // it already logged
233 return;
234 }
235
236 service->addBatteryData(params);
237}
238#endif
239
Andy Hung3f0c9022016-01-15 17:49:46 -0800240// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
241struct {
242 // call when you acquire a partial wakelock
243 void acquire(const sp<IBinder> &wakeLockToken) {
244 pthread_mutex_lock(&mLock);
245 if (wakeLockToken.get() == nullptr) {
246 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
247 } else {
248 if (mCount == 0) {
249 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
250 }
251 ++mCount;
252 }
253 pthread_mutex_unlock(&mLock);
254 }
255
256 // call when you release a partial wakelock.
257 void release(const sp<IBinder> &wakeLockToken) {
258 if (wakeLockToken.get() == nullptr) {
259 return;
260 }
261 pthread_mutex_lock(&mLock);
262 if (--mCount < 0) {
263 ALOGE("negative wakelock count");
264 mCount = 0;
265 }
266 pthread_mutex_unlock(&mLock);
267 }
268
269 // retrieves the boottime timebase offset from monotonic.
270 int64_t getBoottimeOffset() {
271 pthread_mutex_lock(&mLock);
272 int64_t boottimeOffset = mBoottimeOffset;
273 pthread_mutex_unlock(&mLock);
274 return boottimeOffset;
275 }
276
277 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
278 // and the selected timebase.
279 // Currently only TIMEBASE_BOOTTIME is allowed.
280 //
281 // This only needs to be called upon acquiring the first partial wakelock
282 // after all other partial wakelocks are released.
283 //
284 // We do an empirical measurement of the offset rather than parsing
285 // /proc/timer_list since the latter is not a formal kernel ABI.
286 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
287 int clockbase;
288 switch (timebase) {
289 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
290 clockbase = SYSTEM_TIME_BOOTTIME;
291 break;
292 default:
293 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
294 break;
295 }
296 // try three times to get the clock offset, choose the one
297 // with the minimum gap in measurements.
298 const int tries = 3;
299 nsecs_t bestGap, measured;
300 for (int i = 0; i < tries; ++i) {
301 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
302 const nsecs_t tbase = systemTime(clockbase);
303 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
304 const nsecs_t gap = tmono2 - tmono;
305 if (i == 0 || gap < bestGap) {
306 bestGap = gap;
307 measured = tbase - ((tmono + tmono2) >> 1);
308 }
309 }
310
311 // to avoid micro-adjusting, we don't change the timebase
312 // unless it is significantly different.
313 //
314 // Assumption: It probably takes more than toleranceNs to
315 // suspend and resume the device.
316 static int64_t toleranceNs = 10000; // 10 us
317 if (llabs(*offset - measured) > toleranceNs) {
318 ALOGV("Adjusting timebase offset old: %lld new: %lld",
319 (long long)*offset, (long long)measured);
320 *offset = measured;
321 }
322 }
323
324 pthread_mutex_t mLock;
325 int32_t mCount;
326 int64_t mBoottimeOffset;
327} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800328
329// ----------------------------------------------------------------------------
330// CPU Stats
331// ----------------------------------------------------------------------------
332
333class CpuStats {
334public:
335 CpuStats();
336 void sample(const String8 &title);
337#ifdef DEBUG_CPU_USAGE
338private:
339 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700340 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800341
Andy Hung16698b82018-08-01 10:48:38 -0700342 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800343
344 int mCpuNum; // thread's current CPU number
345 int mCpukHz; // frequency of thread's current CPU in kHz
346#endif
347};
348
349CpuStats::CpuStats()
350#ifdef DEBUG_CPU_USAGE
351 : mCpuNum(-1), mCpukHz(-1)
352#endif
353{
354}
355
Glenn Kasten0f11b512014-01-31 16:18:54 -0800356void CpuStats::sample(const String8 &title
357#ifndef DEBUG_CPU_USAGE
358 __unused
359#endif
360 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800361#ifdef DEBUG_CPU_USAGE
362 // get current thread's delta CPU time in wall clock ns
363 double wcNs;
364 bool valid = mCpuUsage.sampleAndEnable(wcNs);
365
366 // record sample for wall clock statistics
367 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700368 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800369 }
370
371 // get the current CPU number
372 int cpuNum = sched_getcpu();
373
374 // get the current CPU frequency in kHz
375 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
376
377 // check if either CPU number or frequency changed
378 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
379 mCpuNum = cpuNum;
380 mCpukHz = cpukHz;
381 // ignore sample for purposes of cycles
382 valid = false;
383 }
384
385 // if no change in CPU number or frequency, then record sample for cycle statistics
386 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700387 const double cycles = wcNs * cpukHz * 0.000001;
388 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800389 }
390
Eric Tan5b13ff82018-07-27 11:20:17 -0700391 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800392 // mCpuUsage.elapsed() is expensive, so don't call it every loop
393 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700394 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800395 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700396 const double perLoop = elapsed / (double) n;
397 const double perLoop100 = perLoop * 0.01;
398 const double perLoop1k = perLoop * 0.001;
399 const double mean = mWcStats.getMean();
400 const double stddev = mWcStats.getStdDev();
401 const double minimum = mWcStats.getMin();
402 const double maximum = mWcStats.getMax();
403 const double meanCycles = mHzStats.getMean();
404 const double stddevCycles = mHzStats.getStdDev();
405 const double minCycles = mHzStats.getMin();
406 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800407 mCpuUsage.resetElapsed();
408 mWcStats.reset();
409 mHzStats.reset();
410 ALOGD("CPU usage for %s over past %.1f secs\n"
411 " (%u mixer loops at %.1f mean ms per loop):\n"
412 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
413 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
414 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
415 title.string(),
416 elapsed * .000000001, n, perLoop * .000001,
417 mean * .001,
418 stddev * .001,
419 minimum * .001,
420 maximum * .001,
421 mean / perLoop100,
422 stddev / perLoop100,
423 minimum / perLoop100,
424 maximum / perLoop100,
425 meanCycles / perLoop1k,
426 stddevCycles / perLoop1k,
427 minCycles / perLoop1k,
428 maxCycles / perLoop1k);
429
430 }
431 }
432#endif
433};
434
435// ----------------------------------------------------------------------------
436// ThreadBase
437// ----------------------------------------------------------------------------
438
Glenn Kasten97b7b752014-09-28 13:04:24 -0700439// static
440const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
441{
442 switch (type) {
443 case MIXER:
444 return "MIXER";
445 case DIRECT:
446 return "DIRECT";
447 case DUPLICATING:
448 return "DUPLICATING";
449 case RECORD:
450 return "RECORD";
451 case OFFLOAD:
452 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800453 case MMAP:
454 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700455 default:
456 return "unknown";
457 }
458}
459
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700460std::string devicesToString(audio_devices_t devices)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800461{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700462 std::string result;
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800463 if (devices & AUDIO_DEVICE_BIT_IN) {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700464 InputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800465 } else {
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700466 OutputDeviceConverter::maskToString(devices, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800467 }
468 return result;
469}
470
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700471std::string inputFlagsToString(audio_input_flags_t flags)
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800472{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700473 std::string result;
474 InputFlagConverter::maskToString(flags, result);
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800475 return result;
476}
477
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700478std::string outputFlagsToString(audio_output_flags_t flags)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700479{
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700480 std::string result;
481 OutputFlagConverter::maskToString(flags, result);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700482 return result;
483}
484
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800485const char *sourceToString(audio_source_t source)
486{
487 switch (source) {
488 case AUDIO_SOURCE_DEFAULT: return "default";
489 case AUDIO_SOURCE_MIC: return "mic";
490 case AUDIO_SOURCE_VOICE_UPLINK: return "voice uplink";
491 case AUDIO_SOURCE_VOICE_DOWNLINK: return "voice downlink";
492 case AUDIO_SOURCE_VOICE_CALL: return "voice call";
493 case AUDIO_SOURCE_CAMCORDER: return "camcorder";
494 case AUDIO_SOURCE_VOICE_RECOGNITION: return "voice recognition";
495 case AUDIO_SOURCE_VOICE_COMMUNICATION: return "voice communication";
496 case AUDIO_SOURCE_REMOTE_SUBMIX: return "remote submix";
rago8a397d52015-12-02 11:27:57 -0800497 case AUDIO_SOURCE_UNPROCESSED: return "unprocessed";
Eric Laurentae4b6ec2019-01-15 18:34:38 -0800498 case AUDIO_SOURCE_VOICE_PERFORMANCE: return "voice performance";
499 case AUDIO_SOURCE_ECHO_REFERENCE: return "echo reference";
Glenn Kasten0f5b5622015-02-18 14:33:30 -0800500 case AUDIO_SOURCE_FM_TUNER: return "FM tuner";
501 case AUDIO_SOURCE_HOTWORD: return "hotword";
502 default: return "unknown";
503 }
504}
505
Eric Laurent81784c32012-11-19 14:55:58 -0800506AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -0700507 audio_devices_t outDevice, audio_devices_t inDevice, type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800508 : Thread(false /*canCallJava*/),
509 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700510 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700511 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800512 // are set by PlaybackThread::readOutputParameters_l() or
513 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700514 //FIXME: mStandby should be true here. Is this some kind of hack?
Eric Laurent81784c32012-11-19 14:55:58 -0800515 mStandby(false), mOutDevice(outDevice), mInDevice(inDevice),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700516 mPrevOutDevice(AUDIO_DEVICE_NONE), mPrevInDevice(AUDIO_DEVICE_NONE),
517 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800518 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700519 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800520 mSystemReady(systemReady),
521 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800522{
Eric Laurent296fb132015-05-01 11:38:42 -0700523 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800524}
525
526AudioFlinger::ThreadBase::~ThreadBase()
527{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700528 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700529 mConfigEvents.clear();
530
Eric Laurent81784c32012-11-19 14:55:58 -0800531 // do not lock the mutex in destructor
532 releaseWakeLock_l();
533 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800534 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800535 binder->unlinkToDeath(mDeathRecipient);
536 }
537}
538
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700539status_t AudioFlinger::ThreadBase::readyToRun()
540{
541 status_t status = initCheck();
542 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800543 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700544 } else {
545 ALOGE("No working audio driver found.");
546 }
547 return status;
548}
549
Eric Laurent81784c32012-11-19 14:55:58 -0800550void AudioFlinger::ThreadBase::exit()
551{
552 ALOGV("ThreadBase::exit");
553 // do any cleanup required for exit to succeed
554 preExit();
555 {
556 // This lock prevents the following race in thread (uniprocessor for illustration):
557 // if (!exitPending()) {
558 // // context switch from here to exit()
559 // // exit() calls requestExit(), what exitPending() observes
560 // // exit() calls signal(), which is dropped since no waiters
561 // // context switch back from exit() to here
562 // mWaitWorkCV.wait(...);
563 // // now thread is hung
564 // }
565 AutoMutex lock(mLock);
566 requestExit();
567 mWaitWorkCV.broadcast();
568 }
569 // When Thread::requestExitAndWait is made virtual and this method is renamed to
570 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
571 requestExitAndWait();
572}
573
574status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
575{
Eric Laurent81784c32012-11-19 14:55:58 -0800576 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
577 Mutex::Autolock _l(mLock);
578
Eric Laurent10351942014-05-08 18:49:52 -0700579 return sendSetParameterConfigEvent_l(keyValuePairs);
580}
581
582// sendConfigEvent_l() must be called with ThreadBase::mLock held
583// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
584status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
585{
586 status_t status = NO_ERROR;
587
Eric Laurent72e3f392015-05-20 14:43:50 -0700588 if (event->mRequiresSystemReady && !mSystemReady) {
589 event->mWaitStatus = false;
590 mPendingConfigEvents.add(event);
591 return status;
592 }
Eric Laurent10351942014-05-08 18:49:52 -0700593 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700594 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800595 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700596 mLock.unlock();
597 {
598 Mutex::Autolock _l(event->mLock);
599 while (event->mWaitStatus) {
600 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
601 event->mStatus = TIMED_OUT;
602 event->mWaitStatus = false;
603 }
604 }
605 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800606 }
Eric Laurent10351942014-05-08 18:49:52 -0700607 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800608 return status;
609}
610
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700611void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800612{
613 Mutex::Autolock _l(mLock);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700614 sendIoConfigEvent_l(event, pid);
Eric Laurent81784c32012-11-19 14:55:58 -0800615}
616
617// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700618void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid)
Eric Laurent81784c32012-11-19 14:55:58 -0800619{
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700620 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid);
Eric Laurent10351942014-05-08 18:49:52 -0700621 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800622}
623
Mikhail Naganov83f04272017-02-07 10:45:09 -0800624void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700625{
626 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800627 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700628}
629
Eric Laurent81784c32012-11-19 14:55:58 -0800630// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800631void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
632 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800633{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800634 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700635 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800636}
637
Eric Laurent10351942014-05-08 18:49:52 -0700638// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
639status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800640{
Andy Hung2ddee192015-12-18 17:34:44 -0800641 sp<ConfigEvent> configEvent;
642 AudioParameter param(keyValuePair);
643 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700644 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800645 setMasterMono_l(value != 0);
646 if (param.size() == 1) {
647 return NO_ERROR; // should be a solo parameter - we don't pass down
648 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700649 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800650 configEvent = new SetParameterConfigEvent(param.toString());
651 } else {
652 configEvent = new SetParameterConfigEvent(keyValuePair);
653 }
Eric Laurent10351942014-05-08 18:49:52 -0700654 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700655}
656
Eric Laurent1c333e22014-05-20 10:48:17 -0700657status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
658 const struct audio_patch *patch,
659 audio_patch_handle_t *handle)
660{
661 Mutex::Autolock _l(mLock);
662 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
663 status_t status = sendConfigEvent_l(configEvent);
664 if (status == NO_ERROR) {
665 CreateAudioPatchConfigEventData *data =
666 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
667 *handle = data->mHandle;
668 }
669 return status;
670}
671
672status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
673 const audio_patch_handle_t handle)
674{
675 Mutex::Autolock _l(mLock);
676 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
677 return sendConfigEvent_l(configEvent);
678}
679
680
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700681// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700682void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700683{
Eric Laurent10351942014-05-08 18:49:52 -0700684 bool configChanged = false;
685
Eric Laurent81784c32012-11-19 14:55:58 -0800686 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700687 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700688 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800689 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700690 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700691 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700692 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
693 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800694 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700695 true /*asynchronous*/);
696 if (err != 0) {
697 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700698 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700699 }
700 } break;
701 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700702 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700703 ioConfigChanged(data->mEvent, data->mPid);
Eric Laurent10351942014-05-08 18:49:52 -0700704 } break;
705 case CFG_EVENT_SET_PARAMETER: {
706 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
707 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
708 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700709 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
710 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700711 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700712 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700713 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700714 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700715 CreateAudioPatchConfigEventData *data =
716 (CreateAudioPatchConfigEventData *)event->mData.get();
717 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700718 const audio_devices_t newDevice = getDevice();
719 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
720 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
721 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700722 } break;
723 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hung293558a2017-03-21 12:19:20 -0700724 const audio_devices_t oldDevice = getDevice();
Eric Laurent1c333e22014-05-20 10:48:17 -0700725 ReleaseAudioPatchConfigEventData *data =
726 (ReleaseAudioPatchConfigEventData *)event->mData.get();
727 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hung293558a2017-03-21 12:19:20 -0700728 const audio_devices_t newDevice = getDevice();
729 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %#x (%s) new device %#x (%s)",
730 (unsigned)oldDevice, devicesToString(oldDevice).c_str(),
731 (unsigned)newDevice, devicesToString(newDevice).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700732 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700733 default:
Eric Laurent10351942014-05-08 18:49:52 -0700734 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700735 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent10351942014-05-08 18:49:52 -0700737 {
738 Mutex::Autolock _l(event->mLock);
739 if (event->mWaitStatus) {
740 event->mWaitStatus = false;
741 event->mCond.signal();
742 }
743 }
744 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
745 }
746
747 if (configChanged) {
748 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800749 }
Eric Laurent81784c32012-11-19 14:55:58 -0800750}
751
Marco Nelissenb2208842014-02-07 14:00:50 -0800752String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
753 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700754 const audio_channel_representation_t representation =
755 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700756
757 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800758 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700759 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
760 if (output) {
761 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
762 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
764 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
765 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
766 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
767 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
768 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
769 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
770 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
771 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
772 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
773 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
774 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
775 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
776 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
777 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
778 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700779 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
780 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800781 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
782 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700783 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
784 } else {
785 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
786 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
787 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
788 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
789 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
790 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
791 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
792 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
793 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
794 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
795 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
796 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700797 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
798 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
799 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
800 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
801 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
802 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700803 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
804 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
805 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
806 }
807 const int len = s.length();
808 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700809 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700810 s.unlockBuffer(len - 2); // remove trailing ", "
811 }
812 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800813 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700814 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
815 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
816 return s;
817 default:
818 s.appendFormat("unknown mask, representation:%d bits:%#x",
819 representation, audio_channel_mask_get_bits(mask));
820 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800821 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800822}
823
Glenn Kasten0f11b512014-01-31 16:18:54 -0800824void AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -0800825{
826 const size_t SIZE = 256;
827 char buffer[SIZE];
828 String8 result;
829
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800830 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
831 this, mThreadName, getTid(), type(), threadTypeToString(type()));
832
Eric Laurent81784c32012-11-19 14:55:58 -0800833 bool locked = AudioFlinger::dumpTryLock(mLock);
834 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800835 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800836 }
837
Elliott Hughes87cebad2014-05-22 10:14:43 -0700838 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700840 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700841 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700842 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700843 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700844 dprintf(fd, " Channel count: %u\n", mChannelCount);
845 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800846 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700847 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700848 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700849 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800850 size_t numConfig = mConfigEvents.size();
851 if (numConfig) {
852 for (size_t i = 0; i < numConfig; i++) {
853 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700854 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700856 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700858 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Andy Hung293558a2017-03-21 12:19:20 -0700860 // Note: output device may be used by capture threads for effects such as AEC.
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700861 dprintf(fd, " Output device: %#x (%s)\n", mOutDevice, devicesToString(mOutDevice).c_str());
862 dprintf(fd, " Input device: %#x (%s)\n", mInDevice, devicesToString(mInDevice).c_str());
Glenn Kasten0b89bc02015-03-05 16:37:47 -0800863 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, sourceToString(mAudioSource));
Eric Laurent81784c32012-11-19 14:55:58 -0800864
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700865 // Dump timestamp statistics for the Thread types that support it.
866 if (mType == RECORD
867 || mType == MIXER
868 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700869 || mType == DIRECT
870 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700871 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700872 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700873 }
874
Eric Laurent81784c32012-11-19 14:55:58 -0800875 if (locked) {
876 mLock.unlock();
877 }
878}
879
880void AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
881{
882 const size_t SIZE = 256;
883 char buffer[SIZE];
884 String8 result;
885
Marco Nelissenb2208842014-02-07 14:00:50 -0800886 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000887 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800888 write(fd, buffer, strlen(buffer));
889
Marco Nelissenb2208842014-02-07 14:00:50 -0800890 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800891 sp<EffectChain> chain = mEffectChains[i];
892 if (chain != 0) {
893 chain->dump(fd, args);
894 }
895 }
896}
897
Andy Hungdae27702016-10-31 14:01:16 -0700898void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800899{
900 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700901 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800902}
903
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100904String16 AudioFlinger::ThreadBase::getWakeLockTag()
905{
906 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800907 case MIXER:
908 return String16("AudioMix");
909 case DIRECT:
910 return String16("AudioDirectOut");
911 case DUPLICATING:
912 return String16("AudioDup");
913 case RECORD:
914 return String16("AudioIn");
915 case OFFLOAD:
916 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800917 case MMAP:
918 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800919 default:
920 ALOG_ASSERT(false);
921 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100922 }
923}
924
Andy Hungdae27702016-10-31 14:01:16 -0700925void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800926{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800927 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800928 if (mPowerManager != 0) {
929 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700930 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
931 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700932 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100933 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700934 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700935 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800936 if (status == NO_ERROR) {
937 mWakeLockToken = binder;
938 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800939 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800940 }
Wei Jia3f273d12015-11-24 09:06:49 -0800941
Andy Hung3f0c9022016-01-15 17:49:46 -0800942 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800943 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
944 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800945}
946
947void AudioFlinger::ThreadBase::releaseWakeLock()
948{
949 Mutex::Autolock _l(mLock);
950 releaseWakeLock_l();
951}
952
953void AudioFlinger::ThreadBase::releaseWakeLock_l()
954{
Andy Hung3f0c9022016-01-15 17:49:46 -0800955 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800956 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800957 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800958 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700959 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
960 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800961 }
962 mWakeLockToken.clear();
963 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800964}
965
966void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700967 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800968 // use checkService() to avoid blocking if power service is not up yet
969 sp<IBinder> binder =
970 defaultServiceManager()->checkService(String16("power"));
971 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800972 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800973 } else {
974 mPowerManager = interface_cast<IPowerManager>(binder);
975 binder->linkToDeath(mDeathRecipient);
976 }
977 }
978}
979
Andy Hungd01b0f12016-11-07 16:10:30 -0800980void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800981 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -0700982
983#if !LOG_NDEBUG
984 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -0800985 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -0700986 s << uid << " ";
987 }
988 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
989#endif
990
Andy Hung438e7572015-12-14 15:51:17 -0800991 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
992 if (mSystemReady) {
993 ALOGE("no wake lock to update, but system ready!");
994 } else {
995 ALOGW("no wake lock to update, system not ready yet");
996 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800997 return;
998 }
999 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001000 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1001 status_t status = mPowerManager->updateWakeLockUids(
1002 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1003 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001004 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001005 }
1006}
1007
Eric Laurent81784c32012-11-19 14:55:58 -08001008void AudioFlinger::ThreadBase::clearPowerManager()
1009{
1010 Mutex::Autolock _l(mLock);
1011 releaseWakeLock_l();
1012 mPowerManager.clear();
1013}
1014
Glenn Kasten0f11b512014-01-31 16:18:54 -08001015void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001016{
1017 sp<ThreadBase> thread = mThread.promote();
1018 if (thread != 0) {
1019 thread->clearPowerManager();
1020 }
1021 ALOGW("power manager service died !!!");
1022}
1023
Eric Laurent81784c32012-11-19 14:55:58 -08001024void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001025 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001026{
1027 sp<EffectChain> chain = getEffectChain_l(sessionId);
1028 if (chain != 0) {
1029 if (type != NULL) {
1030 chain->setEffectSuspended_l(type, suspend);
1031 } else {
1032 chain->setEffectSuspendedAll_l(suspend);
1033 }
1034 }
1035
1036 updateSuspendedSessions_l(type, suspend, sessionId);
1037}
1038
1039void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1040{
1041 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1042 if (index < 0) {
1043 return;
1044 }
1045
1046 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1047 mSuspendedSessions.valueAt(index);
1048
1049 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001050 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001051 for (int j = 0; j < desc->mRefCount; j++) {
1052 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1053 chain->setEffectSuspendedAll_l(true);
1054 } else {
1055 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1056 desc->mType.timeLow);
1057 chain->setEffectSuspended_l(&desc->mType, true);
1058 }
1059 }
1060 }
1061}
1062
1063void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1064 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001065 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001066{
1067 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1068
1069 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1070
1071 if (suspend) {
1072 if (index >= 0) {
1073 sessionEffects = mSuspendedSessions.valueAt(index);
1074 } else {
1075 mSuspendedSessions.add(sessionId, sessionEffects);
1076 }
1077 } else {
1078 if (index < 0) {
1079 return;
1080 }
1081 sessionEffects = mSuspendedSessions.valueAt(index);
1082 }
1083
1084
1085 int key = EffectChain::kKeyForSuspendAll;
1086 if (type != NULL) {
1087 key = type->timeLow;
1088 }
1089 index = sessionEffects.indexOfKey(key);
1090
1091 sp<SuspendedSessionDesc> desc;
1092 if (suspend) {
1093 if (index >= 0) {
1094 desc = sessionEffects.valueAt(index);
1095 } else {
1096 desc = new SuspendedSessionDesc();
1097 if (type != NULL) {
1098 desc->mType = *type;
1099 }
1100 sessionEffects.add(key, desc);
1101 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1102 }
1103 desc->mRefCount++;
1104 } else {
1105 if (index < 0) {
1106 return;
1107 }
1108 desc = sessionEffects.valueAt(index);
1109 if (--desc->mRefCount == 0) {
1110 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1111 sessionEffects.removeItemsAt(index);
1112 if (sessionEffects.isEmpty()) {
1113 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1114 sessionId);
1115 mSuspendedSessions.removeItem(sessionId);
1116 }
1117 }
1118 }
1119 if (!sessionEffects.isEmpty()) {
1120 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1121 }
1122}
1123
1124void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1125 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001126 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001127{
1128 Mutex::Autolock _l(mLock);
1129 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1130}
1131
1132void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1133 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001134 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001135{
1136 if (mType != RECORD) {
1137 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1138 // another session. This gives the priority to well behaved effect control panels
1139 // and applications not using global effects.
1140 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1141 // global effects
1142 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1143 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1144 }
1145 }
1146
1147 sp<EffectChain> chain = getEffectChain_l(sessionId);
1148 if (chain != 0) {
1149 chain->checkSuspendOnEffectEnabled(effect, enabled);
1150 }
1151}
1152
Eric Laurent4c415062016-06-17 16:14:16 -07001153// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1154status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1155 const effect_descriptor_t *desc, audio_session_t sessionId)
1156{
1157 // No global effect sessions on record threads
1158 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1159 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1160 desc->name, mThreadName);
1161 return BAD_VALUE;
1162 }
1163 // only pre processing effects on record thread
1164 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1165 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1166 desc->name, mThreadName);
1167 return BAD_VALUE;
1168 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001169
1170 // always allow effects without processing load or latency
1171 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1172 return NO_ERROR;
1173 }
1174
Eric Laurent4c415062016-06-17 16:14:16 -07001175 audio_input_flags_t flags = mInput->flags;
1176 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1177 if (flags & AUDIO_INPUT_FLAG_RAW) {
1178 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1179 desc->name, mThreadName);
1180 return BAD_VALUE;
1181 }
1182 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1183 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1184 desc->name, mThreadName);
1185 return BAD_VALUE;
1186 }
1187 }
1188 return NO_ERROR;
1189}
1190
1191// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1192status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1193 const effect_descriptor_t *desc, audio_session_t sessionId)
1194{
1195 // no preprocessing on playback threads
1196 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1197 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1198 " thread %s", desc->name, mThreadName);
1199 return BAD_VALUE;
1200 }
1201
Eric Laurent3e4de772017-07-16 16:55:08 -07001202 // always allow effects without processing load or latency
1203 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1204 return NO_ERROR;
1205 }
1206
Eric Laurent4c415062016-06-17 16:14:16 -07001207 switch (mType) {
1208 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001209#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001210 // Reject any effect on mixer multichannel sinks.
1211 // TODO: fix both format and multichannel issues with effects.
1212 if (mChannelCount != FCC_2) {
1213 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1214 " thread %s", desc->name, mChannelCount, mThreadName);
1215 return BAD_VALUE;
1216 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001217#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001218 audio_output_flags_t flags = mOutput->flags;
1219 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1220 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1221 // global effects are applied only to non fast tracks if they are SW
1222 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1223 break;
1224 }
1225 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1226 // only post processing on output stage session
1227 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1228 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1229 " on output stage session", desc->name);
1230 return BAD_VALUE;
1231 }
1232 } else {
1233 // no restriction on effects applied on non fast tracks
1234 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1235 break;
1236 }
1237 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001238
Eric Laurent4c415062016-06-17 16:14:16 -07001239 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1240 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1241 desc->name);
1242 return BAD_VALUE;
1243 }
1244 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1245 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1246 " in fast mode", desc->name);
1247 return BAD_VALUE;
1248 }
1249 }
1250 } break;
1251 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001252 // nothing actionable on offload threads, if the effect:
1253 // - is offloadable: the effect can be created
1254 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1255 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001256 break;
1257 case DIRECT:
1258 // Reject any effect on Direct output threads for now, since the format of
1259 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1260 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1261 desc->name, mThreadName);
1262 return BAD_VALUE;
1263 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001264#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001265 // Reject any effect on mixer multichannel sinks.
1266 // TODO: fix both format and multichannel issues with effects.
1267 if (mChannelCount != FCC_2) {
1268 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1269 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1270 return BAD_VALUE;
1271 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001272#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001273 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1274 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1275 " thread %s", desc->name, mThreadName);
1276 return BAD_VALUE;
1277 }
1278 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1279 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1280 " DUPLICATING thread %s", desc->name, mThreadName);
1281 return BAD_VALUE;
1282 }
1283 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1284 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1285 " DUPLICATING thread %s", desc->name, mThreadName);
1286 return BAD_VALUE;
1287 }
1288 break;
1289 default:
1290 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1291 }
1292
1293 return NO_ERROR;
1294}
1295
Eric Laurent81784c32012-11-19 14:55:58 -08001296// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1297sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1298 const sp<AudioFlinger::Client>& client,
1299 const sp<IEffectClient>& effectClient,
1300 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001301 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001302 effect_descriptor_t *desc,
1303 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001304 status_t *status,
1305 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001306{
1307 sp<EffectModule> effect;
1308 sp<EffectHandle> handle;
1309 status_t lStatus;
1310 sp<EffectChain> chain;
1311 bool chainCreated = false;
1312 bool effectCreated = false;
1313 bool effectRegistered = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001314 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001315
1316 lStatus = initCheck();
1317 if (lStatus != NO_ERROR) {
1318 ALOGW("createEffect_l() Audio driver not initialized.");
1319 goto Exit;
1320 }
1321
Eric Laurent81784c32012-11-19 14:55:58 -08001322 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1323
1324 { // scope for mLock
1325 Mutex::Autolock _l(mLock);
1326
Eric Laurent4c415062016-06-17 16:14:16 -07001327 lStatus = checkEffectCompatibility_l(desc, sessionId);
1328 if (lStatus != NO_ERROR) {
1329 goto Exit;
1330 }
1331
Eric Laurent81784c32012-11-19 14:55:58 -08001332 // check for existing effect chain with the requested audio session
1333 chain = getEffectChain_l(sessionId);
1334 if (chain == 0) {
1335 // create a new chain for this session
1336 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1337 chain = new EffectChain(this, sessionId);
1338 addEffectChain_l(chain);
1339 chain->setStrategy(getStrategyForSession_l(sessionId));
1340 chainCreated = true;
1341 } else {
1342 effect = chain->getEffectFromDesc_l(desc);
1343 }
1344
1345 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1346
1347 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001348 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001349 // Check CPU and memory usage
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001350 lStatus = AudioSystem::registerEffect(
1351 desc, mId, chain->strategy(), sessionId, effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001352 if (lStatus != NO_ERROR) {
1353 goto Exit;
1354 }
1355 effectRegistered = true;
1356 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001357 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001358 if (lStatus != NO_ERROR) {
1359 goto Exit;
1360 }
1361 effectCreated = true;
1362
1363 effect->setDevice(mOutDevice);
1364 effect->setDevice(mInDevice);
1365 effect->setMode(mAudioFlinger->getMode());
1366 effect->setAudioSource(mAudioSource);
1367 }
1368 // create effect handle and connect it to effect module
1369 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001370 lStatus = handle->initCheck();
1371 if (lStatus == OK) {
1372 lStatus = effect->addHandle(handle.get());
1373 }
Eric Laurent81784c32012-11-19 14:55:58 -08001374 if (enabled != NULL) {
1375 *enabled = (int)effect->isEnabled();
1376 }
1377 }
1378
1379Exit:
1380 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1381 Mutex::Autolock _l(mLock);
1382 if (effectCreated) {
1383 chain->removeEffect_l(effect);
1384 }
1385 if (effectRegistered) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001386 AudioSystem::unregisterEffect(effectId);
Eric Laurent81784c32012-11-19 14:55:58 -08001387 }
1388 if (chainCreated) {
1389 removeEffectChain_l(chain);
1390 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001391 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001392 }
1393
Glenn Kasten9156ef32013-08-06 15:39:08 -07001394 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001395 return handle;
1396}
1397
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001398void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1399 bool unpinIfLast)
1400{
1401 bool remove = false;
1402 sp<EffectModule> effect;
1403 {
1404 Mutex::Autolock _l(mLock);
1405
1406 effect = handle->effect().promote();
1407 if (effect == 0) {
1408 return;
1409 }
1410 // restore suspended effects if the disconnected handle was enabled and the last one.
1411 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1412 if (remove) {
1413 removeEffect_l(effect, true);
1414 }
1415 }
1416 if (remove) {
1417 mAudioFlinger->updateOrphanEffectChains(effect);
1418 AudioSystem::unregisterEffect(effect->id());
1419 if (handle->enabled()) {
1420 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1421 }
1422 }
1423}
1424
Glenn Kastend848eb42016-03-08 13:42:11 -08001425sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1426 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001427{
1428 Mutex::Autolock _l(mLock);
1429 return getEffect_l(sessionId, effectId);
1430}
1431
Glenn Kastend848eb42016-03-08 13:42:11 -08001432sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1433 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001434{
1435 sp<EffectChain> chain = getEffectChain_l(sessionId);
1436 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1437}
1438
1439// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1440// PlaybackThread::mLock held
1441status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1442{
1443 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001444 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001445 sp<EffectChain> chain = getEffectChain_l(sessionId);
1446 bool chainCreated = false;
1447
Eric Laurent5baf2af2013-09-12 17:37:00 -07001448 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001449 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001450 this, effect->desc().name, effect->desc().flags);
1451
Eric Laurent81784c32012-11-19 14:55:58 -08001452 if (chain == 0) {
1453 // create a new chain for this session
1454 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1455 chain = new EffectChain(this, sessionId);
1456 addEffectChain_l(chain);
1457 chain->setStrategy(getStrategyForSession_l(sessionId));
1458 chainCreated = true;
1459 }
1460 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1461
1462 if (chain->getEffectFromId_l(effect->id()) != 0) {
1463 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1464 this, effect->desc().name, chain.get());
1465 return BAD_VALUE;
1466 }
1467
Eric Laurent5baf2af2013-09-12 17:37:00 -07001468 effect->setOffloaded(mType == OFFLOAD, mId);
1469
Eric Laurent81784c32012-11-19 14:55:58 -08001470 status_t status = chain->addEffect_l(effect);
1471 if (status != NO_ERROR) {
1472 if (chainCreated) {
1473 removeEffectChain_l(chain);
1474 }
1475 return status;
1476 }
1477
1478 effect->setDevice(mOutDevice);
1479 effect->setDevice(mInDevice);
1480 effect->setMode(mAudioFlinger->getMode());
1481 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001482
Eric Laurent81784c32012-11-19 14:55:58 -08001483 return NO_ERROR;
1484}
1485
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001486void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001487
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001488 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001489 effect_descriptor_t desc = effect->desc();
1490 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1491 detachAuxEffect_l(effect->id());
1492 }
1493
1494 sp<EffectChain> chain = effect->chain().promote();
1495 if (chain != 0) {
1496 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001497 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001498 removeEffectChain_l(chain);
1499 }
1500 } else {
1501 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1502 }
1503}
1504
1505void AudioFlinger::ThreadBase::lockEffectChains_l(
1506 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1507{
1508 effectChains = mEffectChains;
1509 for (size_t i = 0; i < mEffectChains.size(); i++) {
1510 mEffectChains[i]->lock();
1511 }
1512}
1513
1514void AudioFlinger::ThreadBase::unlockEffectChains(
1515 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1516{
1517 for (size_t i = 0; i < effectChains.size(); i++) {
1518 effectChains[i]->unlock();
1519 }
1520}
1521
Glenn Kastend848eb42016-03-08 13:42:11 -08001522sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001523{
1524 Mutex::Autolock _l(mLock);
1525 return getEffectChain_l(sessionId);
1526}
1527
Glenn Kastend848eb42016-03-08 13:42:11 -08001528sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1529 const
Eric Laurent81784c32012-11-19 14:55:58 -08001530{
1531 size_t size = mEffectChains.size();
1532 for (size_t i = 0; i < size; i++) {
1533 if (mEffectChains[i]->sessionId() == sessionId) {
1534 return mEffectChains[i];
1535 }
1536 }
1537 return 0;
1538}
1539
1540void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1541{
1542 Mutex::Autolock _l(mLock);
1543 size_t size = mEffectChains.size();
1544 for (size_t i = 0; i < size; i++) {
1545 mEffectChains[i]->setMode_l(mode);
1546 }
1547}
1548
Mikhail Naganovdc769682018-05-04 15:34:08 -07001549void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001550{
1551 config->type = AUDIO_PORT_TYPE_MIX;
1552 config->ext.mix.handle = mId;
1553 config->sample_rate = mSampleRate;
1554 config->format = mFormat;
1555 config->channel_mask = mChannelMask;
1556 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1557 AUDIO_PORT_CONFIG_FORMAT;
1558}
1559
Eric Laurent72e3f392015-05-20 14:43:50 -07001560void AudioFlinger::ThreadBase::systemReady()
1561{
1562 Mutex::Autolock _l(mLock);
1563 if (mSystemReady) {
1564 return;
1565 }
1566 mSystemReady = true;
1567
1568 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1569 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1570 }
1571 mPendingConfigEvents.clear();
1572}
1573
Andy Hungdae27702016-10-31 14:01:16 -07001574template <typename T>
1575ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1576 ssize_t index = mActiveTracks.indexOf(track);
1577 if (index >= 0) {
1578 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1579 return index;
1580 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001581 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001582 mActiveTracksGeneration++;
1583 mLatestActiveTrack = track;
1584 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001585 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001586 return mActiveTracks.add(track);
1587}
1588
1589template <typename T>
1590ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1591 ssize_t index = mActiveTracks.remove(track);
1592 if (index < 0) {
1593 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1594 return index;
1595 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001596 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001597 mActiveTracksGeneration++;
1598 --mBatteryCounter[track->uid()].second;
1599 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001600 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001601#ifdef TEE_SINK
1602 track->dumpTee(-1 /* fd */, "_REMOVE");
1603#endif
Andy Hungdae27702016-10-31 14:01:16 -07001604 return index;
1605}
1606
1607template <typename T>
1608void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1609 for (const sp<T> &track : mActiveTracks) {
1610 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001611 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001612 }
1613 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001614 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001615 mActiveTracks.clear();
1616 mLatestActiveTrack.clear();
1617 mBatteryCounter.clear();
1618}
1619
1620template <typename T>
1621void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1622 sp<ThreadBase> thread, bool force) {
1623 // Updates ActiveTracks client uids to the thread wakelock.
1624 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1625 thread->updateWakeLockUids_l(getWakeLockUids());
1626 mLastActiveTracksGeneration = mActiveTracksGeneration;
1627 }
1628
1629 // Updates BatteryNotifier uids
1630 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1631 const uid_t uid = it->first;
1632 ssize_t &previous = it->second.first;
1633 ssize_t &current = it->second.second;
1634 if (current > 0) {
1635 if (previous == 0) {
1636 BatteryNotifier::getInstance().noteStartAudio(uid);
1637 }
1638 previous = current;
1639 ++it;
1640 } else if (current == 0) {
1641 if (previous > 0) {
1642 BatteryNotifier::getInstance().noteStopAudio(uid);
1643 }
1644 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1645 } else /* (current < 0) */ {
1646 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1647 }
1648 }
1649}
Eric Laurent83b88082014-06-20 18:31:16 -07001650
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001651template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001652bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1653 const bool hasChanged = mHasChanged;
1654 mHasChanged = false;
1655 return hasChanged;
1656}
1657
1658template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001659void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1660 const char *funcName, const sp<T> &track) const {
1661 if (mLocalLog != nullptr) {
1662 String8 result;
1663 track->appendDump(result, false /* active */);
1664 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1665 }
1666}
1667
Eric Laurent6acd1d42017-01-04 14:23:29 -08001668void AudioFlinger::ThreadBase::broadcast_l()
1669{
1670 // Thread could be blocked waiting for async
1671 // so signal it to handle state changes immediately
1672 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1673 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1674 mSignalPending = true;
1675 mWaitWorkCV.broadcast();
1676}
1677
Eric Laurent81784c32012-11-19 14:55:58 -08001678// ----------------------------------------------------------------------------
1679// Playback
1680// ----------------------------------------------------------------------------
1681
1682AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1683 AudioStreamOut* output,
1684 audio_io_handle_t id,
1685 audio_devices_t device,
Eric Laurent72e3f392015-05-20 14:43:50 -07001686 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001687 bool systemReady)
Eric Laurent72e3f392015-05-20 14:43:50 -07001688 : ThreadBase(audioFlinger, id, device, AUDIO_DEVICE_NONE, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001689 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001690 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001691 mMixerBuffer(NULL),
1692 mMixerBufferSize(0),
1693 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1694 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001695 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001696 mEffectBuffer(NULL),
1697 mEffectBufferSize(0),
1698 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1699 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001700 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001701 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001702 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001703 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001704 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001705 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001706 mOutput(output),
Andy Hung69488c42016-05-16 18:43:33 -07001707 mLastWriteTime(-1), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001708 mMixerStatus(MIXER_IDLE),
1709 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001710 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001711 mBytesRemaining(0),
1712 mCurrentWriteLength(0),
1713 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001714 mWriteAckSequence(0),
1715 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001716 mScreenState(AudioFlinger::mScreenState),
1717 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001718 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001719 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1720 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001721{
Glenn Kastend7dca052015-03-05 16:05:54 -08001722 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1723 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001724
1725 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1726 // it would be safer to explicitly pass initial masterVolume/masterMute as
1727 // parameter.
1728 //
1729 // If the HAL we are using has support for master volume or master mute,
1730 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1731 // and the mute set to false).
1732 mMasterVolume = audioFlinger->masterVolume_l();
1733 mMasterMute = audioFlinger->masterMute_l();
1734 if (mOutput && mOutput->audioHwDev) {
1735 if (mOutput->audioHwDev->canSetMasterVolume()) {
1736 mMasterVolume = 1.0;
1737 }
1738
1739 if (mOutput->audioHwDev->canSetMasterMute()) {
1740 mMasterMute = false;
1741 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001742 mIsMsdDevice = strcmp(
1743 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001744 }
1745
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001746 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001747
Andy Hungc8fddf32018-08-08 18:32:37 -07001748 // TODO: We may also match on address as well as device type for
1749 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
1750 if (type == MIXER || type == DIRECT) {
1751 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
1752 "audio.timestamp.corrected_output_devices",
1753 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1754 : AUDIO_DEVICE_NONE));
1755 }
1756
Eric Laurent223fd5c2014-11-11 13:43:36 -08001757 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001758 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001759 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001760 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001761 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1762 }
Eric Laurent98e38192018-02-15 18:31:53 -08001763 // Audio patch volume is always max
1764 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1765 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001766}
1767
1768AudioFlinger::PlaybackThread::~PlaybackThread()
1769{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001770 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001771 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001772 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001773 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001774}
1775
1776void AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1777{
1778 dumpInternals(fd, args);
1779 dumpTracks(fd, args);
1780 dumpEffectChains(fd, args);
Andy Hung293558a2017-03-21 12:19:20 -07001781 dprintf(fd, " Local log:\n");
1782 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08001783}
1784
Glenn Kasten0f11b512014-01-31 16:18:54 -08001785void AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
Eric Laurent81784c32012-11-19 14:55:58 -08001787 String8 result;
1788
Marco Nelissenb2208842014-02-07 14:00:50 -08001789 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001790 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1791 const stream_type_t *st = &mStreamTypes[i];
1792 if (i > 0) {
1793 result.appendFormat(", ");
1794 }
1795 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1796 if (st->mute) {
1797 result.append("M");
1798 }
1799 }
1800 result.append("\n");
1801 write(fd, result.string(), result.length());
1802 result.clear();
1803
Eric Laurent81784c32012-11-19 14:55:58 -08001804 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1805 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001806 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001807 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001808
1809 size_t numtracks = mTracks.size();
1810 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001811 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001812 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001813 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001814 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001815 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001816 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001817 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001818 for (size_t i = 0; i < numtracks; ++i) {
1819 sp<Track> track = mTracks[i];
1820 if (track != 0) {
1821 bool active = mActiveTracks.indexOf(track) >= 0;
1822 if (active) {
1823 numactiveseen++;
1824 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001825 result.append(prefix);
1826 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001827 }
1828 }
1829 } else {
1830 result.append("\n");
1831 }
1832 if (numactiveseen != numactive) {
1833 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001834 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001835 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001836 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001837 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001838 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001839 sp<Track> track = mActiveTracks[i];
1840 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001841 result.append(prefix);
1842 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001843 }
1844 }
1845 }
1846
1847 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001848}
1849
1850void AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1851{
Glenn Kasten44182c22015-03-05 17:12:23 -08001852 dumpBase(fd, args);
1853
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001854 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001855 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1856 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1857 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1858 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001859 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001860 dprintf(fd, " Last write occurred (msecs): %llu\n",
1861 (unsigned long long) ns2ms(systemTime() - mLastWriteTime));
Elliott Hughes87cebad2014-05-22 10:14:43 -07001862 dprintf(fd, " Total writes: %d\n", mNumWrites);
1863 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1864 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1865 dprintf(fd, " Suspend count: %d\n", mSuspended);
1866 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1867 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1868 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1869 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001870 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001871 AudioStreamOut *output = mOutput;
1872 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001873 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
1874 output, flags, outputFlagsToString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001875 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1876 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1877 if (mPipeSink.get() != nullptr) {
1878 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1879 }
1880 if (output != nullptr) {
1881 dprintf(fd, " Hal stream dump:\n");
1882 (void)output->stream->dump(fd);
1883 }
Eric Laurent81784c32012-11-19 14:55:58 -08001884}
1885
1886// Thread virtuals
Eric Laurent81784c32012-11-19 14:55:58 -08001887
1888void AudioFlinger::PlaybackThread::onFirstRef()
1889{
Glenn Kastend7dca052015-03-05 16:05:54 -08001890 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001891}
1892
1893// ThreadBase virtuals
1894void AudioFlinger::PlaybackThread::preExit()
1895{
1896 ALOGV(" preExit()");
Mikhail Naganovad9c7e42018-03-05 12:25:58 -08001897 // FIXME this is using hard-coded strings but in the future, this functionality will be
1898 // converted to use audio HAL extensions required to support tunneling
1899 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1900 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
Eric Laurent81784c32012-11-19 14:55:58 -08001901}
1902
1903// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1904sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1905 const sp<AudioFlinger::Client>& client,
1906 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001907 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001908 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001909 audio_format_t format,
1910 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001911 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001912 size_t *pNotificationFrameCount,
1913 uint32_t notificationsPerBuffer,
1914 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001915 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001916 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001917 audio_output_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08001918 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001919 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001920 status_t *status,
1921 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001922{
Glenn Kasten74935e42013-12-19 08:56:45 -08001923 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001924 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001925 sp<Track> track;
1926 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001927 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001928 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001929 uint32_t sampleRate;
1930
1931 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1932 lStatus = BAD_VALUE;
1933 goto Exit;
1934 }
Eric Laurent21da6472017-11-09 16:29:26 -08001935
1936 if (*pSampleRate == 0) {
1937 *pSampleRate = mSampleRate;
1938 }
Eric Laurent9b11c022018-06-06 19:19:22 -07001939 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07001940
1941 // special case for FAST flag considered OK if fast mixer is present
1942 if (hasFastMixer()) {
1943 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
1944 }
1945
1946 // Check if requested flags are compatible with output stream flags
1947 if ((*flags & outputFlags) != *flags) {
1948 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
1949 *flags, outputFlags);
1950 *flags = (audio_output_flags_t)(*flags & outputFlags);
1951 }
Eric Laurent81784c32012-11-19 14:55:58 -08001952
Eric Laurent81784c32012-11-19 14:55:58 -08001953 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07001954 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08001955 if (
Eric Laurent81784c32012-11-19 14:55:58 -08001956 // PCM data
1957 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07001958 // TODO: extract as a data library function that checks that a computationally
1959 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08001960 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07001961 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
1962 (channelMask == AUDIO_CHANNEL_OUT_MONO
1963 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001964 // hardware sample rate
1965 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08001966 // normal mixer has an associated fast mixer
1967 hasFastMixer() &&
1968 // there are sufficient fast track slots available
1969 (mFastTrackAvailMask != 0)
1970 // FIXME test that MixerThread for this fast track has a capable output HAL
1971 // FIXME add a permission test also?
1972 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07001973 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
1974 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07001975 // read the fast track multiplier property the first time it is needed
1976 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
1977 if (ok != 0) {
1978 ALOGE("%s pthread_once failed: %d", __func__, ok);
1979 }
Andy Hunge0a269a2016-03-23 15:13:42 -07001980 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08001981 }
Eric Laurent4c415062016-06-17 16:14:16 -07001982
1983 // check compatibility with audio effects.
1984 { // scope for mLock
1985 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07001986 for (audio_session_t session : {
1987 AUDIO_SESSION_OUTPUT_STAGE,
1988 AUDIO_SESSION_OUTPUT_MIX,
1989 sessionId,
1990 }) {
1991 sp<EffectChain> chain = getEffectChain_l(session);
1992 if (chain.get() != nullptr) {
1993 audio_output_flags_t old = *flags;
1994 chain->checkOutputFlagCompatibility(flags);
1995 if (old != *flags) {
1996 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
1997 (int)session, (int)old, (int)*flags);
1998 }
Eric Laurent4c415062016-06-17 16:14:16 -07001999 }
2000 }
2001 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002002 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002003 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2004 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002005 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002006 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2007 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002008 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002009 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002010 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002011 audio_is_linear_pcm(format),
2012 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002013 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002014 }
2015 }
Eric Laurent21da6472017-11-09 16:29:26 -08002016
2017 if (!audio_has_proportional_frames(format)) {
2018 if (sharedBuffer != 0) {
2019 // Same comment as below about ignoring frameCount parameter for set()
2020 frameCount = sharedBuffer->size();
2021 } else if (frameCount == 0) {
2022 frameCount = mNormalFrameCount;
2023 }
2024 if (notificationFrameCount != frameCount) {
2025 notificationFrameCount = frameCount;
2026 }
2027 } else if (sharedBuffer != 0) {
2028 // FIXME: Ensure client side memory buffers need
2029 // not have additional alignment beyond sample
2030 // (e.g. 16 bit stereo accessed as 32 bit frame).
2031 size_t alignment = audio_bytes_per_sample(format);
2032 if (alignment & 1) {
2033 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2034 alignment = 1;
2035 }
2036 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2037 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2038 if (channelCount > 1) {
2039 // More than 2 channels does not require stronger alignment than stereo
2040 alignment <<= 1;
2041 }
2042 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2043 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2044 sharedBuffer->pointer(), channelCount);
2045 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002046 goto Exit;
2047 }
Eric Laurent21da6472017-11-09 16:29:26 -08002048
2049 // When initializing a shared buffer AudioTrack via constructors,
2050 // there's no frameCount parameter.
2051 // But when initializing a shared buffer AudioTrack via set(),
2052 // there _is_ a frameCount parameter. We silently ignore it.
2053 frameCount = sharedBuffer->size() / frameSize;
2054 } else {
2055 size_t minFrameCount = 0;
2056 // For fast tracks we try to respect the application's request for notifications per buffer.
2057 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2058 if (notificationsPerBuffer > 0) {
2059 // Avoid possible arithmetic overflow during multiplication.
2060 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2061 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2062 notificationsPerBuffer, mFrameCount);
2063 } else {
2064 minFrameCount = mFrameCount * notificationsPerBuffer;
2065 }
2066 }
2067 } else {
2068 // For normal PCM streaming tracks, update minimum frame count.
2069 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2070 // cover audio hardware latency.
2071 // This is probably too conservative, but legacy application code may depend on it.
2072 // If you change this calculation, also review the start threshold which is related.
2073 uint32_t latencyMs = latency_l();
2074 if (latencyMs == 0) {
2075 ALOGE("Error when retrieving output stream latency");
2076 lStatus = UNKNOWN_ERROR;
2077 goto Exit;
2078 }
2079
2080 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2081 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2082
Eric Laurent81784c32012-11-19 14:55:58 -08002083 }
Eric Laurent21da6472017-11-09 16:29:26 -08002084 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002085 frameCount = minFrameCount;
2086 }
Eric Laurent81784c32012-11-19 14:55:58 -08002087 }
Eric Laurent21da6472017-11-09 16:29:26 -08002088
2089 // Make sure that application is notified with sufficient margin before underrun.
2090 // The client can divide the AudioTrack buffer into sub-buffers,
2091 // and expresses its desire to server as the notification frame count.
2092 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2093 size_t maxNotificationFrames;
2094 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2095 // notify every HAL buffer, regardless of the size of the track buffer
2096 maxNotificationFrames = mFrameCount;
2097 } else {
2098 // For normal tracks, use at least double-buffering if no sample rate conversion,
2099 // or at least triple-buffering if there is sample rate conversion
2100 const int nBuffering = sampleRate == mSampleRate ? 2 : 3;
2101 maxNotificationFrames = frameCount / nBuffering;
2102 // If client requested a fast track but this was denied, then use the smaller maximum.
2103 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2104 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2105 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2106 maxNotificationFrames = maxNotificationFramesFastDenied;
2107 }
2108 }
2109 }
2110 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2111 if (notificationFrameCount == 0) {
2112 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2113 maxNotificationFrames, frameCount);
2114 } else {
2115 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2116 notificationFrameCount, maxNotificationFrames, frameCount);
2117 }
2118 notificationFrameCount = maxNotificationFrames;
2119 }
2120 }
2121
Glenn Kasten74935e42013-12-19 08:56:45 -08002122 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002123 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002124
Glenn Kastenc3df8382014-03-13 15:05:25 -07002125 switch (mType) {
2126
2127 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002128 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002129 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002130 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2131 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002132 sampleRate, format, channelMask, mOutput, mFormat);
2133 lStatus = BAD_VALUE;
2134 goto Exit;
2135 }
2136 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002137 break;
2138
2139 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002140 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002141 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2142 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002143 sampleRate, format, channelMask, mOutput, mFormat);
2144 lStatus = BAD_VALUE;
2145 goto Exit;
2146 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002147 break;
2148
2149 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002150 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002151 ALOGE("createTrack_l() Bad parameter: format %#x \""
2152 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002153 format, mOutput, mFormat);
2154 lStatus = BAD_VALUE;
2155 goto Exit;
2156 }
Andy Hungcd044842014-08-07 11:04:34 -07002157 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002158 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2159 lStatus = BAD_VALUE;
2160 goto Exit;
2161 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002162 break;
2163
Eric Laurent81784c32012-11-19 14:55:58 -08002164 }
2165
2166 lStatus = initCheck();
2167 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002168 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002169 goto Exit;
2170 }
2171
2172 { // scope for mLock
2173 Mutex::Autolock _l(mLock);
2174
2175 // all tracks in same audio session must share the same routing strategy otherwise
2176 // conflicts will happen when tracks are moved from one output to another by audio policy
2177 // manager
2178 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2179 for (size_t i = 0; i < mTracks.size(); ++i) {
2180 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002181 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002182 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2183 if (sessionId == t->sessionId() && strategy != actual) {
2184 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2185 strategy, actual);
2186 lStatus = BAD_VALUE;
2187 goto Exit;
2188 }
2189 }
2190 }
2191
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002192 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002193 channelMask, frameCount,
2194 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002195 sessionId, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002196
Glenn Kasten03003332013-08-06 15:40:54 -07002197 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2198 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002199 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002200 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002201 goto Exit;
2202 }
2203 mTracks.add(track);
2204
2205 sp<EffectChain> chain = getEffectChain_l(sessionId);
2206 if (chain != 0) {
2207 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2208 track->setMainBuffer(chain->inBuffer());
2209 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2210 chain->incTrackCnt();
2211 }
2212
Eric Laurent05067782016-06-01 18:27:28 -07002213 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002214 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2215 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2216 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002217 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002218 }
2219 }
2220
2221 lStatus = NO_ERROR;
2222
2223Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002224 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002225 return track;
2226}
2227
Andy Hung1bc088a2018-02-09 15:57:31 -08002228template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002229ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2230{
Andy Hungc0691382018-09-12 18:01:57 -07002231 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002232 const ssize_t index = mTracks.remove(track);
2233 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002234 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002235 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002236 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002237 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002238 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002239 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002240 }
2241 return index;
2242}
2243
Eric Laurent81784c32012-11-19 14:55:58 -08002244uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2245{
2246 return latency;
2247}
2248
2249uint32_t AudioFlinger::PlaybackThread::latency() const
2250{
2251 Mutex::Autolock _l(mLock);
2252 return latency_l();
2253}
2254uint32_t AudioFlinger::PlaybackThread::latency_l() const
2255{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002256 uint32_t latency;
2257 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2258 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002259 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002260 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002261}
2262
2263void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2264{
2265 Mutex::Autolock _l(mLock);
2266 // Don't apply master volume in SW if our HAL can do it for us.
2267 if (mOutput && mOutput->audioHwDev &&
2268 mOutput->audioHwDev->canSetMasterVolume()) {
2269 mMasterVolume = 1.0;
2270 } else {
2271 mMasterVolume = value;
2272 }
2273}
2274
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002275void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2276{
2277 mMasterBalance.store(balance);
2278}
2279
Eric Laurent81784c32012-11-19 14:55:58 -08002280void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2281{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002282 if (isDuplicating()) {
2283 return;
2284 }
Eric Laurent81784c32012-11-19 14:55:58 -08002285 Mutex::Autolock _l(mLock);
2286 // Don't apply master mute in SW if our HAL can do it for us.
2287 if (mOutput && mOutput->audioHwDev &&
2288 mOutput->audioHwDev->canSetMasterMute()) {
2289 mMasterMute = false;
2290 } else {
2291 mMasterMute = muted;
2292 }
2293}
2294
2295void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2296{
2297 Mutex::Autolock _l(mLock);
2298 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002299 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002300}
2301
2302void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2303{
2304 Mutex::Autolock _l(mLock);
2305 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002306 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002307}
2308
2309float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2310{
2311 Mutex::Autolock _l(mLock);
2312 return mStreamTypes[stream].volume;
2313}
2314
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002315void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2316{
2317 mOutput->stream->setVolume(left, right);
2318}
2319
Eric Laurent81784c32012-11-19 14:55:58 -08002320// addTrack_l() must be called with ThreadBase::mLock held
2321status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2322{
2323 status_t status = ALREADY_EXISTS;
2324
Eric Laurent81784c32012-11-19 14:55:58 -08002325 if (mActiveTracks.indexOf(track) < 0) {
2326 // the track is newly added, make sure it fills up all its
2327 // buffers before playing. This is to ensure the client will
2328 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002329 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002330 TrackBase::track_state state = track->mState;
2331 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002332 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002333 mLock.lock();
2334 // abort track was stopped/paused while we released the lock
2335 if (state != track->mState) {
2336 if (status == NO_ERROR) {
2337 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002338 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002339 mLock.lock();
2340 }
2341 return INVALID_OPERATION;
2342 }
2343 // abort if start is rejected by audio policy manager
2344 if (status != NO_ERROR) {
2345 return PERMISSION_DENIED;
2346 }
2347#ifdef ADD_BATTERY_DATA
2348 // to track the speaker usage
2349 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2350#endif
2351 }
2352
Eric Laurent51716182016-02-29 18:00:56 -08002353 // set retry count for buffer fill
2354 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002355 if (track->isStopping_1()) {
2356 track->mRetryCount = kMaxTrackStopRetriesOffload;
2357 } else {
2358 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2359 }
2360 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002361 } else {
2362 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002363 track->mFillingUpStatus =
2364 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002365 }
2366
jiabin245cdd92018-12-07 17:55:15 -08002367 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2368 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002369 // Unlock due to VibratorService will lock for this call and will
2370 // call Tracks.mute/unmute which also require thread's lock.
2371 mLock.unlock();
2372 const int intensity = AudioFlinger::onExternalVibrationStart(
2373 track->getExternalVibration());
2374 mLock.lock();
2375 // Haptic playback should be enabled by vibrator service.
2376 if (track->getHapticPlaybackEnabled()) {
2377 // Disable haptic playback of all active track to ensure only
2378 // one track playing haptic if current track should play haptic.
2379 for (const auto &t : mActiveTracks) {
2380 t->setHapticPlaybackEnabled(false);
2381 }
jiabin245cdd92018-12-07 17:55:15 -08002382 }
jiabin57303cc2018-12-18 15:45:57 -08002383 track->setHapticIntensity(intensity);
jiabin245cdd92018-12-07 17:55:15 -08002384 }
2385
Eric Laurent81784c32012-11-19 14:55:58 -08002386 track->mResetDone = false;
2387 track->mPresentationCompleteFrames = 0;
2388 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002389 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2390 if (chain != 0) {
2391 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2392 track->sessionId());
2393 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002394 }
2395
2396 status = NO_ERROR;
2397 }
2398
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002399 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002400 return status;
2401}
2402
Eric Laurentbfb1b832013-01-07 09:53:42 -08002403bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002404{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002405 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002406 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002407 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2408 track->mState = TrackBase::STOPPED;
2409 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002410 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002411 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002413 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002414
2415 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002416}
2417
2418void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2419{
2420 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002421
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002422 String8 result;
2423 track->appendDump(result, false /* active */);
2424 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002425
Eric Laurent81784c32012-11-19 14:55:58 -08002426 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002427 if (track->isFastTrack()) {
2428 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002429 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002430 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2431 mFastTrackAvailMask |= 1 << index;
2432 // redundant as track is about to be destroyed, for dumpsys only
2433 track->mFastIndex = -1;
2434 }
2435 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2436 if (chain != 0) {
2437 chain->decTrackCnt();
2438 }
2439}
2440
2441String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2442{
Eric Laurent81784c32012-11-19 14:55:58 -08002443 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002444 String8 out_s8;
2445 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2446 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002447 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002448 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002449}
2450
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002451status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2452 Mutex::Autolock _l(mLock);
2453 if (mOutput == nullptr || mOutput->stream == nullptr) {
2454 return NO_INIT;
2455 }
2456 return mOutput->stream->selectPresentation(presentationId, programId);
2457}
2458
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002459void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002460 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2461 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002462
Eric Laurent73e26b62015-04-27 16:55:58 -07002463 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002464
2465 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002466 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002467 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002468 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002469 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002470 desc->mChannelMask = mChannelMask;
2471 desc->mSamplingRate = mSampleRate;
2472 desc->mFormat = mFormat;
2473 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002474 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002475 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002476 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002477 break;
2478
Eric Laurent73e26b62015-04-27 16:55:58 -07002479 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002480 default:
2481 break;
2482 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002483 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002484}
2485
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002486void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002487{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002488 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002489}
2490
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002491void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002492{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002493 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002494}
2495
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002496void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002497{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002498 mCallbackThread->setAsyncError();
2499}
2500
Eric Laurent3b4529e2013-09-05 18:09:19 -07002501void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002502{
2503 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002504 // reject out of sequence requests
2505 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2506 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002507 mWaitWorkCV.signal();
2508 }
2509}
2510
Eric Laurent3b4529e2013-09-05 18:09:19 -07002511void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002512{
2513 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002514 // reject out of sequence requests
2515 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002516 // Register discontinuity when HW drain is completed because that can cause
2517 // the timestamp frame position to reset to 0 for direct and offload threads.
2518 // (Out of sequence requests are ignored, since the discontinuity would be handled
2519 // elsewhere, e.g. in flush).
2520 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002521 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002522 mWaitWorkCV.signal();
2523 }
2524}
2525
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002526void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002527{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002528 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002529 mSampleRate = mOutput->getSampleRate();
2530 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002531 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002532 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002533 }
Andy Hung9a592762014-07-21 21:56:01 -07002534 if ((mType == MIXER || mType == DUPLICATING)
2535 && !isValidPcmSinkChannelMask(mChannelMask)) {
2536 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2537 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002538 }
Andy Hunge5412692014-05-16 11:25:07 -07002539 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002540 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002541
2542 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 status_t result = mOutput->stream->getFormat(&mHALFormat);
2544 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002545 // Get format from the shim, which will be different than the HAL format
2546 // if playing compressed audio over HDMI passthrough.
2547 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002548 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002549 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002550 }
Andy Hung6146c082014-03-18 11:56:15 -07002551 if ((mType == MIXER || mType == DUPLICATING)
2552 && !isValidPcmSinkFormat(mFormat)) {
2553 LOG_FATAL("HAL format %#x not supported for mixed output",
2554 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002555 }
Phil Burk062e67a2015-02-11 13:40:50 -08002556 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002557 result = mOutput->stream->getBufferSize(&mBufferSize);
2558 LOG_ALWAYS_FATAL_IF(result != OK,
2559 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002560 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002561 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002562 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002563 mFrameCount);
2564 }
2565
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002566 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2567 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002568 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002569 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570 }
2571 }
2572
Eric Laurentd1f69b02014-12-15 14:33:13 -08002573 mHwSupportsPause = false;
2574 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002575 bool supportsPause = false, supportsResume = false;
2576 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2577 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002578 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002579 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002580 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002581 } else if (supportsResume) {
2582 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002583 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002584 }
2585 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002586 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2587 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2588 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002589
Andy Hungfbfc3952015-01-15 13:33:51 -08002590 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2591 // For best precision, we use float instead of the associated output
2592 // device format (typically PCM 16 bit).
2593
2594 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2595 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2596 mBufferSize = mFrameSize * mFrameCount;
2597
2598 // TODO: We currently use the associated output device channel mask and sample rate.
2599 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2600 // (if a valid mask) to avoid premature downmix.
2601 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2602 // instead of the output device sample rate to avoid loss of high frequency information.
2603 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2604 }
2605
Andy Hung09a50072014-02-27 14:30:47 -08002606 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002607 double multiplier = 1.0;
2608 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2609 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002610 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2611 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002612
Eric Laurent81784c32012-11-19 14:55:58 -08002613 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2614 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2615 maxNormalFrameCount = maxNormalFrameCount & ~15;
2616 if (maxNormalFrameCount < minNormalFrameCount) {
2617 maxNormalFrameCount = minNormalFrameCount;
2618 }
2619 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2620 if (multiplier <= 1.0) {
2621 multiplier = 1.0;
2622 } else if (multiplier <= 2.0) {
2623 if (2 * mFrameCount <= maxNormalFrameCount) {
2624 multiplier = 2.0;
2625 } else {
2626 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2627 }
2628 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002629 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002630 }
2631 }
2632 mNormalFrameCount = multiplier * mFrameCount;
2633 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002634 if (mType == MIXER || mType == DUPLICATING) {
2635 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2636 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002637 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002638 mNormalFrameCount);
2639
Andy Hung08fb1742015-05-31 23:22:10 -07002640 // Check if we want to throttle the processing to no more than 2x normal rate
2641 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002642 mThreadThrottleTimeMs = 0;
2643 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002644 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2645
Andy Hung010a1a12014-03-13 13:57:33 -07002646 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2647 // Originally this was int16_t[] array, need to remove legacy implications.
2648 free(mSinkBuffer);
2649 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002650 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2651 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2652 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002653 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002654
Andy Hung69aed5f2014-02-25 17:24:40 -08002655 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2656 // drives the output.
2657 free(mMixerBuffer);
2658 mMixerBuffer = NULL;
2659 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002660 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002661 mMixerBufferSize = mNormalFrameCount * mChannelCount
2662 * audio_bytes_per_sample(mMixerBufferFormat);
2663 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2664 }
Andy Hung98ef9782014-03-04 14:46:50 -08002665 free(mEffectBuffer);
2666 mEffectBuffer = NULL;
2667 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002668 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002669 mEffectBufferSize = mNormalFrameCount * mChannelCount
2670 * audio_bytes_per_sample(mEffectBufferFormat);
2671 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2672 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002673
jiabin245cdd92018-12-07 17:55:15 -08002674 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2675 mChannelMask &= ~mHapticChannelMask;
2676 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2677 mChannelCount -= mHapticChannelCount;
2678
Eric Laurent81784c32012-11-19 14:55:58 -08002679 // force reconfiguration of effect chains and engines to take new buffer size and audio
2680 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002681 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002682 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2683 // matter.
2684 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2685 Vector< sp<EffectChain> > effectChains = mEffectChains;
2686 for (size_t i = 0; i < effectChains.size(); i ++) {
2687 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
2688 }
2689}
2690
Kevin Rocard069c2712018-03-29 19:09:14 -07002691void AudioFlinger::PlaybackThread::updateMetadata_l()
2692{
Kevin Rocard12381092018-04-11 09:19:59 -07002693 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2694 return; // That should not happen
2695 }
2696 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2697 for (const sp<Track> &track : mActiveTracks) {
2698 // Do not short-circuit as all hasChanged states must be reset
2699 // as all the metadata are going to be sent
2700 hasChanged |= track->readAndClearHasChanged();
2701 }
2702 if (!hasChanged) {
2703 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002704 }
2705 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002706 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002707 for (const sp<Track> &track : mActiveTracks) {
2708 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002709 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002710 }
Kevin Rocard12381092018-04-11 09:19:59 -07002711 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002712}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002713
Kevin Rocard12381092018-04-11 09:19:59 -07002714void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2715 const StreamOutHalInterface::SourceMetadata& metadata)
2716{
2717 mOutput->stream->updateSourceMetadata(metadata);
2718};
2719
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002720status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002721{
2722 if (halFrames == NULL || dspFrames == NULL) {
2723 return BAD_VALUE;
2724 }
2725 Mutex::Autolock _l(mLock);
2726 if (initCheck() != NO_ERROR) {
2727 return INVALID_OPERATION;
2728 }
Andy Hung818e7a32016-02-16 18:08:07 -08002729 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002730 *halFrames = framesWritten;
2731
2732 if (isSuspended()) {
2733 // return an estimation of rendered frames when the output is suspended
2734 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002735 *dspFrames = (uint32_t)
2736 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002737 return NO_ERROR;
2738 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002739 status_t status;
2740 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002741 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002742 *dspFrames = (size_t)frames;
2743 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002744 }
2745}
2746
Eric Laurent4c415062016-06-17 16:14:16 -07002747// hasAudioSession_l() must be called with ThreadBase::mLock held
2748uint32_t AudioFlinger::PlaybackThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08002749{
Eric Laurent81784c32012-11-19 14:55:58 -08002750 uint32_t result = 0;
2751 if (getEffectChain_l(sessionId) != 0) {
2752 result = EFFECT_SESSION;
2753 }
2754
2755 for (size_t i = 0; i < mTracks.size(); ++i) {
2756 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002757 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002758 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07002759 if (track->isFastTrack()) {
2760 result |= FAST_SESSION;
2761 }
Eric Laurent81784c32012-11-19 14:55:58 -08002762 break;
2763 }
2764 }
2765
2766 return result;
2767}
2768
Glenn Kastend848eb42016-03-08 13:42:11 -08002769uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002770{
2771 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2772 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2773 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2774 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2775 }
2776 for (size_t i = 0; i < mTracks.size(); i++) {
2777 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002778 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002779 return AudioSystem::getStrategyForStream(track->streamType());
2780 }
2781 }
2782 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2783}
2784
2785
Phil Burk062e67a2015-02-11 13:40:50 -08002786AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002787{
2788 Mutex::Autolock _l(mLock);
2789 return mOutput;
2790}
2791
Phil Burk062e67a2015-02-11 13:40:50 -08002792AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
2794 Mutex::Autolock _l(mLock);
2795 AudioStreamOut *output = mOutput;
2796 mOutput = NULL;
2797 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2798 // must push a NULL and wait for ack
2799 mOutputSink.clear();
2800 mPipeSink.clear();
2801 mNormalSink.clear();
2802 return output;
2803}
2804
2805// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002806sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002807{
2808 if (mOutput == NULL) {
2809 return NULL;
2810 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002811 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002812}
2813
2814uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2815{
2816 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2817}
2818
2819status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2820{
2821 if (!isValidSyncEvent(event)) {
2822 return BAD_VALUE;
2823 }
2824
2825 Mutex::Autolock _l(mLock);
2826
2827 for (size_t i = 0; i < mTracks.size(); ++i) {
2828 sp<Track> track = mTracks[i];
2829 if (event->triggerSession() == track->sessionId()) {
2830 (void) track->setSyncEvent(event);
2831 return NO_ERROR;
2832 }
2833 }
2834
2835 return NAME_NOT_FOUND;
2836}
2837
2838bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2839{
2840 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2841}
2842
2843void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2844 const Vector< sp<Track> >& tracksToRemove)
2845{
Andy Hungfe726a62018-09-27 15:17:25 -07002846 // Miscellaneous track cleanup when removed from the active list,
2847 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002848#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002849 for (const auto& track : tracksToRemove) {
2850 if (track->isExternalTrack()) {
2851 // to track the speaker usage
2852 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002853 }
2854 }
Andy Hungfe726a62018-09-27 15:17:25 -07002855#else
2856 (void)tracksToRemove; // suppress unused warning
2857#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002858}
2859
2860void AudioFlinger::PlaybackThread::checkSilentMode_l()
2861{
2862 if (!mMasterMute) {
2863 char value[PROPERTY_VALUE_MAX];
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002864 if (mOutDevice == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
2865 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2866 return;
2867 }
Eric Laurent81784c32012-11-19 14:55:58 -08002868 if (property_get("ro.audio.silent", value, "0") > 0) {
2869 char *endptr;
2870 unsigned long ul = strtoul(value, &endptr, 0);
2871 if (*endptr == '\0' && ul != 0) {
2872 ALOGD("Silence is golden");
2873 // The setprop command will not allow a property to be changed after
2874 // the first time it is set, so we don't have to worry about un-muting.
2875 setMasterMute_l(true);
2876 }
2877 }
2878 }
2879}
2880
2881// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002883{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002884 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002885 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002886 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002887 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002888
2889 // If an NBAIO sink is present, use it to write the normal mixer's submix
2890 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002891
Andy Hung010a1a12014-03-13 13:57:33 -07002892 const size_t count = mBytesRemaining / mFrameSize;
2893
Simon Wilson2d590962012-11-29 15:18:50 -08002894 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002895 // update the setpoint when AudioFlinger::mScreenState changes
2896 uint32_t screenState = AudioFlinger::mScreenState;
2897 if (screenState != mScreenState) {
2898 mScreenState = screenState;
2899 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2900 if (pipe != NULL) {
2901 pipe->setAvgFrames((mScreenState & 1) ?
2902 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2903 }
2904 }
Andy Hung010a1a12014-03-13 13:57:33 -07002905 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002906 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002907 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002908 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002909#ifdef TEE_SINK
2910 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2911#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002912 } else {
2913 bytesWritten = framesWritten;
2914 }
2915 // otherwise use the HAL / AudioStreamOut directly
2916 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002917 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002918
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002920 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2921 mWriteAckSequence += 2;
2922 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002923 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002924 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002925 }
Glenn Kasten767094d2013-08-23 13:51:43 -07002926 // FIXME We should have an implementation of timestamps for direct output threads.
2927 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002928 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Eric Laurent51716182016-02-29 18:00:56 -08002929
Eric Laurentbfb1b832013-01-07 09:53:42 -08002930 if (mUseAsyncWrite &&
2931 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2932 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002933 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002934 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002935 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002936 }
Eric Laurent81784c32012-11-19 14:55:58 -08002937 }
2938
Eric Laurent81784c32012-11-19 14:55:58 -08002939 mNumWrites++;
2940 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07002941 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002942 return bytesWritten;
2943}
2944
2945void AudioFlinger::PlaybackThread::threadLoop_drain()
2946{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002947 bool supportsDrain = false;
2948 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002949 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
2950 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002951 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
2952 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002953 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002954 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002955 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07002956 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002957 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002958 }
2959}
2960
2961void AudioFlinger::PlaybackThread::threadLoop_exit()
2962{
Eric Laurent275e8e92014-11-30 15:14:47 -08002963 {
2964 Mutex::Autolock _l(mLock);
2965 for (size_t i = 0; i < mTracks.size(); i++) {
2966 sp<Track> track = mTracks[i];
2967 track->invalidate();
2968 }
Andy Hungdae27702016-10-31 14:01:16 -07002969 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
2970 // After we exit there are no more track changes sent to BatteryNotifier
2971 // because that requires an active threadLoop.
2972 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
2973 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08002974 }
Eric Laurent81784c32012-11-19 14:55:58 -08002975}
2976
2977/*
2978The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08002979 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07002980 - mActiveSleepTimeUs from activeSleepTimeUs()
2981 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08002982 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
2983 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08002984 - maxPeriod from frame count and sample rate (MIXER only)
2985
2986The parameters that affect these derived values are:
2987 - frame count
2988 - frame size
2989 - sample rate
2990 - device type: A2DP or not
2991 - device latency
2992 - format: PCM or not
2993 - active sleep time
2994 - idle sleep time
2995*/
2996
2997void AudioFlinger::PlaybackThread::cacheParameters_l()
2998{
Andy Hung25c2dac2014-02-27 14:56:00 -08002999 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003000 mActiveSleepTimeUs = activeSleepTimeUs();
3001 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003002
3003 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3004 // truncating audio when going to standby.
3005 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
3006 if ((mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != 0) {
3007 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3008 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3009 }
3010 }
Eric Laurent81784c32012-11-19 14:55:58 -08003011}
3012
Eric Laurent13084622016-05-17 10:51:49 -07003013bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003014{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003015 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003016 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003017 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003018 size_t size = mTracks.size();
3019 for (size_t i = 0; i < size; i++) {
3020 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003021 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003022 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003023 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003024 }
3025 }
Eric Laurent13084622016-05-17 10:51:49 -07003026 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003027}
3028
Haynes Mathew George05317d22016-05-03 16:34:26 -07003029void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3030{
3031 Mutex::Autolock _l(mLock);
3032 invalidateTracks_l(streamType);
3033}
3034
Eric Laurent81784c32012-11-19 14:55:58 -08003035status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3036{
Glenn Kastend848eb42016-03-08 13:42:11 -08003037 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003038 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003039 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003040 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3041 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3042 &halInBuffer);
3043 if (result != OK) return result;
3044 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003045 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003046 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003047 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003048 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003049 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003050 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003051 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003052 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003053 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003054 &halInBuffer);
3055 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003056#ifdef FLOAT_EFFECT_CHAIN
3057 buffer = halInBuffer->audioBuffer()->f32;
3058#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003059 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003060#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003061 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3062 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003063 }
3064
3065 // Attach all tracks with same session ID to this chain.
3066 for (size_t i = 0; i < mTracks.size(); ++i) {
3067 sp<Track> track = mTracks[i];
3068 if (session == track->sessionId()) {
3069 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3070 buffer);
3071 track->setMainBuffer(buffer);
3072 chain->incTrackCnt();
3073 }
3074 }
3075
3076 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003077 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003078 if (session == track->sessionId()) {
3079 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3080 chain->incActiveTrackCnt();
3081 }
3082 }
3083 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003084 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003085 chain->setInBuffer(halInBuffer);
3086 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003087 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003088 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003089 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3090 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003091 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003092 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003093 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003094 // Effect chain for other sessions are inserted at beginning of effect
3095 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003096 // sessions is not important.
3097 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3098 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3099 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003100 size_t size = mEffectChains.size();
3101 size_t i = 0;
3102 for (i = 0; i < size; i++) {
3103 if (mEffectChains[i]->sessionId() < session) {
3104 break;
3105 }
3106 }
3107 mEffectChains.insertAt(chain, i);
3108 checkSuspendOnAddEffectChain_l(chain);
3109
3110 return NO_ERROR;
3111}
3112
3113size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3114{
Glenn Kastend848eb42016-03-08 13:42:11 -08003115 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003116
3117 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3118
3119 for (size_t i = 0; i < mEffectChains.size(); i++) {
3120 if (chain == mEffectChains[i]) {
3121 mEffectChains.removeAt(i);
3122 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003123 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003124 if (session == track->sessionId()) {
3125 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3126 chain.get(), session);
3127 chain->decActiveTrackCnt();
3128 }
3129 }
3130
3131 // detach all tracks with same session ID from this chain
3132 for (size_t i = 0; i < mTracks.size(); ++i) {
3133 sp<Track> track = mTracks[i];
3134 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003135 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003136 chain->decTrackCnt();
3137 }
3138 }
3139 break;
3140 }
3141 }
3142 return mEffectChains.size();
3143}
3144
3145status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003146 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003147{
3148 Mutex::Autolock _l(mLock);
3149 return attachAuxEffect_l(track, EffectId);
3150}
3151
3152status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003153 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003154{
3155 status_t status = NO_ERROR;
3156
3157 if (EffectId == 0) {
3158 track->setAuxBuffer(0, NULL);
3159 } else {
3160 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3161 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3162 if (effect != 0) {
3163 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3164 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3165 } else {
3166 status = INVALID_OPERATION;
3167 }
3168 } else {
3169 status = BAD_VALUE;
3170 }
3171 }
3172 return status;
3173}
3174
3175void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3176{
3177 for (size_t i = 0; i < mTracks.size(); ++i) {
3178 sp<Track> track = mTracks[i];
3179 if (track->auxEffectId() == effectId) {
3180 attachAuxEffect_l(track, 0);
3181 }
3182 }
3183}
3184
3185bool AudioFlinger::PlaybackThread::threadLoop()
3186{
Glenn Kasten388d5712017-04-07 14:38:41 -07003187 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003188
Eric Laurent81784c32012-11-19 14:55:58 -08003189 Vector< sp<Track> > tracksToRemove;
3190
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003191 mStandbyTimeNs = systemTime();
Andy Hung69488c42016-05-16 18:43:33 -07003192 nsecs_t lastWriteFinished = -1; // time last server write completed
3193 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003194
3195 // MIXER
3196 nsecs_t lastWarning = 0;
3197
3198 // DUPLICATING
3199 // FIXME could this be made local to while loop?
3200 writeFrames = 0;
3201
3202 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003203 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003204
3205 if (mType == MIXER) {
3206 sleepTimeShift = 0;
3207 }
3208
3209 CpuStats cpuStats;
3210 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3211
3212 acquireWakeLock();
3213
Glenn Kasteneef598c2017-04-03 14:41:13 -07003214 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3215 // thread associated with this PlaybackThread.
3216 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3217 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003218 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3219 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003220 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003221 const char *logString = NULL;
3222
rago1bb90822017-05-02 18:31:48 -07003223 // Estimated time for next buffer to be written to hal. This is used only on
3224 // suspended mode (for now) to help schedule the wait time until next iteration.
3225 nsecs_t timeLoopNextNs = 0;
3226
Eric Laurent664539d2013-09-23 18:24:31 -07003227 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003228
Andy Hungf3234512018-07-03 14:51:47 -07003229 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3230 // TODO: add confirmation checks:
3231 // 1) DIRECT threads and linear PCM format really resets to 0?
3232 // 2) Is frame count really valid if not linear pcm?
3233 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3234 if (mType == OFFLOAD || mType == DIRECT) {
3235 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3236 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003237 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003238
Eric Laurent81784c32012-11-19 14:55:58 -08003239 while (!exitPending())
3240 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003241 // Log merge requests are performed during AudioFlinger binder transactions, but
3242 // that does not cover audio playback. It's requested here for that reason.
3243 mAudioFlinger->requestLogMerge();
3244
Eric Laurent81784c32012-11-19 14:55:58 -08003245 cpuStats.sample(myName);
3246
3247 Vector< sp<EffectChain> > effectChains;
3248
Andy Hung2dbffc22018-08-08 18:50:41 -07003249 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3250 //
3251 // Note: we access outDevice() outside of mLock.
3252 if (isMsdDevice() && (outDevice() & AUDIO_DEVICE_OUT_BUS) != 0) {
3253 // Here, we try for the AF lock, but do not block on it as the latency
3254 // is more informational.
3255 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3256 std::vector<PatchPanel::SoftwarePatch> swPatches;
3257 double latencyMs;
3258 status_t status = INVALID_OPERATION;
3259 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3260 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3261 && swPatches.size() > 0) {
3262 status = swPatches[0].getLatencyMs_l(&latencyMs);
3263 downstreamPatchHandle = swPatches[0].getPatchHandle();
3264 }
3265 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003266 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003267 lastDownstreamPatchHandle = downstreamPatchHandle;
3268 }
3269 if (status == OK) {
3270 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003271 // latency of 5 seconds).
3272 const double minLatency = 0., maxLatency = 5000.;
3273 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003274 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003275 } else {
3276 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003277 if (latencyMs < minLatency) latencyMs = minLatency;
3278 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003279 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003280 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003281 }
3282 mAudioFlinger->mLock.unlock();
3283 }
3284 } else {
3285 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3286 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003287 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003288 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3289 }
3290 }
3291
Eric Laurent81784c32012-11-19 14:55:58 -08003292 { // scope for mLock
3293
3294 Mutex::Autolock _l(mLock);
3295
Eric Laurent021cf962014-05-13 10:18:14 -07003296 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003297
Glenn Kasteneef598c2017-04-03 14:41:13 -07003298 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003299 if (logString != NULL) {
3300 mNBLogWriter->logTimestamp();
3301 mNBLogWriter->log(logString);
3302 logString = NULL;
3303 }
3304
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003305 // Collect timestamp statistics for the Playback Thread types that support it.
3306 if (mType == MIXER
3307 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003308 || mType == DIRECT
3309 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003310 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003311 // and associate with the sink frames written out. We need
3312 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003313 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003314 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003315 if (mStandby) {
3316 mTimestampVerifier.discontinuity();
3317 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3318 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3319 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3320 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003321
3322 if (isTimestampCorrectionEnabled()) {
3323 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3324 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3325 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3326 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3327 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3328 = correctedTimestamp.mFrames;
3329 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3330 = correctedTimestamp.mTimeNs;
3331 ALOGV("TS_AFTER: %d %lld %lld", id(),
3332 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3333 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003334
3335 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003336 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003337 const int64_t newPosition =
3338 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003339 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003340 // prevent retrograde
3341 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3342 newPosition,
3343 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3344 - mSuspendedFrames));
3345 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003346 }
3347
Andy Hung818e7a32016-02-16 18:08:07 -08003348 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003349 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003350
3351 // We keep track of the last valid kernel position in case we are in underrun
3352 // and the normal mixer period is the same as the fast mixer period, or there
3353 // is some error from the HAL.
3354 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3355 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3356 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3357 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3358 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3359
3360 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3361 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3362 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3363 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003364 }
3365
3366 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3367 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003368 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003369 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003370 }
3371
Andy Hung818e7a32016-02-16 18:08:07 -08003372 // copy over kernel info
3373 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003374 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3375 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003376 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3377 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003378 } else {
3379 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003380 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003381
Andy Hungc54b1ff2016-02-23 14:07:07 -08003382 // mFramesWritten for non-offloaded tracks are contiguous
3383 // even after standby() is called. This is useful for the track frame
3384 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003385 bool serverLocationUpdate = false;
3386 if (mFramesWritten != lastFramesWritten) {
3387 serverLocationUpdate = true;
3388 lastFramesWritten = mFramesWritten;
3389 }
3390 // Only update timestamps if there is a meaningful change.
3391 // Either the kernel timestamp must be valid or we have written something.
3392 if (kernelLocationUpdate || serverLocationUpdate) {
3393 if (serverLocationUpdate) {
3394 // use the time before we called the HAL write - it is a bit more accurate
3395 // to when the server last read data than the current time here.
3396 //
3397 // If we haven't written anything, mLastWriteTime will be -1
3398 // and we use systemTime().
3399 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
3400 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastWriteTime == -1
3401 ? systemTime() : mLastWriteTime;
3402 }
Andy Hungdae27702016-10-31 14:01:16 -07003403
3404 for (const sp<Track> &t : mActiveTracks) {
3405 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003406 t->updateTrackFrameInfo(
3407 t->mAudioTrackServerProxy->framesReleased(),
3408 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003409 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003410 mTimestamp);
3411 }
Andy Hunge10393e2015-06-12 13:59:33 -07003412 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003413 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003414 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003415#if 0
3416 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003417 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003418 timespec ts;
3419 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003420 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003421 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003422 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003423 }
3424 ++z;
3425#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003426 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003427 if (mSignalPending) {
3428 // A signal was raised while we were unlocked
3429 mSignalPending = false;
3430 } else if (waitingAsyncCallback_l()) {
3431 if (exitPending()) {
3432 break;
3433 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003434 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003435 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003436 releaseWakeLock_l();
3437 released = true;
3438 }
Andy Hung10cbff12017-02-21 17:30:14 -08003439
3440 const int64_t waitNs = computeWaitTimeNs_l();
3441 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3442 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3443 if (status == TIMED_OUT) {
3444 mSignalPending = true; // if timeout recheck everything
3445 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003446 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003447 if (released) {
3448 acquireWakeLock_l();
3449 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003450 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3451 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003452
3453 continue;
3454 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003455 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003456 isSuspended()) {
3457 // put audio hardware into standby after short delay
3458 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003459
3460 threadLoop_standby();
3461
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003462 // This is where we go into standby
3463 if (!mStandby) {
3464 LOG_AUDIO_STATE();
3465 }
Eric Laurent81784c32012-11-19 14:55:58 -08003466 mStandby = true;
3467 }
3468
Eric Tan39ec8d62018-07-24 09:49:29 -07003469 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003470 // we're about to wait, flush the binder command buffer
3471 IPCThreadState::self()->flushCommands();
3472
3473 clearOutputTracks();
3474
3475 if (exitPending()) {
3476 break;
3477 }
3478
3479 releaseWakeLock_l();
3480 // wait until we have something to do...
3481 ALOGV("%s going to sleep", myName.string());
3482 mWaitWorkCV.wait(mLock);
3483 ALOGV("%s waking up", myName.string());
3484 acquireWakeLock_l();
3485
3486 mMixerStatus = MIXER_IDLE;
3487 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3488 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003489 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003490 checkSilentMode_l();
3491
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003492 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3493 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003494 if (mType == MIXER) {
3495 sleepTimeShift = 0;
3496 }
3497
3498 continue;
3499 }
3500 }
Eric Laurent81784c32012-11-19 14:55:58 -08003501 // mMixerStatusIgnoringFastTracks is also updated internally
3502 mMixerStatus = prepareTracks_l(&tracksToRemove);
3503
Andy Hungdae27702016-10-31 14:01:16 -07003504 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003505
Kevin Rocard069c2712018-03-29 19:09:14 -07003506 updateMetadata_l();
3507
Eric Laurent81784c32012-11-19 14:55:58 -08003508 // prevent any changes in effect chain list and in each effect chain
3509 // during mixing and effect process as the audio buffers could be deleted
3510 // or modified if an effect is created or deleted
3511 lockEffectChains_l(effectChains);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003512 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003513
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514 if (mBytesRemaining == 0) {
3515 mCurrentWriteLength = 0;
3516 if (mMixerStatus == MIXER_TRACKS_READY) {
3517 // threadLoop_mix() sets mCurrentWriteLength
3518 threadLoop_mix();
3519 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3520 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003521 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003522 // must be written to HAL
3523 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003524 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003525 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 }
3527 }
Andy Hung98ef9782014-03-04 14:46:50 -08003528 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003529 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003530 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3531 // or mSinkBuffer (if there are no effects).
3532 //
3533 // This is done pre-effects computation; if effects change to
3534 // support higher precision, this needs to move.
3535 //
3536 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003537 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003538 if (mMixerBufferValid) {
3539 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3540 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3541
Andy Hung2ddee192015-12-18 17:34:44 -08003542 // mono blend occurs for mixer threads only (not direct or offloaded)
3543 // and is handled here if we're going directly to the sink.
3544 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003545 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3546 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003547 }
3548
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003549 if (!hasFastMixer()) {
3550 // Balance must take effect after mono conversion.
3551 // We do it here if there is no FastMixer.
3552 // mBalance detects zero balance within the class for speed (not needed here).
3553 mBalance.setBalance(mMasterBalance.load());
3554 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3555 }
3556
Andy Hung98ef9782014-03-04 14:46:50 -08003557 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003558 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3559
3560 // If we're going directly to the sink and there are haptic channels,
3561 // we should adjust channels as the sample data is partially interleaved
3562 // in this case.
3563 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3564 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3565 mChannelCount + mHapticChannelCount,
3566 audio_bytes_per_sample(format),
3567 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3568 }
Andy Hung98ef9782014-03-04 14:46:50 -08003569 }
3570
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 mBytesRemaining = mCurrentWriteLength;
3572 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003573 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3574 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3575 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3576 mBytesWritten += mBytesRemaining;
3577 mFramesWritten += framesRemaining;
3578 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003579 mBytesRemaining = 0;
3580 }
Eric Laurent81784c32012-11-19 14:55:58 -08003581
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003583 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584 for (size_t i = 0; i < effectChains.size(); i ++) {
3585 effectChains[i]->process_l();
3586 }
Eric Laurent81784c32012-11-19 14:55:58 -08003587 }
3588 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003589 // Process effect chains for offloaded thread even if no audio
3590 // was read from audio track: process only updates effect state
3591 // and thus does have to be synchronized with audio writes but may have
3592 // to be called while waiting for async write callback
3593 if (mType == OFFLOAD) {
3594 for (size_t i = 0; i < effectChains.size(); i ++) {
3595 effectChains[i]->process_l();
3596 }
3597 }
Eric Laurent81784c32012-11-19 14:55:58 -08003598
Andy Hung98ef9782014-03-04 14:46:50 -08003599 // Only if the Effects buffer is enabled and there is data in the
3600 // Effects buffer (buffer valid), we need to
3601 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003602 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003603 if (mEffectBufferValid) {
3604 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003605
3606 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003607 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3608 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003609 }
3610
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003611 if (!hasFastMixer()) {
3612 // Balance must take effect after mono conversion.
3613 // We do it here if there is no FastMixer.
3614 // mBalance detects zero balance within the class for speed (not needed here).
3615 mBalance.setBalance(mMasterBalance.load());
3616 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3617 }
3618
Andy Hung98ef9782014-03-04 14:46:50 -08003619 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003620 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3621 // The sample data is partially interleaved when haptic channels exist,
3622 // we need to adjust channels here.
3623 if (mHapticChannelCount > 0) {
3624 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3625 mChannelCount + mHapticChannelCount,
3626 audio_bytes_per_sample(mFormat),
3627 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3628 }
Andy Hung98ef9782014-03-04 14:46:50 -08003629 }
3630
Eric Laurent81784c32012-11-19 14:55:58 -08003631 // enable changes in effect chain
3632 unlockEffectChains(effectChains);
3633
Eric Laurentbfb1b832013-01-07 09:53:42 -08003634 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003635 // mSleepTimeUs == 0 means we must write to audio hardware
3636 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003637 ssize_t ret = 0;
Andy Hung69488c42016-05-16 18:43:33 -07003638 // We save lastWriteFinished here, as previousLastWriteFinished,
3639 // for throttling. On thread start, previousLastWriteFinished will be
3640 // set to -1, which properly results in no throttling after the first write.
3641 nsecs_t previousLastWriteFinished = lastWriteFinished;
3642 nsecs_t delta = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003643 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003644 // FIXME rewrite to reduce number of system calls
3645 mLastWriteTime = systemTime(); // also used for dumpsys
Andy Hung08fb1742015-05-31 23:22:10 -07003646 ret = threadLoop_write();
Andy Hung69488c42016-05-16 18:43:33 -07003647 lastWriteFinished = systemTime();
3648 delta = lastWriteFinished - mLastWriteTime;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 if (ret < 0) {
3650 mBytesRemaining = 0;
3651 } else {
3652 mBytesWritten += ret;
3653 mBytesRemaining -= ret;
Andy Hungc54b1ff2016-02-23 14:07:07 -08003654 mFramesWritten += ret / mFrameSize;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003655 }
3656 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3657 (mMixerStatus == MIXER_DRAIN_ALL)) {
3658 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003659 }
Andy Hung08fb1742015-05-31 23:22:10 -07003660 if (mType == MIXER && !mStandby) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003661 // write blocked detection
Andy Hung08fb1742015-05-31 23:22:10 -07003662 if (delta > maxPeriod) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003663 mNumDelayedWrites++;
Andy Hung69488c42016-05-16 18:43:33 -07003664 if ((lastWriteFinished - lastWarning) > kWarningThrottleNs) {
Glenn Kasten4944acb2013-08-19 08:39:20 -07003665 ATRACE_NAME("underrun");
3666 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003667 (unsigned long long) ns2ms(delta), mNumDelayedWrites, this);
Andy Hung69488c42016-05-16 18:43:33 -07003668 lastWarning = lastWriteFinished;
Glenn Kasten4944acb2013-08-19 08:39:20 -07003669 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 }
Andy Hung08fb1742015-05-31 23:22:10 -07003671
3672 if (mThreadThrottle
3673 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
3674 && ret > 0) { // we wrote something
3675 // Limit MixerThread data processing to no more than twice the
3676 // expected processing rate.
3677 //
3678 // This helps prevent underruns with NuPlayer and other applications
3679 // which may set up buffers that are close to the minimum size, or use
3680 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3681 //
3682 // The throttle smooths out sudden large data drains from the device,
3683 // e.g. when it comes out of standby, which often causes problems with
3684 // (1) mixer threads without a fast mixer (which has its own warm-up)
3685 // (2) minimum buffer sized tracks (even if the track is full,
3686 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003687 //
3688 // Total time spent in last processing cycle equals time spent in
3689 // 1. threadLoop_write, as well as time spent in
3690 // 2. threadLoop_mix (significant for heavy mixing, especially
3691 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003692
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003693 // it's OK if deltaMs (and deltaNs) is an overestimate.
3694 nsecs_t deltaNs;
3695 // deltaNs = lastWriteFinished - previousLastWriteFinished;
3696 __builtin_sub_overflow(
3697 lastWriteFinished,previousLastWriteFinished, &deltaNs);
3698 const int32_t deltaMs = deltaNs / 1000000;
3699
Ivan Lozanoea04d392017-11-07 14:37:07 -08003700 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003701 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3702 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003703 // notify of throttle start on verbose log
3704 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3705 "mixer(%p) throttle begin:"
3706 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003707 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003708 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003709 // Throttle must be attributed to the previous mixer loop's write time
3710 // to allow back-to-back throttling.
3711 lastWriteFinished += throttleMs * 1000000;
Andy Hung40eb1a12015-06-18 13:42:02 -07003712 } else {
3713 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3714 if (diff > 0) {
3715 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003716 // but prevent spamming for bluetooth
Jakub Pawlowski0568ded2018-03-14 11:20:05 -07003717 ALOGD_IF(!audio_is_a2dp_out_device(outDevice()) &&
3718 !audio_is_hearing_aid_out_device(outDevice()),
Andy Hung3ea004d2016-05-05 16:48:37 -07003719 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003720 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3721 }
Andy Hung08fb1742015-05-31 23:22:10 -07003722 }
3723 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003724 }
Eric Laurent81784c32012-11-19 14:55:58 -08003725
Eric Laurentbfb1b832013-01-07 09:53:42 -08003726 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003727 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003728 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003729 // suspended requires accurate metering of sleep time.
3730 if (isSuspended()) {
3731 // advance by expected sleepTime
3732 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3733 const nsecs_t nowNs = systemTime();
3734
3735 // compute expected next time vs current time.
3736 // (negative deltas are treated as delays).
3737 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3738 if (deltaNs < -kMaxNextBufferDelayNs) {
3739 // Delays longer than the max allowed trigger a reset.
3740 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3741 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3742 timeLoopNextNs = nowNs + deltaNs;
3743 } else if (deltaNs < 0) {
3744 // Delays within the max delay allowed: zero the delta/sleepTime
3745 // to help the system catch up in the next iteration(s)
3746 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3747 deltaNs = 0;
3748 }
3749 // update sleep time (which is >= 0)
3750 mSleepTimeUs = deltaNs / 1000;
3751 }
Eric Laurente93cc032016-05-05 10:15:10 -07003752 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3753 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003754 }
Glenn Kastene7754022014-10-31 12:11:26 -07003755 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003756 }
Eric Laurent81784c32012-11-19 14:55:58 -08003757 }
3758
3759 // Finally let go of removed track(s), without the lock held
3760 // since we can't guarantee the destructors won't acquire that
3761 // same lock. This will also mutate and push a new fast mixer state.
3762 threadLoop_removeTracks(tracksToRemove);
3763 tracksToRemove.clear();
3764
3765 // FIXME I don't understand the need for this here;
3766 // it was in the original code but maybe the
3767 // assignment in saveOutputTracks() makes this unnecessary?
3768 clearOutputTracks();
3769
3770 // Effect chains will be actually deleted here if they were removed from
3771 // mEffectChains list during mixing or effects processing
3772 effectChains.clear();
3773
3774 // FIXME Note that the above .clear() is no longer necessary since effectChains
3775 // is now local to this block, but will keep it for now (at least until merge done).
3776 }
3777
Eric Laurentbfb1b832013-01-07 09:53:42 -08003778 threadLoop_exit();
3779
Eric Laurentcf817a22014-08-04 20:36:31 -07003780 if (!mStandby) {
3781 threadLoop_standby();
3782 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003783 }
3784
3785 releaseWakeLock();
3786
3787 ALOGV("Thread %p type %d exiting", this, mType);
3788 return false;
3789}
3790
Eric Laurentbfb1b832013-01-07 09:53:42 -08003791// removeTracks_l() must be called with ThreadBase::mLock held
3792void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3793{
Andy Hungfe726a62018-09-27 15:17:25 -07003794 for (const auto& track : tracksToRemove) {
3795 mActiveTracks.remove(track);
3796 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3797 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3798 if (chain != 0) {
3799 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3800 __func__, track->id(), chain.get(), track->sessionId());
3801 chain->decActiveTrackCnt();
3802 }
3803 // If an external client track, inform APM we're no longer active, and remove if needed.
3804 // We do this under lock so that the state is consistent if the Track is destroyed.
3805 if (track->isExternalTrack()) {
3806 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003807 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003808 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003809 }
3810 }
Andy Hungfe726a62018-09-27 15:17:25 -07003811 if (track->isTerminated()) {
3812 // remove from our tracks vector
3813 removeTrack_l(track);
3814 }
jiabin57303cc2018-12-18 15:45:57 -08003815 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3816 && mHapticChannelCount > 0) {
3817 mLock.unlock();
3818 // Unlock due to VibratorService will lock for this call and will
3819 // call Tracks.mute/unmute which also require thread's lock.
3820 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3821 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003822 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003823 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003824}
Eric Laurent81784c32012-11-19 14:55:58 -08003825
Eric Laurentaccc1472013-09-20 09:36:34 -07003826status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3827{
3828 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003829 ExtendedTimestamp ets;
3830 status_t status = mNormalSink->getTimestamp(ets);
3831 if (status == NO_ERROR) {
3832 status = ets.getBestTimestamp(&timestamp);
3833 }
3834 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003835 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003836 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003837 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003838 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003839 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003840 if (mDownstreamLatencyStatMs.getN() > 0) {
3841 const uint32_t positionOffset =
3842 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3843 if (positionOffset > timestamp.mPosition) {
3844 timestamp.mPosition = 0;
3845 } else {
3846 timestamp.mPosition -= positionOffset;
3847 }
3848 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003849 return NO_ERROR;
3850 }
3851 }
3852 return INVALID_OPERATION;
3853}
Eric Laurent1c333e22014-05-20 10:48:17 -07003854
Eric Laurent054d9d32015-04-24 08:48:48 -07003855status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
3856 audio_patch_handle_t *handle)
3857{
Andy Hungf60abce2016-08-26 11:37:54 -07003858 status_t status;
3859 if (property_get_bool("af.patch_park", false /* default_value */)) {
3860 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3861 // or if HAL does not properly lock against access.
3862 AutoPark<FastMixer> park(mFastMixer);
3863 status = PlaybackThread::createAudioPatch_l(patch, handle);
3864 } else {
3865 status = PlaybackThread::createAudioPatch_l(patch, handle);
3866 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003867 return status;
3868}
3869
Eric Laurent1c333e22014-05-20 10:48:17 -07003870status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
3871 audio_patch_handle_t *handle)
3872{
3873 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003874
3875 // store new device and send to effects
3876 audio_devices_t type = AUDIO_DEVICE_NONE;
3877 for (unsigned int i = 0; i < patch->num_sinks; i++) {
3878 type |= patch->sinks[i].ext.device.type;
3879 }
3880
François Gaffie0c280aa2018-07-25 10:02:15 +02003881 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07003882#ifdef ADD_BATTERY_DATA
3883 // when changing the audio output device, call addBatteryData to notify
3884 // the change
3885 if (mOutDevice != type) {
3886 uint32_t params = 0;
3887 // check whether speaker is on
3888 if (type & AUDIO_DEVICE_OUT_SPEAKER) {
3889 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07003890 }
3891
Eric Laurent054d9d32015-04-24 08:48:48 -07003892 audio_devices_t deviceWithoutSpeaker
3893 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
3894 // check if any other device (except speaker) is on
3895 if (type & deviceWithoutSpeaker) {
3896 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
3897 }
3898
3899 if (params != 0) {
3900 addBatteryData(params);
3901 }
3902 }
3903#endif
3904
3905 for (size_t i = 0; i < mEffectChains.size(); i++) {
3906 mEffectChains[i]->setDevice_l(type);
3907 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003908
3909 // mPrevOutDevice is the latest device set by createAudioPatch_l(). It is not set when
3910 // the thread is created so that the first patch creation triggers an ioConfigChanged callback
François Gaffie0c280aa2018-07-25 10:02:15 +02003911 bool configChanged = (mPrevOutDevice != type) || (mDeviceId != sinkPortId);
Eric Laurent054d9d32015-04-24 08:48:48 -07003912 mOutDevice = type;
Eric Laurent296fb132015-05-01 11:38:42 -07003913 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07003914
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003915 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003916 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3917 status = hwDevice->createAudioPatch(patch->num_sources,
3918 patch->sources,
3919 patch->num_sinks,
3920 patch->sinks,
3921 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003922 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003923 char *address;
3924 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
3925 //FIXME: we only support address on first sink with HAL version < 3.0
3926 address = audio_device_address_to_parameter(
3927 patch->sinks[0].ext.device.type,
3928 patch->sinks[0].ext.device.address);
3929 } else {
3930 address = (char *)calloc(1, 1);
3931 }
3932 AudioParameter param = AudioParameter(String8(address));
3933 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07003934 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003935 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07003936 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07003937 }
Eric Laurente8726fe2015-06-26 09:39:24 -07003938 if (configChanged) {
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07003939 mPrevOutDevice = type;
François Gaffie0c280aa2018-07-25 10:02:15 +02003940 mDeviceId = sinkPortId;
Eric Laurente8726fe2015-06-26 09:39:24 -07003941 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
3942 }
Eric Laurent1c333e22014-05-20 10:48:17 -07003943 return status;
3944}
3945
Eric Laurent054d9d32015-04-24 08:48:48 -07003946status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3947{
Andy Hungf60abce2016-08-26 11:37:54 -07003948 status_t status;
3949 if (property_get_bool("af.patch_park", false /* default_value */)) {
3950 // Park FastMixer to avoid potential DOS issues with writing to the HAL
3951 // or if HAL does not properly lock against access.
3952 AutoPark<FastMixer> park(mFastMixer);
3953 status = PlaybackThread::releaseAudioPatch_l(handle);
3954 } else {
3955 status = PlaybackThread::releaseAudioPatch_l(handle);
3956 }
Eric Laurent054d9d32015-04-24 08:48:48 -07003957 return status;
3958}
3959
Eric Laurent1c333e22014-05-20 10:48:17 -07003960status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
3961{
3962 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07003963
3964 mOutDevice = AUDIO_DEVICE_NONE;
3965
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003966 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07003967 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
3968 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003969 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07003970 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07003971 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003972 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07003973 }
3974 return status;
3975}
3976
Eric Laurent83b88082014-06-20 18:31:16 -07003977void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
3978{
3979 Mutex::Autolock _l(mLock);
3980 mTracks.add(track);
3981}
3982
3983void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
3984{
3985 Mutex::Autolock _l(mLock);
3986 destroyTrack_l(track);
3987}
3988
Mikhail Naganovdc769682018-05-04 15:34:08 -07003989void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07003990{
Mikhail Naganovdc769682018-05-04 15:34:08 -07003991 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07003992 config->role = AUDIO_PORT_ROLE_SOURCE;
3993 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
3994 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07003995 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
3996 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
3997 config->flags.output = mOutput->flags;
3998 }
Eric Laurent83b88082014-06-20 18:31:16 -07003999}
4000
Eric Laurent81784c32012-11-19 14:55:58 -08004001// ----------------------------------------------------------------------------
4002
4003AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurent72e3f392015-05-20 14:43:50 -07004004 audio_io_handle_t id, audio_devices_t device, bool systemReady, type_t type)
4005 : PlaybackThread(audioFlinger, output, id, device, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004006 // mAudioMixer below
4007 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004008 mFastMixerFutex(0),
4009 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004010 // mOutputSink below
4011 // mPipeSink below
4012 // mNormalSink below
4013{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004014 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08004015 ALOGV("MixerThread() id=%d device=%#x type=%d", id, device, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004016 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004017 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004018 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4019 mNormalFrameCount);
4020 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4021
Andy Hungfbfc3952015-01-15 13:33:51 -08004022 if (type == DUPLICATING) {
4023 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4024 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4025 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4026 return;
4027 }
Eric Laurent81784c32012-11-19 14:55:58 -08004028 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004029 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004030 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004031 const NBAIO_Format offers[1] = {Format_from_SR_C(
4032 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004033#if !LOG_NDEBUG
4034 ssize_t index =
4035#else
4036 (void)
4037#endif
4038 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004039 ALOG_ASSERT(index == 0);
4040
4041 // initialize fast mixer depending on configuration
4042 bool initFastMixer;
4043 switch (kUseFastMixer) {
4044 case FastMixer_Never:
4045 initFastMixer = false;
4046 break;
4047 case FastMixer_Always:
4048 initFastMixer = true;
4049 break;
4050 case FastMixer_Static:
4051 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004052 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4053 // where the period is less than an experimentally determined threshold that can be
4054 // scheduled reliably with CFS. However, the BT A2DP HAL is
4055 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4056 initFastMixer = mFrameCount < mNormalFrameCount
4057 && (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004058 break;
4059 }
Andy Hungfda69402017-02-15 14:33:12 -08004060 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4061 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4062 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004063 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004064 audio_format_t fastMixerFormat;
4065 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4066 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4067 } else {
4068 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4069 }
4070 if (mFormat != fastMixerFormat) {
4071 // change our Sink format to accept our intermediate precision
4072 mFormat = fastMixerFormat;
4073 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004074 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004075 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4076 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4077 }
Eric Laurent81784c32012-11-19 14:55:58 -08004078
4079 // create a MonoPipe to connect our submix to FastMixer
4080 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004081
Andy Hung1258c1a2014-05-23 21:22:17 -07004082 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004083 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004084 format.mFormat = fastMixerFormat;
4085 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4086
Eric Laurent81784c32012-11-19 14:55:58 -08004087 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4088 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4089 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4090 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4091 const NBAIO_Format offers[1] = {format};
4092 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004093#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004094 ssize_t index =
4095#else
4096 (void)
4097#endif
4098 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004099 ALOG_ASSERT(index == 0);
4100 monoPipe->setAvgFrames((mScreenState & 1) ?
4101 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4102 mPipeSink = monoPipe;
4103
Eric Laurent81784c32012-11-19 14:55:58 -08004104 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004105 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004106 FastMixerStateQueue *sq = mFastMixer->sq();
4107#ifdef STATE_QUEUE_DUMP
4108 sq->setObserverDump(&mStateQueueObserverDump);
4109 sq->setMutatorDump(&mStateQueueMutatorDump);
4110#endif
4111 FastMixerState *state = sq->begin();
4112 FastTrack *fastTrack = &state->mFastTracks[0];
4113 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4114 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4115 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004116 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4117 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004118 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004119 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004120 fastTrack->mGeneration++;
4121 state->mFastTracksGen++;
4122 state->mTrackMask = 1;
4123 // fast mixer will use the HAL output sink
4124 state->mOutputSink = mOutputSink.get();
4125 state->mOutputSinkGen++;
4126 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004127 // specify sink channel mask when haptic channel mask present as it can not
4128 // be calculated directly from channel count
4129 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4130 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004131 state->mCommand = FastMixerState::COLD_IDLE;
4132 // already done in constructor initialization list
4133 //mFastMixerFutex = 0;
4134 state->mColdFutexAddr = &mFastMixerFutex;
4135 state->mColdGen++;
4136 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004137 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4138 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004139 sq->end();
4140 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4141
Eric Tan0513b5d2018-09-17 10:32:48 -07004142 NBLog::thread_info_t info;
4143 info.id = mId;
4144 info.type = NBLog::FASTMIXER;
4145 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4146
Eric Laurent81784c32012-11-19 14:55:58 -08004147 // start the fast mixer
4148 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4149 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004150 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004151 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004152
4153#ifdef AUDIO_WATCHDOG
4154 // create and start the watchdog
4155 mAudioWatchdog = new AudioWatchdog();
4156 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4157 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4158 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004159 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004160#endif
Andy Hung8946a282018-04-19 20:04:56 -07004161 } else {
4162#ifdef TEE_SINK
4163 // Only use the MixerThread tee if there is no FastMixer.
4164 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4165 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4166#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004167 }
4168
4169 switch (kUseFastMixer) {
4170 case FastMixer_Never:
4171 case FastMixer_Dynamic:
4172 mNormalSink = mOutputSink;
4173 break;
4174 case FastMixer_Always:
4175 mNormalSink = mPipeSink;
4176 break;
4177 case FastMixer_Static:
4178 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4179 break;
4180 }
4181}
4182
4183AudioFlinger::MixerThread::~MixerThread()
4184{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004185 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004186 FastMixerStateQueue *sq = mFastMixer->sq();
4187 FastMixerState *state = sq->begin();
4188 if (state->mCommand == FastMixerState::COLD_IDLE) {
4189 int32_t old = android_atomic_inc(&mFastMixerFutex);
4190 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004191 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004192 }
4193 }
4194 state->mCommand = FastMixerState::EXIT;
4195 sq->end();
4196 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4197 mFastMixer->join();
4198 // Though the fast mixer thread has exited, it's state queue is still valid.
4199 // We'll use that extract the final state which contains one remaining fast track
4200 // corresponding to our sub-mix.
4201 state = sq->begin();
4202 ALOG_ASSERT(state->mTrackMask == 1);
4203 FastTrack *fastTrack = &state->mFastTracks[0];
4204 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4205 delete fastTrack->mBufferProvider;
4206 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004207 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004208#ifdef AUDIO_WATCHDOG
4209 if (mAudioWatchdog != 0) {
4210 mAudioWatchdog->requestExit();
4211 mAudioWatchdog->requestExitAndWait();
4212 mAudioWatchdog.clear();
4213 }
4214#endif
4215 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004216 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004217 delete mAudioMixer;
4218}
4219
4220
4221uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4222{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004223 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004224 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4225 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4226 }
4227 return latency;
4228}
4229
Eric Laurentbfb1b832013-01-07 09:53:42 -08004230ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004231{
4232 // FIXME we should only do one push per cycle; confirm this is true
4233 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004234 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004235 FastMixerStateQueue *sq = mFastMixer->sq();
4236 FastMixerState *state = sq->begin();
4237 if (state->mCommand != FastMixerState::MIX_WRITE &&
4238 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4239 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004240
4241 // FIXME workaround for first HAL write being CPU bound on some devices
4242 ATRACE_BEGIN("write");
4243 mOutput->write((char *)mSinkBuffer, 0);
4244 ATRACE_END();
4245
Eric Laurent81784c32012-11-19 14:55:58 -08004246 int32_t old = android_atomic_inc(&mFastMixerFutex);
4247 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004248 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004249 }
4250#ifdef AUDIO_WATCHDOG
4251 if (mAudioWatchdog != 0) {
4252 mAudioWatchdog->resume();
4253 }
4254#endif
4255 }
4256 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004257#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004258 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004259 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004260#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004261 sq->end();
4262 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4263 if (kUseFastMixer == FastMixer_Dynamic) {
4264 mNormalSink = mPipeSink;
4265 }
4266 } else {
4267 sq->end(false /*didModify*/);
4268 }
4269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004270 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004271}
4272
4273void AudioFlinger::MixerThread::threadLoop_standby()
4274{
4275 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004276 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004277 FastMixerStateQueue *sq = mFastMixer->sq();
4278 FastMixerState *state = sq->begin();
4279 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004280 // Report any frames trapped in the Monopipe
4281 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4282 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4283 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4284 "monoPipeWritten:%lld monoPipeLeft:%lld",
4285 (long long)mFramesWritten, (long long)mSuspendedFrames,
4286 (long long)mPipeSink->framesWritten(), pipeFrames);
4287 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4288
Eric Laurent81784c32012-11-19 14:55:58 -08004289 state->mCommand = FastMixerState::COLD_IDLE;
4290 state->mColdFutexAddr = &mFastMixerFutex;
4291 state->mColdGen++;
4292 mFastMixerFutex = 0;
4293 sq->end();
4294 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4295 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4296 if (kUseFastMixer == FastMixer_Dynamic) {
4297 mNormalSink = mOutputSink;
4298 }
4299#ifdef AUDIO_WATCHDOG
4300 if (mAudioWatchdog != 0) {
4301 mAudioWatchdog->pause();
4302 }
4303#endif
4304 } else {
4305 sq->end(false /*didModify*/);
4306 }
4307 }
4308 PlaybackThread::threadLoop_standby();
4309}
4310
Eric Laurentbfb1b832013-01-07 09:53:42 -08004311bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4312{
4313 return false;
4314}
4315
4316bool AudioFlinger::PlaybackThread::shouldStandby_l()
4317{
4318 return !mStandby;
4319}
4320
4321bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4322{
4323 Mutex::Autolock _l(mLock);
4324 return waitingAsyncCallback_l();
4325}
4326
Eric Laurent81784c32012-11-19 14:55:58 -08004327// shared by MIXER and DIRECT, overridden by DUPLICATING
4328void AudioFlinger::PlaybackThread::threadLoop_standby()
4329{
4330 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004331 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004332 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004333 // discard any pending drain or write ack by incrementing sequence
4334 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4335 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004336 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004337 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4338 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004339 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004340 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004341}
4342
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004343void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4344{
4345 ALOGV("signal playback thread");
4346 broadcast_l();
4347}
4348
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004349void AudioFlinger::PlaybackThread::onAsyncError()
4350{
4351 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4352 invalidateTracks((audio_stream_type_t)i);
4353 }
4354}
4355
Eric Laurent81784c32012-11-19 14:55:58 -08004356void AudioFlinger::MixerThread::threadLoop_mix()
4357{
Eric Laurent81784c32012-11-19 14:55:58 -08004358 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004359 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004360 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004361 // increase sleep time progressively when application underrun condition clears.
4362 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4363 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4364 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004365 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004366 sleepTimeShift--;
4367 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004368 mSleepTimeUs = 0;
4369 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004370 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004371
Eric Laurent81784c32012-11-19 14:55:58 -08004372}
4373
4374void AudioFlinger::MixerThread::threadLoop_sleepTime()
4375{
4376 // If no tracks are ready, sleep once for the duration of an output
4377 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004378 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004379 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004380 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4381 // Using the Monopipe availableToWrite, we estimate the
4382 // sleep time to retry for more data (before we underrun).
4383 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4384 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4385 const size_t pipeFrames = monoPipe->maxFrames();
4386 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4387 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4388 const size_t framesDelay = std::min(
4389 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4390 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4391 pipeFrames, framesLeft, framesDelay);
4392 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4393 } else {
4394 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4395 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4396 mSleepTimeUs = kMinThreadSleepTimeUs;
4397 }
4398 // reduce sleep time in case of consecutive application underruns to avoid
4399 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4400 // duration we would end up writing less data than needed by the audio HAL if
4401 // the condition persists.
4402 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4403 sleepTimeShift++;
4404 }
Eric Laurent81784c32012-11-19 14:55:58 -08004405 }
4406 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004407 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004408 }
4409 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004410 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4411 // before effects processing or output.
4412 if (mMixerBufferValid) {
4413 memset(mMixerBuffer, 0, mMixerBufferSize);
4414 } else {
4415 memset(mSinkBuffer, 0, mSinkBufferSize);
4416 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004417 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004418 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4419 "anticipated start");
4420 }
4421 // TODO add standby time extension fct of effect tail
4422}
4423
4424// prepareTracks_l() must be called with ThreadBase::mLock held
4425AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4426 Vector< sp<Track> > *tracksToRemove)
4427{
Andy Hungc0691382018-09-12 18:01:57 -07004428 // clean up deleted track ids in AudioMixer before allocating new tracks
4429 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4430 // for each trackId, destroy it in the AudioMixer
4431 if (mAudioMixer->exists(trackId)) {
4432 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004433 }
4434 });
Andy Hungc0691382018-09-12 18:01:57 -07004435 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004436
4437 mixer_state mixerStatus = MIXER_IDLE;
4438 // find out which tracks need to be processed
4439 size_t count = mActiveTracks.size();
4440 size_t mixedTracks = 0;
4441 size_t tracksWithEffect = 0;
4442 // counts only _active_ fast tracks
4443 size_t fastTracks = 0;
4444 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4445
4446 float masterVolume = mMasterVolume;
4447 bool masterMute = mMasterMute;
4448
4449 if (masterMute) {
4450 masterVolume = 0;
4451 }
4452 // Delegate master volume control to effect in output mix effect chain if needed
4453 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4454 if (chain != 0) {
4455 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4456 chain->setVolume_l(&v, &v);
4457 masterVolume = (float)((v + (1 << 23)) >> 24);
4458 chain.clear();
4459 }
4460
4461 // prepare a new state to push
4462 FastMixerStateQueue *sq = NULL;
4463 FastMixerState *state = NULL;
4464 bool didModify = false;
4465 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004466 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004467 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004468 sq = mFastMixer->sq();
4469 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004470 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004471 }
4472
Andy Hung69aed5f2014-02-25 17:24:40 -08004473 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004474 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004475
Andy Hungbd3b2b02018-05-21 10:53:11 -07004476 // DeferredOperations handles statistics after setting mixerStatus.
4477 class DeferredOperations {
4478 public:
4479 DeferredOperations(mixer_state *mixerStatus)
4480 : mMixerStatus(mixerStatus) { }
4481
4482 // when leaving scope, tally frames properly.
4483 ~DeferredOperations() {
4484 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4485 // because that is when the underrun occurs.
4486 // We do not distinguish between FastTracks and NormalTracks here.
4487 if (*mMixerStatus == MIXER_TRACKS_READY) {
4488 for (const auto &underrun : mUnderrunFrames) {
4489 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4490 underrun.second);
4491 }
4492 }
4493 }
4494
4495 // tallyUnderrunFrames() is called to update the track counters
4496 // with the number of underrun frames for a particular mixer period.
4497 // We defer tallying until we know the final mixer status.
4498 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4499 mUnderrunFrames.emplace_back(track, underrunFrames);
4500 }
4501
4502 private:
4503 const mixer_state * const mMixerStatus;
4504 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4505 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4506
jiabin245cdd92018-12-07 17:55:15 -08004507 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004508 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004509 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004510
4511 // this const just means the local variable doesn't change
4512 Track* const track = t.get();
4513
4514 // process fast tracks
4515 if (track->isFastTrack()) {
jiabin245cdd92018-12-07 17:55:15 -08004516 if (track->getHapticPlaybackEnabled()) {
4517 noFastHapticTrack = false;
4518 }
Eric Laurent81784c32012-11-19 14:55:58 -08004519
4520 // It's theoretically possible (though unlikely) for a fast track to be created
4521 // and then removed within the same normal mix cycle. This is not a problem, as
4522 // the track never becomes active so it's fast mixer slot is never touched.
4523 // The converse, of removing an (active) track and then creating a new track
4524 // at the identical fast mixer slot within the same normal mix cycle,
4525 // is impossible because the slot isn't marked available until the end of each cycle.
4526 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004527 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004528 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4529 FastTrack *fastTrack = &state->mFastTracks[j];
4530
4531 // Determine whether the track is currently in underrun condition,
4532 // and whether it had a recent underrun.
4533 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4534 FastTrackUnderruns underruns = ftDump->mUnderruns;
4535 uint32_t recentFull = (underruns.mBitFields.mFull -
4536 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4537 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4538 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4539 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4540 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4541 uint32_t recentUnderruns = recentPartial + recentEmpty;
4542 track->mObservedUnderruns = underruns;
4543 // don't count underruns that occur while stopping or pausing
4544 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004545 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004546 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4547 recentUnderruns > 0) {
4548 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004549 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004550 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004551 // Immediately account for FastTrack underruns.
4552 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004553
4554 // This is similar to the state machine for normal tracks,
4555 // with a few modifications for fast tracks.
4556 bool isActive = true;
4557 switch (track->mState) {
4558 case TrackBase::STOPPING_1:
4559 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004560 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004561 track->mState = TrackBase::STOPPING_2;
4562 }
4563 break;
4564 case TrackBase::PAUSING:
4565 // ramp down is not yet implemented
4566 track->setPaused();
4567 break;
4568 case TrackBase::RESUMING:
4569 // ramp up is not yet implemented
4570 track->mState = TrackBase::ACTIVE;
4571 break;
4572 case TrackBase::ACTIVE:
4573 if (recentFull > 0 || recentPartial > 0) {
4574 // track has provided at least some frames recently: reset retry count
4575 track->mRetryCount = kMaxTrackRetries;
4576 }
4577 if (recentUnderruns == 0) {
4578 // no recent underruns: stay active
4579 break;
4580 }
4581 // there has recently been an underrun of some kind
4582 if (track->sharedBuffer() == 0) {
4583 // were any of the recent underruns "empty" (no frames available)?
4584 if (recentEmpty == 0) {
4585 // no, then ignore the partial underruns as they are allowed indefinitely
4586 break;
4587 }
4588 // there has recently been an "empty" underrun: decrement the retry counter
4589 if (--(track->mRetryCount) > 0) {
4590 break;
4591 }
4592 // indicate to client process that the track was disabled because of underrun;
4593 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004594 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004595 // remove from active list, but state remains ACTIVE [confusing but true]
4596 isActive = false;
4597 break;
4598 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004599 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004600 case TrackBase::STOPPING_2:
4601 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004602 case TrackBase::STOPPED:
4603 case TrackBase::FLUSHED: // flush() while active
4604 // Check for presentation complete if track is inactive
4605 // We have consumed all the buffers of this track.
4606 // This would be incomplete if we auto-paused on underrun
4607 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004608 uint32_t latency = 0;
4609 status_t result = mOutput->stream->getLatency(&latency);
4610 ALOGE_IF(result != OK,
4611 "Error when retrieving output stream latency: %d", result);
4612 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004613 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004614 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4615 // track stays in active list until presentation is complete
4616 break;
4617 }
4618 }
4619 if (track->isStopping_2()) {
4620 track->mState = TrackBase::STOPPED;
4621 }
4622 if (track->isStopped()) {
4623 // Can't reset directly, as fast mixer is still polling this track
4624 // track->reset();
4625 // So instead mark this track as needing to be reset after push with ack
4626 resetMask |= 1 << i;
4627 }
4628 isActive = false;
4629 break;
4630 case TrackBase::IDLE:
4631 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004632 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
4634
4635 if (isActive) {
4636 // was it previously inactive?
4637 if (!(state->mTrackMask & (1 << j))) {
4638 ExtendedAudioBufferProvider *eabp = track;
4639 VolumeProvider *vp = track;
4640 fastTrack->mBufferProvider = eabp;
4641 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004642 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004643 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004644 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004645 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004646 fastTrack->mGeneration++;
4647 state->mTrackMask |= 1 << j;
4648 didModify = true;
4649 // no acknowledgement required for newly active tracks
4650 }
Kevin Rocard12381092018-04-11 09:19:59 -07004651 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurent81784c32012-11-19 14:55:58 -08004652 // cache the combined master volume and stream type volume for fast mixer; this
4653 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004654 const float vh = track->getVolumeHandler()->getVolume(
Kevin Rocard12381092018-04-11 09:19:59 -07004655 proxy->framesReleased()).first;
4656 float volume = masterVolume
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004657 * mStreamTypes[track->streamType()].volume
4658 * vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004659 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004660 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4661 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4662 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
4663 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004664 ++fastTracks;
4665 } else {
4666 // was it previously active?
4667 if (state->mTrackMask & (1 << j)) {
4668 fastTrack->mBufferProvider = NULL;
4669 fastTrack->mGeneration++;
4670 state->mTrackMask &= ~(1 << j);
4671 didModify = true;
4672 // If any fast tracks were removed, we must wait for acknowledgement
4673 // because we're about to decrement the last sp<> on those tracks.
4674 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4675 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004676 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4677 // AudioTrack may start (which may not be with a start() but with a write()
4678 // after underrun) and immediately paused or released. In that case the
4679 // FastTrack state hasn't had time to update.
4680 // TODO Remove the ALOGW when this theory is confirmed.
4681 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004682 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4683 j, track->mState, state->mTrackMask, recentUnderruns,
4684 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004685 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004686 }
4687 tracksToRemove->add(track);
4688 // Avoids a misleading display in dumpsys
4689 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4690 }
jiabin245cdd92018-12-07 17:55:15 -08004691 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4692 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4693 didModify = true;
4694 }
Eric Laurent81784c32012-11-19 14:55:58 -08004695 continue;
4696 }
4697
4698 { // local variable scope to avoid goto warning
4699
4700 audio_track_cblk_t* cblk = track->cblk();
4701
4702 // The first time a track is added we wait
4703 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004704 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004705
4706 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004707 // use the trackId as the AudioMixer name.
4708 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004709 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004710 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004711 track->mChannelMask,
4712 track->mFormat,
4713 track->mSessionId);
4714 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004715 ALOGW("%s(): AudioMixer cannot create track(%d)"
4716 " mask %#x, format %#x, sessionId %d",
4717 __func__, trackId,
4718 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004719 tracksToRemove->add(track);
4720 track->invalidate(); // consider it dead.
4721 continue;
4722 }
4723 }
4724
Eric Laurent81784c32012-11-19 14:55:58 -08004725 // make sure that we have enough frames to mix one full buffer.
4726 // enforce this condition only once to enable draining the buffer in case the client
4727 // app does not call stop() and relies on underrun to stop:
4728 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4729 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004730 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004731 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004732 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004733
4734 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004735 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004736 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4737 // add frames already consumed but not yet released by the resampler
4738 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004739 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004740
Eric Laurent81784c32012-11-19 14:55:58 -08004741 uint32_t minFrames = 1;
4742 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4743 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004744 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004745 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004746
4747 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004748 if (ATRACE_ENABLED()) {
4749 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004750 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004751 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004752 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004753 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004754 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004755 !track->isPaused() && !track->isTerminated())
4756 {
Andy Hungc0691382018-09-12 18:01:57 -07004757 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004758
4759 mixedTracks++;
4760
Andy Hung69aed5f2014-02-25 17:24:40 -08004761 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4762 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004763 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004764 if (track->mainBuffer() != mSinkBuffer &&
4765 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004766 if (mEffectBufferEnabled) {
4767 mEffectBufferValid = true; // Later can set directly.
4768 }
Eric Laurent81784c32012-11-19 14:55:58 -08004769 chain = getEffectChain_l(track->sessionId());
4770 // Delegate volume control to effect in track effect chain if needed
4771 if (chain != 0) {
4772 tracksWithEffect++;
4773 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004774 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004775 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004776 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004777 }
4778 }
4779
4780
4781 int param = AudioMixer::VOLUME;
4782 if (track->mFillingUpStatus == Track::FS_FILLED) {
4783 // no ramp for the first volume setting
4784 track->mFillingUpStatus = Track::FS_ACTIVE;
4785 if (track->mState == TrackBase::RESUMING) {
4786 track->mState = TrackBase::ACTIVE;
4787 param = AudioMixer::RAMP_VOLUME;
4788 }
Andy Hungc0691382018-09-12 18:01:57 -07004789 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004790 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004791 // FIXME should not make a decision based on mServer
4792 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004793 // If the track is stopped before the first frame was mixed,
4794 // do not apply ramp
4795 param = AudioMixer::RAMP_VOLUME;
4796 }
4797
4798 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004799 uint32_t vl, vr; // in U8.24 integer format
4800 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004801 // read original volumes with volume control
4802 float typeVolume = mStreamTypes[track->streamType()].volume;
4803 float v = masterVolume * typeVolume;
4804
Glenn Kastene4756fe2012-11-29 13:38:14 -08004805 if (track->isPausing() || mStreamTypes[track->streamType()].mute) {
Andy Hung6be49402014-05-30 10:42:03 -07004806 vl = vr = 0;
4807 vlf = vrf = vaf = 0.;
Eric Laurent81784c32012-11-19 14:55:58 -08004808 if (track->isPausing()) {
4809 track->setPaused();
4810 }
4811 } else {
Eric Laurent5bba2f62016-03-18 11:14:14 -07004812 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Glenn Kastenc56f3422014-03-21 17:53:17 -07004813 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07004814 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
4815 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08004816 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07004817 if (vlf > GAIN_FLOAT_UNITY) {
4818 ALOGV("Track left volume out of range: %.3g", vlf);
4819 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004820 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07004821 if (vrf > GAIN_FLOAT_UNITY) {
4822 ALOGV("Track right volume out of range: %.3g", vrf);
4823 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08004824 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004825 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung10cbff12017-02-21 17:30:14 -08004826 track->mAudioTrackServerProxy->framesReleased()).first;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004827 // now apply the master volume and stream type volume and shaper volume
4828 vlf *= v * vh;
4829 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08004830 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07004831 // then derive vl and vr as U8.24 versions for the effect chain
4832 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
4833 vl = (uint32_t) (scaleto8_24 * vlf);
4834 vr = (uint32_t) (scaleto8_24 * vrf);
4835 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08004836 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08004837 // send level comes from shared memory and so may be corrupt
4838 if (sendLevel > MAX_GAIN_INT) {
4839 ALOGV("Track send level out of range: %04X", sendLevel);
4840 sendLevel = MAX_GAIN_INT;
4841 }
Andy Hung6be49402014-05-30 10:42:03 -07004842 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
4843 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08004844 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845
Kevin Rocard12381092018-04-11 09:19:59 -07004846 track->setFinalVolume((vrf + vlf) / 2.f);
4847
Eric Laurent81784c32012-11-19 14:55:58 -08004848 // Delegate volume control to effect in track effect chain if needed
4849 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
4850 // Do not ramp volume if volume is controlled by effect
4851 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08004852 // Update remaining floating point volume levels
4853 vlf = (float)vl / (1 << 24);
4854 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08004855 track->mHasVolumeController = true;
4856 } else {
4857 // force no volume ramp when volume controller was just disabled or removed
4858 // from effect chain to avoid volume spike
4859 if (track->mHasVolumeController) {
4860 param = AudioMixer::VOLUME;
4861 }
4862 track->mHasVolumeController = false;
4863 }
4864
Eric Laurent7c29ec92017-09-20 17:54:22 -07004865 // For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4866 // still applied by the mixer.
4867 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4868 v = mStreamTypes[track->streamType()].mute ? 0.0f : v;
4869 if (v != mLeftVolFloat) {
4870 status_t result = mOutput->stream->setVolume(v, v);
4871 ALOGE_IF(result != OK, "Error when setting output stream volume: %d", result);
4872 if (result == OK) {
4873 mLeftVolFloat = v;
4874 }
4875 }
4876 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4877 // remove stream volume contribution from software volume.
4878 if (v != 0.0f && mLeftVolFloat == v) {
4879 vlf = min(1.0f, vlf / v);
4880 vrf = min(1.0f, vrf / v);
4881 vaf = min(1.0f, vaf / v);
4882 }
4883 }
Eric Laurent81784c32012-11-19 14:55:58 -08004884 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07004885 mAudioMixer->setBufferProvider(trackId, track);
4886 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08004887
Andy Hungc0691382018-09-12 18:01:57 -07004888 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
4889 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
4890 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08004891 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004892 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004893 AudioMixer::TRACK,
4894 AudioMixer::FORMAT, (void *)track->format());
4895 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004896 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004897 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004898 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07004899 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004900 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07004901 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08004902 AudioMixer::MIXER_CHANNEL_MASK,
4903 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08004904 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07004905 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004906 uint32_t reqSampleRate = track->mAudioTrackServerProxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08004907 if (reqSampleRate == 0) {
4908 reqSampleRate = mSampleRate;
4909 } else if (reqSampleRate > maxSampleRate) {
4910 reqSampleRate = maxSampleRate;
4911 }
Eric Laurent81784c32012-11-19 14:55:58 -08004912 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004913 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004914 AudioMixer::RESAMPLE,
4915 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00004916 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004917
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004918 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004919 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004920 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07004921 AudioMixer::TIMESTRETCH,
4922 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004923 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004924
Andy Hung69aed5f2014-02-25 17:24:40 -08004925 /*
4926 * Select the appropriate output buffer for the track.
4927 *
Andy Hung98ef9782014-03-04 14:46:50 -08004928 * Tracks with effects go into their own effects chain buffer
4929 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08004930 *
4931 * Other tracks can use mMixerBuffer for higher precision
4932 * channel accumulation. If this buffer is enabled
4933 * (mMixerBufferEnabled true), then selected tracks will accumulate
4934 * into it.
4935 *
4936 */
4937 if (mMixerBufferEnabled
4938 && (track->mainBuffer() == mSinkBuffer
4939 || track->mainBuffer() == mMixerBuffer)) {
4940 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004941 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004942 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08004943 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08004944 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004945 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004946 AudioMixer::TRACK,
4947 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
4948 // TODO: override track->mainBuffer()?
4949 mMixerBufferValid = true;
4950 } else {
4951 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004952 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004953 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07004954 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08004955 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004956 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08004957 AudioMixer::TRACK,
4958 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
4959 }
Eric Laurent81784c32012-11-19 14:55:58 -08004960 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07004961 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08004962 AudioMixer::TRACK,
4963 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08004964 mAudioMixer->setParameter(
4965 trackId,
4966 AudioMixer::TRACK,
4967 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08004968 mAudioMixer->setParameter(
4969 trackId,
4970 AudioMixer::TRACK,
4971 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08004972
4973 // reset retry count
4974 track->mRetryCount = kMaxTrackRetries;
4975
4976 // If one track is ready, set the mixer ready if:
4977 // - the mixer was not ready during previous round OR
4978 // - no other track is not ready
4979 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
4980 mixerStatus != MIXER_TRACKS_ENABLED) {
4981 mixerStatus = MIXER_TRACKS_READY;
4982 }
4983 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07004984 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004985 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07004986 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
4987 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07004988 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004989 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004990 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08004991
Eric Laurent81784c32012-11-19 14:55:58 -08004992 // clear effect chain input buffer if an active track underruns to avoid sending
4993 // previous audio buffer again to effects
4994 chain = getEffectChain_l(track->sessionId());
4995 if (chain != 0) {
4996 chain->clearInputBuffer();
4997 }
4998
Andy Hungc0691382018-09-12 18:01:57 -07004999 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005000 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5001 track->isStopped() || track->isPaused()) {
5002 // We have consumed all the buffers of this track.
5003 // Remove it from the list of active tracks.
5004 // TODO: use actual buffer filling status instead of latency when available from
5005 // audio HAL
5006 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005007 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005008 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5009 if (track->isStopped()) {
5010 track->reset();
5011 }
5012 tracksToRemove->add(track);
5013 }
5014 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005015 // No buffers for this track. Give it a few chances to
5016 // fill a buffer, then remove it from active list.
5017 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005018 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5019 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005020 tracksToRemove->add(track);
5021 // indicate to client process that the track was disabled because of underrun;
5022 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005023 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // If one track is not ready, mark the mixer also not ready if:
5025 // - the mixer was ready during previous round OR
5026 // - no other track is ready
5027 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5028 mixerStatus != MIXER_TRACKS_READY) {
5029 mixerStatus = MIXER_TRACKS_ENABLED;
5030 }
5031 }
Andy Hungc0691382018-09-12 18:01:57 -07005032 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005033 }
5034
5035 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005036
5037 }
5038
jiabin245cdd92018-12-07 17:55:15 -08005039 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5040 // When there is no fast track playing haptic and FastMixer exists,
5041 // enabling the first FastTrack, which provides mixed data from normal
5042 // tracks, to play haptic data.
5043 FastTrack *fastTrack = &state->mFastTracks[0];
5044 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5045 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5046 didModify = true;
5047 }
5048 }
5049
Eric Laurent81784c32012-11-19 14:55:58 -08005050 // Push the new FastMixer state if necessary
5051 bool pauseAudioWatchdog = false;
5052 if (didModify) {
5053 state->mFastTracksGen++;
5054 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5055 if (kUseFastMixer == FastMixer_Dynamic &&
5056 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5057 state->mCommand = FastMixerState::COLD_IDLE;
5058 state->mColdFutexAddr = &mFastMixerFutex;
5059 state->mColdGen++;
5060 mFastMixerFutex = 0;
5061 if (kUseFastMixer == FastMixer_Dynamic) {
5062 mNormalSink = mOutputSink;
5063 }
5064 // If we go into cold idle, need to wait for acknowledgement
5065 // so that fast mixer stops doing I/O.
5066 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5067 pauseAudioWatchdog = true;
5068 }
Eric Laurent81784c32012-11-19 14:55:58 -08005069 }
5070 if (sq != NULL) {
5071 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005072 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5073 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5074 // when bringing the output sink into standby.)
5075 //
5076 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5077 //
5078 // This occurs with BT suspend when we idle the FastMixer with
5079 // active tracks, which may be added or removed.
5080 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005081 }
5082#ifdef AUDIO_WATCHDOG
5083 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5084 mAudioWatchdog->pause();
5085 }
5086#endif
5087
5088 // Now perform the deferred reset on fast tracks that have stopped
5089 while (resetMask != 0) {
5090 size_t i = __builtin_ctz(resetMask);
5091 ALOG_ASSERT(i < count);
5092 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005093 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005094 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5095 track->reset();
5096 }
5097
Andy Hung80d03d22018-04-10 10:32:11 -07005098 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5099 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5100 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5101 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5102 // See also the implementation of destroyTrack_l().
5103 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005104 const int trackId = track->id();
5105 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5106 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005107 }
5108 }
5109
Eric Laurent81784c32012-11-19 14:55:58 -08005110 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005111 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005112
Eric Laurent97d547d2014-09-02 14:45:53 -07005113 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5114 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005115 }
5116
5117 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005118 // as long as there are effects we should clear the effects buffer, to avoid
5119 // passing a non-clean buffer to the effect chain
5120 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005121 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005122 // sink or mix buffer must be cleared if all tracks are connected to an
5123 // effect chain as in this case the mixer will not write to the sink or mix buffer
5124 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005125 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5126 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005127 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005128 if (mMixerBufferValid) {
5129 memset(mMixerBuffer, 0, mMixerBufferSize);
5130 // TODO: In testing, mSinkBuffer below need not be cleared because
5131 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5132 // after mixing.
5133 //
5134 // To enforce this guarantee:
5135 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5136 // (mixedTracks == 0 && fastTracks > 0))
5137 // must imply MIXER_TRACKS_READY.
5138 // Later, we may clear buffers regardless, and skip much of this logic.
5139 }
Andy Hung98ef9782014-03-04 14:46:50 -08005140 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005141 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005142 }
5143
5144 // if any fast tracks, then status is ready
5145 mMixerStatusIgnoringFastTracks = mixerStatus;
5146 if (fastTracks > 0) {
5147 mixerStatus = MIXER_TRACKS_READY;
5148 }
5149 return mixerStatus;
5150}
5151
Eric Laurentad7dd962016-09-22 12:38:37 -07005152// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005153uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005154{
5155 uint32_t trackCount = 0;
5156 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005157 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005158 trackCount++;
5159 }
5160 }
5161 return trackCount;
5162}
5163
Andy Hung1bc088a2018-02-09 15:57:31 -08005164// isTrackAllowed_l() must be called with ThreadBase::mLock held
5165bool AudioFlinger::MixerThread::isTrackAllowed_l(
5166 audio_channel_mask_t channelMask, audio_format_t format,
5167 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005168{
Andy Hung1bc088a2018-02-09 15:57:31 -08005169 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5170 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005171 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005172 // Check validity as we don't call AudioMixer::create() here.
5173 if (!AudioMixer::isValidFormat(format)) {
5174 ALOGW("%s: invalid format: %#x", __func__, format);
5175 return false;
5176 }
5177 if (!AudioMixer::isValidChannelMask(channelMask)) {
5178 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5179 return false;
5180 }
5181 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005182}
5183
Eric Laurent10351942014-05-08 18:49:52 -07005184// checkForNewParameter_l() must be called with ThreadBase::mLock held
5185bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5186 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005187{
Eric Laurent81784c32012-11-19 14:55:58 -08005188 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005189 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005190
Eric Laurent10351942014-05-08 18:49:52 -07005191 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005192
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005193 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005194
Eric Laurent10351942014-05-08 18:49:52 -07005195 AudioParameter param = AudioParameter(keyValuePair);
5196 int value;
5197 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5198 reconfig = true;
5199 }
5200 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005201 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005202 status = BAD_VALUE;
5203 } else {
5204 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005205 reconfig = true;
5206 }
Eric Laurent10351942014-05-08 18:49:52 -07005207 }
5208 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005209 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005210 status = BAD_VALUE;
5211 } else {
5212 // no need to save value, since it's constant
5213 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005214 }
Eric Laurent10351942014-05-08 18:49:52 -07005215 }
5216 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5217 // do not accept frame count changes if tracks are open as the track buffer
5218 // size depends on frame count and correct behavior would not be guaranteed
5219 // if frame count is changed after track creation
5220 if (!mTracks.isEmpty()) {
5221 status = INVALID_OPERATION;
5222 } else {
5223 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005224 }
Eric Laurent10351942014-05-08 18:49:52 -07005225 }
5226 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurent81784c32012-11-19 14:55:58 -08005227#ifdef ADD_BATTERY_DATA
Eric Laurent10351942014-05-08 18:49:52 -07005228 // when changing the audio output device, call addBatteryData to notify
5229 // the change
5230 if (mOutDevice != value) {
5231 uint32_t params = 0;
5232 // check whether speaker is on
5233 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
5234 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent81784c32012-11-19 14:55:58 -08005235 }
Eric Laurent10351942014-05-08 18:49:52 -07005236
5237 audio_devices_t deviceWithoutSpeaker
5238 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
5239 // check if any other device (except speaker) is on
Eric Laurent054d9d32015-04-24 08:48:48 -07005240 if (value & deviceWithoutSpeaker) {
Eric Laurent10351942014-05-08 18:49:52 -07005241 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5242 }
5243
5244 if (params != 0) {
5245 addBatteryData(params);
5246 }
5247 }
Eric Laurent81784c32012-11-19 14:55:58 -08005248#endif
5249
Eric Laurent10351942014-05-08 18:49:52 -07005250 // forward device change to effects that have requested to be
5251 // aware of attached audio device.
5252 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005253 a2dpDeviceChanged =
5254 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005255 mOutDevice = value;
5256 for (size_t i = 0; i < mEffectChains.size(); i++) {
5257 mEffectChains[i]->setDevice_l(mOutDevice);
Eric Laurent81784c32012-11-19 14:55:58 -08005258 }
5259 }
Eric Laurent10351942014-05-08 18:49:52 -07005260 }
Eric Laurent81784c32012-11-19 14:55:58 -08005261
Eric Laurent10351942014-05-08 18:49:52 -07005262 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005263 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005264 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005265 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005266 mStandby = true;
5267 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005268 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005269 }
Eric Laurent10351942014-05-08 18:49:52 -07005270 if (status == NO_ERROR && reconfig) {
5271 readOutputParameters_l();
5272 delete mAudioMixer;
5273 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005274 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005275 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005276 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005277 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005278 track->mChannelMask,
5279 track->mFormat,
5280 track->mSessionId);
5281 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005282 "%s(): AudioMixer cannot create track(%d)"
5283 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005284 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005285 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005286 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005287 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005288 }
Eric Laurent81784c32012-11-19 14:55:58 -08005289 }
5290
Eric Laurent42537be2016-01-08 17:16:42 -08005291 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005292}
5293
5294
5295void AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
5296{
Eric Laurent81784c32012-11-19 14:55:58 -08005297 PlaybackThread::dumpInternals(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005298 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005299 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005300 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005301 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5302 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5303 : mBalance.toString()).c_str());
Andy Hungf6ab58d2018-05-25 12:50:39 -07005304 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
Andy Hungcef2daa2018-06-01 15:31:49 -07005305 if (latencyMs != 0.) {
Andy Hungf6ab58d2018-05-25 12:50:39 -07005306 dprintf(fd, " NormalMixer latency ms: %.2lf\n", latencyMs);
Andy Hungcef2daa2018-06-01 15:31:49 -07005307 } else {
5308 dprintf(fd, " NormalMixer latency ms: unavail\n");
Andy Hungf6ab58d2018-05-25 12:50:39 -07005309 }
Eric Laurent81784c32012-11-19 14:55:58 -08005310
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005311 if (hasFastMixer()) {
5312 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5313
5314 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5315 // while we are dumping it. It may be inconsistent, but it won't mutate!
5316 // This is a large object so we place it on the heap.
5317 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005318 const std::unique_ptr<FastMixerDumpState> copy =
5319 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005320 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005321
5322#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005323 // Similar for state queue
5324 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5325 observerCopy.dump(fd);
5326 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5327 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005328#endif
5329
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005330#ifdef AUDIO_WATCHDOG
5331 if (mAudioWatchdog != 0) {
5332 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5333 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5334 wdCopy.dump(fd);
5335 }
5336#endif
5337
5338 } else {
5339 dprintf(fd, " No FastMixer\n");
5340 }
Eric Laurent81784c32012-11-19 14:55:58 -08005341}
5342
5343uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5344{
5345 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5346}
5347
5348uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5349{
5350 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5351}
5352
5353void AudioFlinger::MixerThread::cacheParameters_l()
5354{
5355 PlaybackThread::cacheParameters_l();
5356
5357 // FIXME: Relaxed timing because of a certain device that can't meet latency
5358 // Should be reduced to 2x after the vendor fixes the driver issue
5359 // increase threshold again due to low power audio mode. The way this warning
5360 // threshold is calculated and its usefulness should be reconsidered anyway.
5361 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5362}
5363
5364// ----------------------------------------------------------------------------
5365
5366AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
Andy Hung48f59ed2019-01-28 15:06:59 -08005367 AudioStreamOut* output, audio_io_handle_t id, audio_devices_t device,
Eric Laurente93cc032016-05-05 10:15:10 -07005368 ThreadBase::type_t type, bool systemReady)
5369 : PlaybackThread(audioFlinger, output, id, device, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005370{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005371 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005372}
5373
Eric Laurent81784c32012-11-19 14:55:58 -08005374AudioFlinger::DirectOutputThread::~DirectOutputThread()
5375{
5376}
5377
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005378void AudioFlinger::DirectOutputThread::dumpInternals(int fd, const Vector<String16>& args)
5379{
5380 PlaybackThread::dumpInternals(fd, args);
5381 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5382 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5383}
5384
5385void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5386{
5387 Mutex::Autolock _l(mLock);
5388 if (mMasterBalance != balance) {
5389 mMasterBalance.store(balance);
5390 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5391 broadcast_l();
5392 }
5393}
5394
Eric Laurent5850c4c2016-11-10 13:04:31 -08005395void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005396{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005397 float left, right;
5398
5399 if (mMasterMute || mStreamTypes[track->streamType()].mute) {
5400 left = right = 0;
5401 } else {
5402 float typeVolume = mStreamTypes[track->streamType()].volume;
5403 float v = mMasterVolume * typeVolume;
Eric Laurent5bba2f62016-03-18 11:14:14 -07005404 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005405
Andy Hung10cbff12017-02-21 17:30:14 -08005406 // Get volumeshaper scaling
5407 std::pair<float /* volume */, bool /* active */>
5408 vh = track->getVolumeHandler()->getVolume(
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005409 track->mAudioTrackServerProxy->framesReleased());
Andy Hung10cbff12017-02-21 17:30:14 -08005410 v *= vh.first;
5411 mVolumeShaperActive = vh.second;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005412
Glenn Kastenc56f3422014-03-21 17:53:17 -07005413 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5414 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5415 if (left > GAIN_FLOAT_UNITY) {
5416 left = GAIN_FLOAT_UNITY;
5417 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005418 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005419 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5420 if (right > GAIN_FLOAT_UNITY) {
5421 right = GAIN_FLOAT_UNITY;
5422 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005423 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005424 }
5425
5426 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005427 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428 if (left != mLeftVolFloat || right != mRightVolFloat) {
5429 mLeftVolFloat = left;
5430 mRightVolFloat = right;
5431
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 // Delegate volume control to effect in track effect chain if needed
5433 // only one effect chain can be present on DirectOutputThread, so if
5434 // there is one, the track is connected to it
5435 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005436 // if effect chain exists, volume is handled by it.
5437 // Convert volumes from float to 8.24
5438 uint32_t vl = (uint32_t)(left * (1 << 24));
5439 uint32_t vr = (uint32_t)(right * (1 << 24));
5440 // Direct/Offload effect chains set output volume in setVolume_l().
5441 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5442 } else {
5443 // otherwise we directly set the volume.
5444 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446 }
5447 }
5448}
5449
Phil Burk43b4dcc2015-06-09 16:53:44 -07005450void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5451{
5452 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005453 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005454
Eric Laurent0f0631e2015-07-06 18:01:25 -07005455 if (previousTrack != 0 && latestTrack != 0) {
5456 if (mType == DIRECT) {
5457 if (previousTrack.get() != latestTrack.get()) {
5458 mFlushPending = true;
5459 }
5460 } else /* mType == OFFLOAD */ {
5461 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5462 mFlushPending = true;
5463 }
5464 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005465 }
5466 PlaybackThread::onAddNewTrack_l();
5467}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005468
Eric Laurent81784c32012-11-19 14:55:58 -08005469AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5470 Vector< sp<Track> > *tracksToRemove
5471)
5472{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005473 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005474 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005475 bool doHwPause = false;
5476 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005477
5478 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005479 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005480 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005481 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005482 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005483 continue;
5484 }
5485
Eric Laurent5850c4c2016-11-10 13:04:31 -08005486 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005487#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005488 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005489#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005490 // Only consider last track started for volume and mixer state control.
5491 // In theory an older track could underrun and restart after the new one starts
5492 // but as we only care about the transition phase between two tracks on a
5493 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005494 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005495 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005496
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005497 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005498 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005499 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005500 doHwPause = true;
5501 mHwPaused = true;
5502 }
5503 tracksToRemove->add(track);
5504 } else if (track->isFlushPending()) {
5505 track->flushAck();
5506 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005507 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005508 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005509 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005510 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005511 if (last) {
5512 mLeftVolFloat = mRightVolFloat = -1.0;
5513 if (mHwPaused) {
5514 doHwResume = true;
5515 mHwPaused = false;
5516 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005517 }
5518 }
5519
Eric Laurent81784c32012-11-19 14:55:58 -08005520 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005521 // for all its buffers to be filled before processing it.
5522 // Allow draining the buffer in case the client
5523 // app does not call stop() and relies on underrun to stop:
5524 // hence the test on (track->mRetryCount > 1).
5525 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005526 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005527 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005528 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005529 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005530 minFrames = mNormalFrameCount;
5531 } else {
5532 minFrames = 1;
5533 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534
Eric Laurentab5cdba2014-06-09 17:22:27 -07005535 if ((track->framesReady() >= minFrames) && track->isReady() && !track->isPaused() &&
5536 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005537 {
Andy Hungc0691382018-09-12 18:01:57 -07005538 ALOGVV("track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005539
5540 if (track->mFillingUpStatus == Track::FS_FILLED) {
5541 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005542 if (last) {
5543 // make sure processVolume_l() will apply new volume even if 0
5544 mLeftVolFloat = mRightVolFloat = -1.0;
5545 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005546 if (!mHwSupportsPause) {
5547 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005548 }
5549 }
5550
5551 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005552 processVolume_l(track, last);
5553 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005554 sp<Track> previousTrack = mPreviousTrack.promote();
5555 if (previousTrack != 0) {
5556 if (track != previousTrack.get()) {
5557 // Flush any data still being written from last track
5558 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005559 // Invalidate previous track to force a seek when resuming.
5560 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005561 }
5562 }
5563 mPreviousTrack = track;
5564
Eric Laurentd595b7c2013-04-03 17:27:56 -07005565 // reset retry count
5566 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005567 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005568 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005569 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005570 doHwResume = true;
5571 mHwPaused = false;
5572 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005573 }
Eric Laurent81784c32012-11-19 14:55:58 -08005574 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005575 // clear effect chain input buffer if the last active track started underruns
5576 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005577 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005578 mEffectChains[0]->clearInputBuffer();
5579 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005580 if (track->isStopping_1()) {
5581 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005582 if (last && mHwPaused) {
5583 doHwResume = true;
5584 mHwPaused = false;
5585 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005586 }
5587 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5588 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005589 // We have consumed all the buffers of this track.
5590 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005591 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005592 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005593 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5594 } else {
5595 audioHALFrames = 0;
5596 }
5597
Andy Hung818e7a32016-02-16 18:08:07 -08005598 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005599 if (mStandby || !last ||
5600 track->presentationComplete(framesWritten, audioHALFrames)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005601 if (track->isStopping_2()) {
5602 track->mState = TrackBase::STOPPED;
5603 }
Eric Laurent81784c32012-11-19 14:55:58 -08005604 if (track->isStopped()) {
5605 track->reset();
5606 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005607 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005608 }
5609 } else {
5610 // No buffers for this track. Give it a few chances to
5611 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005612 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005613 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005614 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", track->id());
Eric Laurentd595b7c2013-04-03 17:27:56 -07005615 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005616 // indicate to client process that the track was disabled because of underrun;
5617 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005618 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005619 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005620 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5621 "minFrames = %u, mFormat = %#x",
5622 track->framesReady(), minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005624 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005625 doHwPause = true;
5626 mHwPaused = true;
5627 }
Eric Laurent81784c32012-11-19 14:55:58 -08005628 }
5629 }
5630 }
5631 }
5632
Eric Laurentd1f69b02014-12-15 14:33:13 -08005633 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005634 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005635 for (size_t i = 0; i < mTracks.size(); i++) {
5636 if (mTracks[i]->isFlushPending()) {
5637 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005638 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005639 }
5640 }
5641 }
5642
5643 // make sure the pause/flush/resume sequence is executed in the right order.
5644 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5645 // before flush and then resume HW. This can happen in case of pause/flush/resume
5646 // if resume is received before pause is executed.
5647 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005648 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005649 status_t result = mOutput->stream->pause();
5650 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005651 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005652 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005653 flushHw_l();
5654 }
5655 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005656 status_t result = mOutput->stream->resume();
5657 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005658 }
Eric Laurent81784c32012-11-19 14:55:58 -08005659 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005660 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005661
5662 return mixerStatus;
5663}
5664
5665void AudioFlinger::DirectOutputThread::threadLoop_mix()
5666{
Eric Laurent81784c32012-11-19 14:55:58 -08005667 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005668 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005669 // output audio to hardware
5670 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005671 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005672 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005673 status_t status = mActiveTrack->getNextBuffer(&buffer);
5674 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005675 // no need to pad with 0 for compressed audio
5676 if (audio_has_proportional_frames(mFormat)) {
5677 memset(curBuf, 0, frameCount * mFrameSize);
5678 }
Eric Laurent81784c32012-11-19 14:55:58 -08005679 break;
5680 }
5681 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5682 frameCount -= buffer.frameCount;
5683 curBuf += buffer.frameCount * mFrameSize;
5684 mActiveTrack->releaseBuffer(&buffer);
5685 }
Andy Hung2098f272014-02-27 14:00:06 -08005686 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005687 mSleepTimeUs = 0;
5688 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005689 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005690}
5691
5692void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5693{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005694 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005695 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005696 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005697 return;
5698 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005699 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005700 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005701 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005702 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005703 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005704 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005705 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005706 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005707 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005708 }
5709}
5710
Eric Laurentd1f69b02014-12-15 14:33:13 -08005711void AudioFlinger::DirectOutputThread::threadLoop_exit()
5712{
5713 {
5714 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005715 for (size_t i = 0; i < mTracks.size(); i++) {
5716 if (mTracks[i]->isFlushPending()) {
5717 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005718 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005719 }
5720 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005721 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005722 flushHw_l();
5723 }
5724 }
5725 PlaybackThread::threadLoop_exit();
5726}
5727
5728// must be called with thread mutex locked
5729bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5730{
5731 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005732 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005733
vivek mehta9cd7ad12016-03-17 00:18:29 -07005734 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5735 return !mStandby;
5736 }
5737
Eric Laurentd1f69b02014-12-15 14:33:13 -08005738 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5739 // after a timeout and we will enter standby then.
5740 if (mTracks.size() > 0) {
5741 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005742 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5743 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005744 }
5745
Eric Laurent5cff4032015-05-26 13:49:58 -07005746 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005747}
5748
Eric Laurent10351942014-05-08 18:49:52 -07005749// checkForNewParameter_l() must be called with ThreadBase::mLock held
5750bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5751 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005752{
5753 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005754 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005755
Eric Laurent10351942014-05-08 18:49:52 -07005756 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005757
Eric Laurent10351942014-05-08 18:49:52 -07005758 AudioParameter param = AudioParameter(keyValuePair);
5759 int value;
5760 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5761 // forward device change to effects that have requested to be
5762 // aware of attached audio device.
5763 if (value != AUDIO_DEVICE_NONE) {
Eric Laurent42537be2016-01-08 17:16:42 -08005764 a2dpDeviceChanged =
5765 (mOutDevice & AUDIO_DEVICE_OUT_ALL_A2DP) != (value & AUDIO_DEVICE_OUT_ALL_A2DP);
Eric Laurent10351942014-05-08 18:49:52 -07005766 mOutDevice = value;
5767 for (size_t i = 0; i < mEffectChains.size(); i++) {
5768 mEffectChains[i]->setDevice_l(mOutDevice);
Glenn Kastenc125f382014-04-11 18:37:33 -07005769 }
5770 }
Eric Laurent81784c32012-11-19 14:55:58 -08005771 }
Eric Laurent10351942014-05-08 18:49:52 -07005772 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5773 // do not accept frame count changes if tracks are open as the track buffer
5774 // size depends on frame count and correct behavior would not be garantied
5775 // if frame count is changed after track creation
5776 if (!mTracks.isEmpty()) {
5777 status = INVALID_OPERATION;
5778 } else {
5779 reconfig = true;
5780 }
5781 }
5782 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005783 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005784 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005785 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005786 mStandby = true;
5787 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005788 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005789 }
5790 if (status == NO_ERROR && reconfig) {
5791 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005792 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005793 }
5794 }
5795
Eric Laurent42537be2016-01-08 17:16:42 -08005796 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005797}
5798
5799uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5800{
5801 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005802 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005803 time = PlaybackThread::activeSleepTimeUs();
5804 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005805 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005806 }
5807 return time;
5808}
5809
5810uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5811{
5812 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005813 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005814 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5815 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005816 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005817 }
5818 return time;
5819}
5820
5821uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5822{
5823 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005824 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005825 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5826 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005827 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005828 }
5829 return time;
5830}
5831
5832void AudioFlinger::DirectOutputThread::cacheParameters_l()
5833{
5834 PlaybackThread::cacheParameters_l();
5835
5836 // use shorter standby delay as on normal output to release
5837 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005838 // no delay on outputs with HW A/V sync
5839 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005840 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005841 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005842 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005843 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005844 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005845 }
Eric Laurent81784c32012-11-19 14:55:58 -08005846}
5847
Eric Laurente659ef42014-09-29 13:06:46 -07005848void AudioFlinger::DirectOutputThread::flushHw_l()
5849{
Phil Burk062e67a2015-02-11 13:40:50 -08005850 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005851 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005852 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005853 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005854}
5855
Andy Hung10cbff12017-02-21 17:30:14 -08005856int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5857 // If a VolumeShaper is active, we must wake up periodically to update volume.
5858 const int64_t NS_PER_MS = 1000000;
5859 return mVolumeShaperActive ?
5860 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5861}
5862
Eric Laurent81784c32012-11-19 14:55:58 -08005863// ----------------------------------------------------------------------------
5864
Eric Laurentbfb1b832013-01-07 09:53:42 -08005865AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005866 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005867 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005868 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005869 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005870 mDrainSequence(0),
5871 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005872{
5873}
5874
5875AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
5876{
5877}
5878
5879void AudioFlinger::AsyncCallbackThread::onFirstRef()
5880{
5881 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
5882}
5883
5884bool AudioFlinger::AsyncCallbackThread::threadLoop()
5885{
5886 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005887 uint32_t writeAckSequence;
5888 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005889 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005890
5891 {
5892 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005893 while (!((mWriteAckSequence & 1) ||
5894 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005895 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08005896 exitPending())) {
5897 mWaitWorkCV.wait(mLock);
5898 }
5899
Eric Laurentbfb1b832013-01-07 09:53:42 -08005900 if (exitPending()) {
5901 break;
5902 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005903 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
5904 mWriteAckSequence, mDrainSequence);
5905 writeAckSequence = mWriteAckSequence;
5906 mWriteAckSequence &= ~1;
5907 drainSequence = mDrainSequence;
5908 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005909 asyncError = mAsyncError;
5910 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005911 }
5912 {
Eric Laurent4de95592013-09-26 15:28:21 -07005913 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
5914 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005915 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005916 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005917 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07005918 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07005919 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005920 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005921 if (asyncError) {
5922 playbackThread->onAsyncError();
5923 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005924 }
5925 }
5926 }
5927 return false;
5928}
5929
5930void AudioFlinger::AsyncCallbackThread::exit()
5931{
5932 ALOGV("AsyncCallbackThread::exit");
5933 Mutex::Autolock _l(mLock);
5934 requestExit();
5935 mWaitWorkCV.broadcast();
5936}
5937
Eric Laurent3b4529e2013-09-05 18:09:19 -07005938void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005939{
5940 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005941 // bit 0 is cleared
5942 mWriteAckSequence = sequence << 1;
5943}
5944
5945void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
5946{
5947 Mutex::Autolock _l(mLock);
5948 // ignore unexpected callbacks
5949 if (mWriteAckSequence & 2) {
5950 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005951 mWaitWorkCV.signal();
5952 }
5953}
5954
Eric Laurent3b4529e2013-09-05 18:09:19 -07005955void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005956{
5957 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005958 // bit 0 is cleared
5959 mDrainSequence = sequence << 1;
5960}
5961
5962void AudioFlinger::AsyncCallbackThread::resetDraining()
5963{
5964 Mutex::Autolock _l(mLock);
5965 // ignore unexpected callbacks
5966 if (mDrainSequence & 2) {
5967 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005968 mWaitWorkCV.signal();
5969 }
5970}
5971
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005972void AudioFlinger::AsyncCallbackThread::setAsyncError()
5973{
5974 Mutex::Autolock _l(mLock);
5975 mAsyncError = true;
5976 mWaitWorkCV.signal();
5977}
5978
Eric Laurentbfb1b832013-01-07 09:53:42 -08005979
5980// ----------------------------------------------------------------------------
5981AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurente93cc032016-05-05 10:15:10 -07005982 AudioStreamOut* output, audio_io_handle_t id, uint32_t device, bool systemReady)
5983 : DirectOutputThread(audioFlinger, output, id, device, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07005984 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
5985 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005986{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07005987 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07005988 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07005989 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005990}
5991
Eric Laurentbfb1b832013-01-07 09:53:42 -08005992void AudioFlinger::OffloadThread::threadLoop_exit()
5993{
5994 if (mFlushPending || mHwPaused) {
5995 // If a flush is pending or track was paused, just discard buffered data
5996 flushHw_l();
5997 } else {
5998 mMixerStatus = MIXER_DRAIN_ALL;
5999 threadLoop_drain();
6000 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006001 if (mUseAsyncWrite) {
6002 ALOG_ASSERT(mCallbackThread != 0);
6003 mCallbackThread->exit();
6004 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006005 PlaybackThread::threadLoop_exit();
6006}
6007
6008AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6009 Vector< sp<Track> > *tracksToRemove
6010)
6011{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006012 size_t count = mActiveTracks.size();
6013
6014 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006015 bool doHwPause = false;
6016 bool doHwResume = false;
6017
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006018 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006019
Eric Laurentbfb1b832013-01-07 09:53:42 -08006020 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006021 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006022 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006023#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006024 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006025#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006026 // Only consider last track started for volume and mixer state control.
6027 // In theory an older track could underrun and restart after the new one starts
6028 // but as we only care about the transition phase between two tracks on a
6029 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006030 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006031 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006032
Haynes Mathew George7844f672014-01-15 12:32:55 -08006033 if (track->isInvalid()) {
6034 ALOGW("An invalidated track shouldn't be in active list");
6035 tracksToRemove->add(track);
6036 continue;
6037 }
6038
6039 if (track->mState == TrackBase::IDLE) {
6040 ALOGW("An idle track shouldn't be in active list");
6041 continue;
6042 }
6043
Eric Laurentbfb1b832013-01-07 09:53:42 -08006044 if (track->isPausing()) {
6045 track->setPaused();
6046 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006047 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006048 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006049 mHwPaused = true;
6050 }
6051 // If we were part way through writing the mixbuffer to
6052 // the HAL we must save this until we resume
6053 // BUG - this will be wrong if a different track is made active,
6054 // in that case we want to discard the pending data in the
6055 // mixbuffer and tell the client to present it again when the
6056 // track is resumed
6057 mPausedWriteLength = mCurrentWriteLength;
6058 mPausedBytesRemaining = mBytesRemaining;
6059 mBytesRemaining = 0; // stop writing
6060 }
6061 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006062 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006063 if (track->isStopping_1()) {
6064 track->mRetryCount = kMaxTrackStopRetriesOffload;
6065 } else {
6066 track->mRetryCount = kMaxTrackRetriesOffload;
6067 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006068 track->flushAck();
6069 if (last) {
6070 mFlushPending = true;
6071 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006072 } else if (track->isResumePending()){
6073 track->resumeAck();
6074 if (last) {
6075 if (mPausedBytesRemaining) {
6076 // Need to continue write that was interrupted
6077 mCurrentWriteLength = mPausedWriteLength;
6078 mBytesRemaining = mPausedBytesRemaining;
6079 mPausedBytesRemaining = 0;
6080 }
6081 if (mHwPaused) {
6082 doHwResume = true;
6083 mHwPaused = false;
6084 // threadLoop_mix() will handle the case that we need to
6085 // resume an interrupted write
6086 }
6087 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006088 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006089
Eric Laurent3df841a2016-07-15 15:15:40 -07006090 mLeftVolFloat = mRightVolFloat = -1.0;
6091
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006092 // Do not handle new data in this iteration even if track->framesReady()
6093 mixerStatus = MIXER_TRACKS_ENABLED;
6094 }
6095 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006096 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006097 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006098 if (track->mFillingUpStatus == Track::FS_FILLED) {
6099 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006100 if (last) {
6101 // make sure processVolume_l() will apply new volume even if 0
6102 mLeftVolFloat = mRightVolFloat = -1.0;
6103 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006104 }
6105
6106 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006107 sp<Track> previousTrack = mPreviousTrack.promote();
6108 if (previousTrack != 0) {
6109 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006110 // Flush any data still being written from last track
6111 mBytesRemaining = 0;
6112 if (mPausedBytesRemaining) {
6113 // Last track was paused so we also need to flush saved
6114 // mixbuffer state and invalidate track so that it will
6115 // re-submit that unwritten data when it is next resumed
6116 mPausedBytesRemaining = 0;
6117 // Invalidate is a bit drastic - would be more efficient
6118 // to have a flag to tell client that some of the
6119 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006120 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006121 }
6122 // flush data already sent to the DSP if changing audio session as audio
6123 // comes from a different source. Also invalidate previous track to force a
6124 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006125 if (previousTrack->sessionId() != track->sessionId()) {
6126 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006127 }
6128 }
6129 }
6130 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006131 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006132 if (track->isStopping_1()) {
6133 track->mRetryCount = kMaxTrackStopRetriesOffload;
6134 } else {
6135 track->mRetryCount = kMaxTrackRetriesOffload;
6136 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006137 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138 mixerStatus = MIXER_TRACKS_READY;
6139 }
6140 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006141 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006142 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006143 if (--(track->mRetryCount) <= 0) {
6144 // Hardware buffer can hold a large amount of audio so we must
6145 // wait for all current track's data to drain before we say
6146 // that the track is stopped.
6147 if (mBytesRemaining == 0) {
6148 // Only start draining when all data in mixbuffer
6149 // has been written
6150 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6151 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6152 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6153 if (last && !mStandby) {
6154 // do not modify drain sequence if we are already draining. This happens
6155 // when resuming from pause after drain.
6156 if ((mDrainSequence & 1) == 0) {
6157 mSleepTimeUs = 0;
6158 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6159 mixerStatus = MIXER_DRAIN_TRACK;
6160 mDrainSequence += 2;
6161 }
6162 if (mHwPaused) {
6163 // It is possible to move from PAUSED to STOPPING_1 without
6164 // a resume so we must ensure hardware is running
6165 doHwResume = true;
6166 mHwPaused = false;
6167 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006168 }
6169 }
Eric Laurente93cc032016-05-05 10:15:10 -07006170 } else if (last) {
6171 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6172 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006173 }
6174 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006175 // Drain has completed or we are in standby, signal presentation complete
6176 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006177 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006178 uint32_t latency = 0;
6179 status_t result = mOutput->stream->getLatency(&latency);
6180 ALOGE_IF(result != OK,
6181 "Error when retrieving output stream latency: %d", result);
6182 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006183 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006184 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006185 track->presentationComplete(framesWritten, audioHALFrames);
6186 track->reset();
6187 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006188 // DIRECT and OFFLOADED stop resets frame counts.
6189 if (!mUseAsyncWrite) {
6190 // If we don't get explicit drain notification we must
6191 // register discontinuity regardless of whether this is
6192 // the previous (!last) or the upcoming (last) track
6193 // to avoid skipping the discontinuity.
6194 mTimestampVerifier.discontinuity();
6195 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006196 }
6197 } else {
6198 // No buffers for this track. Give it a few chances to
6199 // fill a buffer, then remove it from active list.
6200 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006201 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006202 uint64_t position = 0;
6203 struct timespec unused;
6204 // The running check restarts the retry counter at least once.
6205 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6206 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6207 running = true;
6208 mOffloadUnderrunPosition = position;
6209 }
6210 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006211 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6212 (long long)position, (long long)mOffloadUnderrunPosition);
6213 }
6214 if (running) { // still running, give us more time.
6215 track->mRetryCount = kMaxTrackRetriesOffload;
6216 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006217 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6218 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006219 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006220 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006221 // it will then automatically call start() when data is available
6222 track->disable();
6223 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006224 } else if (last){
6225 mixerStatus = MIXER_TRACKS_ENABLED;
6226 }
6227 }
6228 }
6229 // compute volume for this track
6230 processVolume_l(track, last);
6231 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006232
Eric Laurentea0fade2013-10-04 16:23:48 -07006233 // make sure the pause/flush/resume sequence is executed in the right order.
6234 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6235 // before flush and then resume HW. This can happen in case of pause/flush/resume
6236 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006237 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006238 status_t result = mOutput->stream->pause();
6239 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006240 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006241 if (mFlushPending) {
6242 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006243 }
Eric Laurentfd477972013-10-25 18:10:40 -07006244 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006245 status_t result = mOutput->stream->resume();
6246 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006247 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006248
Eric Laurentbfb1b832013-01-07 09:53:42 -08006249 // remove all the tracks that need to be...
6250 removeTracks_l(*tracksToRemove);
6251
6252 return mixerStatus;
6253}
6254
Eric Laurentbfb1b832013-01-07 09:53:42 -08006255// must be called with thread mutex locked
6256bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6257{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006258 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6259 mWriteAckSequence, mDrainSequence);
6260 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006261 return true;
6262 }
6263 return false;
6264}
6265
Eric Laurentbfb1b832013-01-07 09:53:42 -08006266bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6267{
6268 Mutex::Autolock _l(mLock);
6269 return waitingAsyncCallback_l();
6270}
6271
6272void AudioFlinger::OffloadThread::flushHw_l()
6273{
Eric Laurente659ef42014-09-29 13:06:46 -07006274 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006275 // Flush anything still waiting in the mixbuffer
6276 mCurrentWriteLength = 0;
6277 mBytesRemaining = 0;
6278 mPausedWriteLength = 0;
6279 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006280 // reset bytes written count to reflect that DSP buffers are empty after flush.
6281 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006282 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006283
Eric Laurentbfb1b832013-01-07 09:53:42 -08006284 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006285 // discard any pending drain or write ack by incrementing sequence
6286 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6287 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006288 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006289 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6290 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006291 }
6292}
6293
Haynes Mathew George05317d22016-05-03 16:34:26 -07006294void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6295{
6296 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006297 if (PlaybackThread::invalidateTracks_l(streamType)) {
6298 mFlushPending = true;
6299 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006300}
6301
Eric Laurentbfb1b832013-01-07 09:53:42 -08006302// ----------------------------------------------------------------------------
6303
Eric Laurent81784c32012-11-19 14:55:58 -08006304AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006305 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -08006306 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->outDevice(),
Eric Laurent72e3f392015-05-20 14:43:50 -07006307 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006308 mWaitTimeMs(UINT_MAX)
6309{
6310 addOutputTrack(mainThread);
6311}
6312
6313AudioFlinger::DuplicatingThread::~DuplicatingThread()
6314{
6315 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6316 mOutputTracks[i]->destroy();
6317 }
6318}
6319
6320void AudioFlinger::DuplicatingThread::threadLoop_mix()
6321{
6322 // mix buffers...
6323 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006324 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006325 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006326 if (mMixerBufferValid) {
6327 memset(mMixerBuffer, 0, mMixerBufferSize);
6328 } else {
6329 memset(mSinkBuffer, 0, mSinkBufferSize);
6330 }
Eric Laurent81784c32012-11-19 14:55:58 -08006331 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006332 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006333 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006334 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006335 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006336}
6337
6338void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6339{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006340 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006341 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006342 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006343 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006344 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006345 }
6346 } else if (mBytesWritten != 0) {
6347 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6348 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006349 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006350 } else {
6351 // flush remaining overflow buffers in output tracks
6352 writeFrames = 0;
6353 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006354 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006355 }
6356}
6357
Eric Laurentbfb1b832013-01-07 09:53:42 -08006358ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006359{
6360 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006361 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6362
6363 // Consider the first OutputTrack for timestamp and frame counting.
6364
6365 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6366 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6367 // we always claim success.
6368 if (i == 0) {
6369 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6370 ALOGD_IF(correction != 0 && writeFrames != 0,
6371 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6372 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6373 mFramesWritten -= correction;
6374 }
6375
6376 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006377 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006378 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006379 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006380}
6381
6382void AudioFlinger::DuplicatingThread::threadLoop_standby()
6383{
6384 // DuplicatingThread implements standby by stopping all tracks
6385 for (size_t i = 0; i < outputTracks.size(); i++) {
6386 outputTracks[i]->stop();
6387 }
6388}
6389
Andy Hung1bc088a2018-02-09 15:57:31 -08006390void AudioFlinger::DuplicatingThread::dumpInternals(int fd, const Vector<String16>& args __unused)
6391{
6392 MixerThread::dumpInternals(fd, args);
6393
6394 std::stringstream ss;
6395 const size_t numTracks = mOutputTracks.size();
6396 ss << " " << numTracks << " OutputTracks";
6397 if (numTracks > 0) {
6398 ss << ":";
6399 for (const auto &track : mOutputTracks) {
6400 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006401 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006402 if (thread.get() != nullptr) {
6403 ss << thread.get() << ", " << thread->id();
6404 } else {
6405 ss << "null";
6406 }
6407 ss << ")";
6408 }
6409 }
6410 ss << "\n";
6411 std::string result = ss.str();
6412 write(fd, result.c_str(), result.size());
6413}
6414
Eric Laurent81784c32012-11-19 14:55:58 -08006415void AudioFlinger::DuplicatingThread::saveOutputTracks()
6416{
6417 outputTracks = mOutputTracks;
6418}
6419
6420void AudioFlinger::DuplicatingThread::clearOutputTracks()
6421{
6422 outputTracks.clear();
6423}
6424
6425void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6426{
6427 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006428 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6429 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6430 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6431 const size_t frameCount =
6432 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6433 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6434 // from different OutputTracks and their associated MixerThreads (e.g. one may
6435 // nearly empty and the other may be dropping data).
6436
6437 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006438 this,
6439 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006440 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006441 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006442 frameCount,
6443 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006444 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6445 if (status != NO_ERROR) {
6446 ALOGE("addOutputTrack() initCheck failed %d", status);
6447 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006448 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006449 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6450 mOutputTracks.add(outputTrack);
6451 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6452 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006453}
6454
6455void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6456{
6457 Mutex::Autolock _l(mLock);
6458 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6459 if (mOutputTracks[i]->thread() == thread) {
6460 mOutputTracks[i]->destroy();
6461 mOutputTracks.removeAt(i);
6462 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006463 if (thread->getOutput() == mOutput) {
6464 mOutput = NULL;
6465 }
Eric Laurent81784c32012-11-19 14:55:58 -08006466 return;
6467 }
6468 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006469 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006470}
6471
6472// caller must hold mLock
6473void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6474{
6475 mWaitTimeMs = UINT_MAX;
6476 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6477 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6478 if (strong != 0) {
6479 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6480 if (waitTimeMs < mWaitTimeMs) {
6481 mWaitTimeMs = waitTimeMs;
6482 }
6483 }
6484 }
6485}
6486
6487
6488bool AudioFlinger::DuplicatingThread::outputsReady(
6489 const SortedVector< sp<OutputTrack> > &outputTracks)
6490{
6491 for (size_t i = 0; i < outputTracks.size(); i++) {
6492 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6493 if (thread == 0) {
6494 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6495 outputTracks[i].get());
6496 return false;
6497 }
6498 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6499 // see note at standby() declaration
6500 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6501 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6502 thread.get());
6503 return false;
6504 }
6505 }
6506 return true;
6507}
6508
Kevin Rocard12381092018-04-11 09:19:59 -07006509void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6510 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006511{
Kevin Rocard12381092018-04-11 09:19:59 -07006512 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6513 outputTrack->setMetadatas(metadata.tracks);
6514 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006515}
6516
Eric Laurent81784c32012-11-19 14:55:58 -08006517uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6518{
6519 return (mWaitTimeMs * 1000) / 2;
6520}
6521
6522void AudioFlinger::DuplicatingThread::cacheParameters_l()
6523{
6524 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6525 updateWaitTime_l();
6526
6527 MixerThread::cacheParameters_l();
6528}
6529
Eric Laurent6acd1d42017-01-04 14:23:29 -08006530
Eric Laurent81784c32012-11-19 14:55:58 -08006531// ----------------------------------------------------------------------------
6532// Record
6533// ----------------------------------------------------------------------------
6534
6535AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6536 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006537 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -08006538 audio_devices_t outDevice,
Eric Laurent72e3f392015-05-20 14:43:50 -07006539 audio_devices_t inDevice,
6540 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006541 ) :
Eric Laurent72e3f392015-05-20 14:43:50 -07006542 ThreadBase(audioFlinger, id, outDevice, inDevice, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006543 mInput(input),
6544 mActiveTracks(&this->mLocalLog),
6545 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006546 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006547 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006548 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6549 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006550 // mFastCapture below
6551 , mFastCaptureFutex(0)
6552 // mInputSource
6553 // mPipeSink
6554 // mPipeSource
6555 , mPipeFramesP2(0)
6556 // mPipeMemory
6557 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006558 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006559 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006560{
Glenn Kastend7dca052015-03-05 16:05:54 -08006561 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6562 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006563
Andy Hungc8fddf32018-08-08 18:32:37 -07006564 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6565 mIsMsdDevice = strcmp(
6566 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6567 }
6568
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006569 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006570
Andy Hungc8fddf32018-08-08 18:32:37 -07006571 // TODO: We may also match on address as well as device type for
6572 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
6573 mTimestampCorrectedDevices = (audio_devices_t)property_get_int64(
6574 "audio.timestamp.corrected_input_devices",
6575 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6576 : AUDIO_DEVICE_NONE));
6577
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006578 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006579 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006580 size_t numCounterOffers = 0;
6581 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006582#if !LOG_NDEBUG
6583 ssize_t index =
6584#else
6585 (void)
6586#endif
6587 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006588 ALOG_ASSERT(index == 0);
6589
6590 // initialize fast capture depending on configuration
6591 bool initFastCapture;
6592 switch (kUseFastCapture) {
6593 case FastCapture_Never:
6594 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006595 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006596 break;
6597 case FastCapture_Always:
6598 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006599 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006600 break;
6601 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006602 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006603 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6604 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6605 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006606 break;
6607 // case FastCapture_Dynamic:
6608 }
6609
6610 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006611 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006612 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006613 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6614 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006615 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006616 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006617 const sp<MemoryDealer> roHeap(readOnlyHeap());
6618 sp<IMemory> pipeMemory;
6619 if ((roHeap == 0) ||
6620 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006621 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6622 ALOGE("not enough memory for pipe buffer size=%zu; "
6623 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6624 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6625 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006626 goto failed;
6627 }
6628 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6629 memset(pipeBuffer, 0, pipeSize);
6630 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6631 const NBAIO_Format offers[1] = {format};
6632 size_t numCounterOffers = 0;
6633 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6634 ALOG_ASSERT(index == 0);
6635 mPipeSink = pipe;
6636 PipeReader *pipeReader = new PipeReader(*pipe);
6637 numCounterOffers = 0;
6638 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6639 ALOG_ASSERT(index == 0);
6640 mPipeSource = pipeReader;
6641 mPipeFramesP2 = pipeFramesP2;
6642 mPipeMemory = pipeMemory;
6643
6644 // create fast capture
6645 mFastCapture = new FastCapture();
6646 FastCaptureStateQueue *sq = mFastCapture->sq();
6647#ifdef STATE_QUEUE_DUMP
6648 // FIXME
6649#endif
6650 FastCaptureState *state = sq->begin();
6651 state->mCblk = NULL;
6652 state->mInputSource = mInputSource.get();
6653 state->mInputSourceGen++;
6654 state->mPipeSink = pipe;
6655 state->mPipeSinkGen++;
6656 state->mFrameCount = mFrameCount;
6657 state->mCommand = FastCaptureState::COLD_IDLE;
6658 // already done in constructor initialization list
6659 //mFastCaptureFutex = 0;
6660 state->mColdFutexAddr = &mFastCaptureFutex;
6661 state->mColdGen++;
6662 state->mDumpState = &mFastCaptureDumpState;
6663#ifdef TEE_SINK
6664 // FIXME
6665#endif
6666 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6667 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6668 sq->end();
6669 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6670
6671 // start the fast capture
6672 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6673 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006674 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006675 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006676#ifdef AUDIO_WATCHDOG
6677 // FIXME
6678#endif
6679
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006680 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006681 }
Andy Hung8946a282018-04-19 20:04:56 -07006682#ifdef TEE_SINK
6683 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6684 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6685#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006686failed: ;
6687
6688 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006689}
6690
Eric Laurent81784c32012-11-19 14:55:58 -08006691AudioFlinger::RecordThread::~RecordThread()
6692{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006693 if (mFastCapture != 0) {
6694 FastCaptureStateQueue *sq = mFastCapture->sq();
6695 FastCaptureState *state = sq->begin();
6696 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6697 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6698 if (old == -1) {
6699 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6700 }
6701 }
6702 state->mCommand = FastCaptureState::EXIT;
6703 sq->end();
6704 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6705 mFastCapture->join();
6706 mFastCapture.clear();
6707 }
6708 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006709 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006710 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006711}
6712
6713void AudioFlinger::RecordThread::onFirstRef()
6714{
Glenn Kastend7dca052015-03-05 16:05:54 -08006715 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006716}
6717
Eric Laurent555530a2017-02-07 18:17:24 -08006718void AudioFlinger::RecordThread::preExit()
6719{
6720 ALOGV(" preExit()");
6721 Mutex::Autolock _l(mLock);
6722 for (size_t i = 0; i < mTracks.size(); i++) {
6723 sp<RecordTrack> track = mTracks[i];
6724 track->invalidate();
6725 }
6726 mActiveTracks.clear();
6727 mStartStopCond.broadcast();
6728}
6729
Eric Laurent81784c32012-11-19 14:55:58 -08006730bool AudioFlinger::RecordThread::threadLoop()
6731{
Eric Laurent81784c32012-11-19 14:55:58 -08006732 nsecs_t lastWarning = 0;
6733
6734 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006735
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006736reacquire_wakelock:
6737 sp<RecordTrack> activeTrack;
6738 {
6739 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006740 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006741 }
6742
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006743 // used to request a deferred sleep, to be executed later while mutex is unlocked
6744 uint32_t sleepUs = 0;
6745
6746 // loop while there is work to do
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006747 for (;;) {
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006748 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006749
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006750 // activeTracks accumulates a copy of a subset of mActiveTracks
6751 Vector< sp<RecordTrack> > activeTracks;
6752
Glenn Kasten735f45f2014-08-18 15:51:59 -07006753 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006754 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006755
Glenn Kasten735f45f2014-08-18 15:51:59 -07006756 // reference to a fast track which is about to be removed
6757 sp<RecordTrack> fastTrackToRemove;
6758
Eric Laurent81784c32012-11-19 14:55:58 -08006759 { // scope for mLock
6760 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006761
Eric Laurent021cf962014-05-13 10:18:14 -07006762 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006763
Eric Laurent000a4192014-01-29 15:17:32 -08006764 // check exitPending here because checkForNewParameters_l() and
6765 // checkForNewParameters_l() can temporarily release mLock
6766 if (exitPending()) {
6767 break;
6768 }
6769
Eric Laurent5c25d562016-07-13 17:17:45 -07006770 // sleep with mutex unlocked
6771 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006772 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006773 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6774 ATRACE_END();
6775 sleepUs = 0;
6776 continue;
6777 }
6778
Glenn Kasten2b806402013-11-20 16:37:38 -08006779 // if no active track(s), then standby and release wakelock
6780 size_t size = mActiveTracks.size();
6781 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006782 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006783 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006784 releaseWakeLock_l();
6785 ALOGV("RecordThread: loop stopping");
6786 // go to sleep
6787 mWaitWorkCV.wait(mLock);
6788 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006789 goto reacquire_wakelock;
6790 }
6791
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006792 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006793 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006794 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006795
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006796 activeTrack = mActiveTracks[i];
6797 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006798 if (activeTrack->isFastTrack()) {
6799 ALOG_ASSERT(fastTrackToRemove == 0);
6800 fastTrackToRemove = activeTrack;
6801 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006802 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006803 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006804 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006805 continue;
6806 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006807
6808 TrackBase::track_state activeTrackState = activeTrack->mState;
6809 switch (activeTrackState) {
6810
6811 case TrackBase::PAUSING:
6812 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006813 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006814 doBroadcast = true;
6815 size--;
6816 continue;
6817
6818 case TrackBase::STARTING_1:
6819 sleepUs = 10000;
6820 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006821 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006822 continue;
6823
6824 case TrackBase::STARTING_2:
6825 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006826 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006827 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006828 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006829 break;
6830
6831 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006832 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006833 break;
6834
Andy Hungce685402018-10-05 17:23:27 -07006835 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6836 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6837 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006838 default:
Andy Hungce685402018-10-05 17:23:27 -07006839 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6840 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006841 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006842
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006843 activeTracks.add(activeTrack);
6844 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006845
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006846 if (activeTrack->isFastTrack()) {
6847 ALOG_ASSERT(!mFastTrackAvail);
6848 ALOG_ASSERT(fastTrack == 0);
6849 fastTrack = activeTrack;
6850 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006851 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006852
Andy Hungdae27702016-10-31 14:01:16 -07006853 mActiveTracks.updatePowerState(this);
6854
Kevin Rocard069c2712018-03-29 19:09:14 -07006855 updateMetadata_l();
6856
Eric Laurent5c25d562016-07-13 17:17:45 -07006857 if (allStopped) {
6858 standbyIfNotAlreadyInStandby();
6859 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006860 if (doBroadcast) {
6861 mStartStopCond.broadcast();
6862 }
6863
6864 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006865 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006866 if (sleepUs == 0) {
6867 sleepUs = kRecordThreadSleepUs;
6868 }
6869 continue;
6870 }
6871 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07006872
Eric Laurent81784c32012-11-19 14:55:58 -08006873 lockEffectChains_l(effectChains);
6874 }
6875
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006876 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07006877
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006878 size_t size = effectChains.size();
6879 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006880 // thread mutex is not locked, but effect chain is locked
6881 effectChains[i]->process_l();
6882 }
6883
Glenn Kasten735f45f2014-08-18 15:51:59 -07006884 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006885 if (mFastCapture != 0) {
6886 FastCaptureStateQueue *sq = mFastCapture->sq();
6887 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07006888 bool didModify = false;
6889 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006890 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
6891 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
6892 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6893 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6894 if (old == -1) {
6895 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6896 }
6897 }
6898 state->mCommand = FastCaptureState::READ_WRITE;
6899#if 0 // FIXME
6900 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08006901 FastThreadDumpState::kSamplingNforLowRamDevice :
6902 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006903#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07006904 didModify = true;
6905 }
6906 audio_track_cblk_t *cblkOld = state->mCblk;
6907 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
6908 if (cblkNew != cblkOld) {
6909 state->mCblk = cblkNew;
6910 // block until acked if removing a fast track
6911 if (cblkOld != NULL) {
6912 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
6913 }
6914 didModify = true;
6915 }
jiabin01c8f562018-07-19 17:47:28 -07006916 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
6917 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
6918 if (state->mFastPatchRecordBufferProvider != abp) {
6919 state->mFastPatchRecordBufferProvider = abp;
6920 state->mFastPatchRecordFormat = fastTrack == 0 ?
6921 AUDIO_FORMAT_INVALID : fastTrack->format();
6922 didModify = true;
6923 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07006924 sq->end(didModify);
6925 if (didModify) {
6926 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006927#if 0
6928 if (kUseFastCapture == FastCapture_Dynamic) {
6929 mNormalSource = mPipeSource;
6930 }
6931#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006932 }
6933 }
6934
Glenn Kasten735f45f2014-08-18 15:51:59 -07006935 // now run the fast track destructor with thread mutex unlocked
6936 fastTrackToRemove.clear();
6937
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006938 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
6939 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
6940 // slow, then this RecordThread will overrun by not calling HAL read often enough.
6941 // If destination is non-contiguous, first read past the nominal end of buffer, then
6942 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07006943
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006944 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006945 ssize_t framesRead;
6946
6947 // If an NBAIO source is present, use it to read the normal capture's data
6948 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07006949 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07006950
6951 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
6952 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
6953 // we immediately retry the read() to get data and prevent another overflow.
6954 for (int retries = 0; retries <= 2; ++retries) {
6955 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
6956 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
6957 framesToRead);
6958 if (framesRead != OVERRUN) break;
6959 }
6960
Andy Hung7a3dc6b2018-05-01 16:39:51 -07006961 const ssize_t availableToRead = mPipeSource->availableToRead();
6962 if (availableToRead >= 0) {
6963 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
6964 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
6965 "more frames to read than fifo size, %zd > %zu",
6966 availableToRead, mPipeFramesP2);
6967 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
6968 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
6969 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
6970 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07006971 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
6972 }
6973 if (framesRead < 0) {
6974 status_t status = (status_t) framesRead;
6975 switch (status) {
6976 case OVERRUN:
6977 ALOGW("overrun on read from pipe");
6978 framesRead = 0;
6979 break;
6980 case NEGOTIATE:
6981 ALOGE("re-negotiation is needed");
6982 framesRead = -1; // Will cause an attempt to recover.
6983 break;
6984 default:
6985 ALOGE("unknown error %d on read from pipe", status);
6986 break;
6987 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006988 }
6989 // otherwise use the HAL / AudioStreamIn directly
6990 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07006991 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006992 size_t bytesRead;
6993 status_t result = mInput->stream->read(
6994 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07006995 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006996 if (result < 0) {
6997 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006998 } else {
6999 framesRead = bytesRead / mFrameSize;
7000 }
7001 }
7002
Andy Hung3f0c9022016-01-15 17:49:46 -08007003 // Update server timestamp with server stats
7004 // systemTime() is optional if the hardware supports timestamps.
7005 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7006 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7007
7008 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007009 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007010 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007011 if (mStandby) {
7012 mTimestampVerifier.discontinuity();
Andy Hungc8fddf32018-08-08 18:32:37 -07007013 } else if (mInput->stream->getCapturePosition(&position, &time) == NO_ERROR
7014 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7015
7016 mTimestampVerifier.add(position, time, mSampleRate);
7017
7018 // Correct timestamps
7019 if (isTimestampCorrectionEnabled()) {
7020 ALOGV("TS_BEFORE: %d %lld %lld",
7021 id(), (long long)time, (long long)position);
7022 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7023 position = correctedTimestamp.mFrames;
7024 time = correctedTimestamp.mTimeNs;
7025 ALOGV("TS_AFTER: %d %lld %lld",
7026 id(), (long long)time, (long long)position);
7027 }
7028
Andy Hung3f0c9022016-01-15 17:49:46 -08007029 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7030 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7031 // Note: In general record buffers should tend to be empty in
7032 // a properly running pipeline.
7033 //
7034 // Also, it is not advantageous to call get_presentation_position during the read
7035 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007036 } else {
7037 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007038 }
7039 }
7040 // Use this to track timestamp information
7041 // ALOGD("%s", mTimestamp.toString().c_str());
7042
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007043 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007044 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007045 // Force input into standby so that it tries to recover at next read attempt
7046 inputStandBy();
7047 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007048 }
7049 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007050 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007051 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007052 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007053 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007054
Andy Hung8946a282018-04-19 20:04:56 -07007055#ifdef TEE_SINK
7056 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7057#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007058 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007059 {
7060 size_t part1 = mRsmpInFramesP2 - rear;
7061 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007062 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007063 (framesRead - part1) * mFrameSize);
7064 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007065 }
7066 rear = mRsmpInRear += framesRead;
7067
7068 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007069
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007070 // loop over each active track
7071 for (size_t i = 0; i < size; i++) {
7072 activeTrack = activeTracks[i];
7073
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007074 // skip fast tracks, as those are handled directly by FastCapture
7075 if (activeTrack->isFastTrack()) {
7076 continue;
7077 }
7078
Andy Hung73c02e42015-03-29 01:13:58 -07007079 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007080 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7081
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007082 enum {
7083 OVERRUN_UNKNOWN,
7084 OVERRUN_TRUE,
7085 OVERRUN_FALSE
7086 } overrun = OVERRUN_UNKNOWN;
7087
7088 // loop over getNextBuffer to handle circular sink
7089 for (;;) {
7090
7091 activeTrack->mSink.frameCount = ~0;
7092 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7093 size_t framesOut = activeTrack->mSink.frameCount;
7094 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7095
Andy Hung73c02e42015-03-29 01:13:58 -07007096 // check available frames and handle overrun conditions
7097 // if the record track isn't draining fast enough.
7098 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007099 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007100 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7101 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007102 overrun = OVERRUN_TRUE;
7103 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007104 if (framesOut == 0 || framesIn == 0) {
7105 break;
7106 }
7107
Andy Hung6770c6f2015-04-07 13:43:36 -07007108 // Don't allow framesOut to be larger than what is possible with resampling
7109 // from framesIn.
7110 // This isn't strictly necessary but helps limit buffer resizing in
7111 // RecordBufferConverter. TODO: remove when no longer needed.
7112 framesOut = min(framesOut,
7113 destinationFramesPossible(
7114 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007115
7116 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007117 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007118 // straight from RecordThread buffer to RecordTrack buffer.
7119 AudioBufferProvider::Buffer buffer;
7120 buffer.frameCount = framesOut;
7121 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7122 if (status == OK && buffer.frameCount != 0) {
7123 ALOGV_IF(buffer.frameCount != framesOut,
7124 "%s() read less than expected (%zu vs %zu)",
7125 __func__, buffer.frameCount, framesOut);
7126 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007127 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007128 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7129 } else {
7130 framesOut = 0;
7131 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7132 __func__, status, buffer.frameCount);
7133 }
7134 } else {
7135 // process frames from the RecordThread buffer provider to the RecordTrack
7136 // buffer
7137 framesOut = activeTrack->mRecordBufferConverter->convert(
7138 activeTrack->mSink.raw,
7139 activeTrack->mResamplerBufferProvider,
7140 framesOut);
7141 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007142
7143 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7144 overrun = OVERRUN_FALSE;
7145 }
7146
7147 if (activeTrack->mFramesToDrop == 0) {
7148 if (framesOut > 0) {
7149 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007150 // Sanitize before releasing if the track has no access to the source data
7151 // An idle UID receives silence from non virtual devices until active
7152 if (activeTrack->isSilenced()) {
7153 memset(activeTrack->mSink.raw, 0, framesOut * mFrameSize);
7154 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007155 activeTrack->releaseBuffer(&activeTrack->mSink);
7156 }
7157 } else {
7158 // FIXME could do a partial drop of framesOut
7159 if (activeTrack->mFramesToDrop > 0) {
7160 activeTrack->mFramesToDrop -= framesOut;
7161 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007162 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007163 }
7164 } else {
7165 activeTrack->mFramesToDrop += framesOut;
7166 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7167 activeTrack->mSyncStartEvent->isCancelled()) {
7168 ALOGW("Synced record %s, session %d, trigger session %d",
7169 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7170 activeTrack->sessionId(),
7171 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007172 activeTrack->mSyncStartEvent->triggerSession() :
7173 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007174 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007175 }
7176 }
7177 }
7178
7179 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007180 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007181 }
7182 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007183
7184 switch (overrun) {
7185 case OVERRUN_TRUE:
7186 // client isn't retrieving buffers fast enough
7187 if (!activeTrack->setOverflow()) {
7188 nsecs_t now = systemTime();
7189 // FIXME should lastWarning per track?
7190 if ((now - lastWarning) > kWarningThrottleNs) {
7191 ALOGW("RecordThread: buffer overflow");
7192 lastWarning = now;
7193 }
7194 }
7195 break;
7196 case OVERRUN_FALSE:
7197 activeTrack->clearOverflow();
7198 break;
7199 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007200 break;
7201 }
7202
Andy Hung3f0c9022016-01-15 17:49:46 -08007203 // update frame information and push timestamp out
7204 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007205 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007206 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7207 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007208 }
7209
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007210unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007211 // enable changes in effect chain
7212 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007213 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurent81784c32012-11-19 14:55:58 -08007214 }
7215
Glenn Kasten93e471f2013-08-19 08:40:07 -07007216 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007217
7218 {
7219 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007220 for (size_t i = 0; i < mTracks.size(); i++) {
7221 sp<RecordTrack> track = mTracks[i];
7222 track->invalidate();
7223 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007224 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007225 mStartStopCond.broadcast();
7226 }
7227
7228 releaseWakeLock();
7229
7230 ALOGV("RecordThread %p exiting", this);
7231 return false;
7232}
7233
Glenn Kasten93e471f2013-08-19 08:40:07 -07007234void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007235{
7236 if (!mStandby) {
7237 inputStandBy();
7238 mStandby = true;
7239 }
7240}
7241
7242void AudioFlinger::RecordThread::inputStandBy()
7243{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007244 // Idle the fast capture if it's currently running
7245 if (mFastCapture != 0) {
7246 FastCaptureStateQueue *sq = mFastCapture->sq();
7247 FastCaptureState *state = sq->begin();
7248 if (!(state->mCommand & FastCaptureState::IDLE)) {
7249 state->mCommand = FastCaptureState::COLD_IDLE;
7250 state->mColdFutexAddr = &mFastCaptureFutex;
7251 state->mColdGen++;
7252 mFastCaptureFutex = 0;
7253 sq->end();
7254 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7255 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7256#if 0
7257 if (kUseFastCapture == FastCapture_Dynamic) {
7258 // FIXME
7259 }
7260#endif
7261#ifdef AUDIO_WATCHDOG
7262 // FIXME
7263#endif
7264 } else {
7265 sq->end(false /*didModify*/);
7266 }
7267 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007268 status_t result = mInput->stream->standby();
7269 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007270
7271 // If going into standby, flush the pipe source.
7272 if (mPipeSource.get() != nullptr) {
7273 const ssize_t flushed = mPipeSource->flush();
7274 if (flushed > 0) {
7275 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7276 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7277 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7278 }
7279 }
Eric Laurent81784c32012-11-19 14:55:58 -08007280}
7281
Glenn Kasten05997e22014-03-13 15:08:33 -07007282// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007283sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007284 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007285 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007286 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007287 audio_format_t format,
7288 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007289 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007290 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007291 size_t *pNotificationFrameCount,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007292 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007293 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007294 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007295 status_t *status,
7296 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08007297{
Glenn Kasten74935e42013-12-19 08:56:45 -08007298 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007299 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007300 sp<RecordTrack> track;
7301 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007302 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007303 audio_input_flags_t requestedFlags = *flags;
7304 uint32_t sampleRate;
7305
7306 lStatus = initCheck();
7307 if (lStatus != NO_ERROR) {
7308 ALOGE("createRecordTrack_l() audio driver not initialized");
7309 goto Exit;
7310 }
7311
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007312 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7313 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7314 lStatus = BAD_VALUE;
7315 goto Exit;
7316 }
7317
Eric Laurentf14db3c2017-12-08 14:20:36 -08007318 if (*pSampleRate == 0) {
7319 *pSampleRate = mSampleRate;
7320 }
7321 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007322
7323 // special case for FAST flag considered OK if fast capture is present
7324 if (hasFastCapture()) {
7325 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7326 }
7327
Eric Laurentf14db3c2017-12-08 14:20:36 -08007328 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007329 if ((*flags & inputFlags) != *flags) {
7330 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7331 " input flags (%08x)",
7332 *flags, inputFlags);
7333 *flags = (audio_input_flags_t)(*flags & inputFlags);
7334 }
Eric Laurent81784c32012-11-19 14:55:58 -08007335
Glenn Kasten90e58b12013-07-31 16:16:02 -07007336 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007337 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007338 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007339 // we formerly checked for a callback handler (non-0 tid),
7340 // but that is no longer required for TRANSFER_OBTAIN mode
7341 //
Glenn Kasten74105912014-07-03 12:28:53 -07007342 // frame count is not specified, or is exactly the pipe depth
7343 ((frameCount == 0) || (frameCount == mPipeFramesP2)) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007344 // PCM data
7345 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007346 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007347 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007348 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007349 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007350 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007351 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007352 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007353 hasFastCapture() &&
7354 // there are sufficient fast track slots available
7355 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007356 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007357 // check compatibility with audio effects.
7358 Mutex::Autolock _l(mLock);
7359 // Do not accept FAST flag if the session has software effects
7360 sp<EffectChain> chain = getEffectChain_l(sessionId);
7361 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007362 audio_input_flags_t old = *flags;
7363 chain->checkInputFlagCompatibility(flags);
7364 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007365 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7366 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007367 }
7368 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007369 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007370 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7371 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007372 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007373 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7374 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007375 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007376 this, frameCount, mFrameCount, mPipeFramesP2,
7377 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007378 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007379 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007380 }
7381 }
7382
Eric Laurentf14db3c2017-12-08 14:20:36 -08007383 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7384 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7385 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7386 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7387 lStatus = BAD_TYPE;
7388 goto Exit;
7389 }
7390
Glenn Kasten74105912014-07-03 12:28:53 -07007391 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007392 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007393 // fast track: frame count is exactly the pipe depth
7394 frameCount = mPipeFramesP2;
7395 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007396 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007397 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007398 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7399 // or 20 ms if there is a fast capture
7400 // TODO This could be a roundupRatio inline, and const
7401 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7402 * sampleRate + mSampleRate - 1) / mSampleRate;
7403 // minimum number of notification periods is at least kMinNotifications,
7404 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7405 static const size_t kMinNotifications = 3;
7406 static const uint32_t kMinMs = 30;
7407 // TODO This could be a roundupRatio inline
7408 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7409 // TODO This could be a roundupRatio inline
7410 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7411 maxNotificationFrames;
7412 const size_t minFrameCount = maxNotificationFrames *
7413 max(kMinNotifications, minNotificationsByMs);
7414 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007415 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7416 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007417 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007418 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007419 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007420 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007421
7422 { // scope for mLock
7423 Mutex::Autolock _l(mLock);
7424
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007425 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007426 format, channelMask, frameCount,
7427 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007428 *flags, TrackBase::TYPE_DEFAULT, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007429
Glenn Kasten03003332013-08-06 15:40:54 -07007430 lStatus = track->initCheck();
7431 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007432 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007433 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007434 goto Exit;
7435 }
7436 mTracks.add(track);
7437
Eric Laurent05067782016-06-01 18:27:28 -07007438 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007439 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7440 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7441 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007442 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007443 }
Eric Laurent81784c32012-11-19 14:55:58 -08007444 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007445
Eric Laurent81784c32012-11-19 14:55:58 -08007446 lStatus = NO_ERROR;
7447
7448Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007449 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007450 return track;
7451}
7452
7453status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7454 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007455 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007456{
7457 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7458 sp<ThreadBase> strongMe = this;
7459 status_t status = NO_ERROR;
7460
7461 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007462 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007463 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007464 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007465 triggerSession,
7466 recordTrack->sessionId(),
7467 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007468 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007469 // Sync event can be cancelled by the trigger session if the track is not in a
7470 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007471 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007472 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007473 } else {
7474 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007475 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007476 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007477 }
7478 }
7479
7480 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007481 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007482 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007483 if (recordTrack->isInvalid()) {
7484 recordTrack->clearSyncStartEvent();
7485 return INVALID_OPERATION;
7486 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007487 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7488 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007489 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7490 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007491 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007492 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007493 } else {
7494 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007495 }
7496 return status;
7497 }
7498
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007499 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7500 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7501 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007502 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007503 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007504 status_t status = NO_ERROR;
7505 if (recordTrack->isExternalTrack()) {
7506 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007507 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007508 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007509 if (recordTrack->isInvalid()) {
7510 recordTrack->clearSyncStartEvent();
7511 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7512 recordTrack->mState = TrackBase::STARTING_2;
7513 // STARTING_2 forces destroy to call stopInput.
7514 }
7515 return INVALID_OPERATION;
7516 }
7517 if (recordTrack->mState != TrackBase::STARTING_1) {
7518 ALOGW("%s(%d): unsynchronized mState:%d change",
7519 __func__, recordTrack->id(), recordTrack->mState);
7520 // Someone else has changed state, let them take over,
7521 // leave mState in the new state.
7522 recordTrack->clearSyncStartEvent();
7523 return INVALID_OPERATION;
7524 }
7525 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007526 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007527 ALOGW("%s(%d): startInput failed, status %d",
7528 __func__, recordTrack->id(), status);
7529 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7530 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007531 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007532 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007533 return status;
7534 }
Eric Laurent81784c32012-11-19 14:55:58 -08007535 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007536 // Catch up with current buffer indices if thread is already running.
7537 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7538 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7539 // see previously buffered data before it called start(), but with greater risk of overrun.
7540
Andy Hung73c02e42015-03-29 01:13:58 -07007541 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007542 if (!recordTrack->isDirect()) {
7543 // clear any converter state as new data will be discontinuous
7544 recordTrack->mRecordBufferConverter->reset();
7545 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007546 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007547 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007548 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007549 return status;
7550 }
Eric Laurent81784c32012-11-19 14:55:58 -08007551}
7552
Eric Laurent81784c32012-11-19 14:55:58 -08007553void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7554{
7555 sp<SyncEvent> strongEvent = event.promote();
7556
7557 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007558 sp<RefBase> ptr = strongEvent->cookie().promote();
7559 if (ptr != 0) {
7560 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7561 recordTrack->handleSyncStartEvent(strongEvent);
7562 }
Eric Laurent81784c32012-11-19 14:55:58 -08007563 }
7564}
7565
Glenn Kastena8356f62013-07-25 14:37:52 -07007566bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007567 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007568 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007569 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007570 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007571 return false;
7572 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007573 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007574 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007575
7576 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7577 mWaitWorkCV.broadcast(); // signal thread to stop
7578 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007579 }
Andy Hungce685402018-10-05 17:23:27 -07007580
7581 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007582 ALOGV("Record stopped OK");
7583 return true;
7584 }
Andy Hungce685402018-10-05 17:23:27 -07007585
7586 // don't handle anything - we've been invalidated or restarted and in a different state
7587 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7588 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007589 return false;
7590}
7591
Glenn Kasten0f11b512014-01-31 16:18:54 -08007592bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007593{
7594 return false;
7595}
7596
Glenn Kasten0f11b512014-01-31 16:18:54 -08007597status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007598{
7599#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7600 if (!isValidSyncEvent(event)) {
7601 return BAD_VALUE;
7602 }
7603
Glenn Kastend848eb42016-03-08 13:42:11 -08007604 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007605 status_t ret = NAME_NOT_FOUND;
7606
7607 Mutex::Autolock _l(mLock);
7608
7609 for (size_t i = 0; i < mTracks.size(); i++) {
7610 sp<RecordTrack> track = mTracks[i];
7611 if (eventSession == track->sessionId()) {
7612 (void) track->setSyncEvent(event);
7613 ret = NO_ERROR;
7614 }
7615 }
7616 return ret;
7617#else
7618 return BAD_VALUE;
7619#endif
7620}
7621
jiabin653cc0a2018-01-17 17:54:10 -08007622status_t AudioFlinger::RecordThread::getActiveMicrophones(
7623 std::vector<media::MicrophoneInfo>* activeMicrophones)
7624{
7625 ALOGV("RecordThread::getActiveMicrophones");
7626 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007627 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7628 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007629}
7630
Paul McLean03a6e6a2018-12-04 10:54:13 -07007631status_t AudioFlinger::RecordThread::setMicrophoneDirection(audio_microphone_direction_t direction)
7632{
7633 ALOGV("RecordThread::setMicrophoneDirection");
7634 AutoMutex _l(mLock);
7635 return mInput->stream->setMicrophoneDirection(direction);
7636}
7637
7638status_t AudioFlinger::RecordThread::setMicrophoneFieldDimension(float zoom)
7639{
7640 ALOGV("RecordThread::setMicrophoneFieldDimension");
7641 AutoMutex _l(mLock);
7642 return mInput->stream->setMicrophoneFieldDimension(zoom);
7643}
7644
Kevin Rocard069c2712018-03-29 19:09:14 -07007645void AudioFlinger::RecordThread::updateMetadata_l()
7646{
7647 if (mInput == nullptr || mInput->stream == nullptr ||
7648 !mActiveTracks.readAndClearHasChanged()) {
7649 return;
7650 }
7651 StreamInHalInterface::SinkMetadata metadata;
7652 for (const sp<RecordTrack> &track : mActiveTracks) {
7653 // No track is invalid as this is called after prepareTrack_l in the same critical section
7654 metadata.tracks.push_back({
7655 .source = track->attributes().source,
7656 .gain = 1, // capture tracks do not have volumes
7657 });
7658 }
7659 mInput->stream->updateSinkMetadata(metadata);
7660}
7661
Eric Laurent81784c32012-11-19 14:55:58 -08007662// destroyTrack_l() must be called with ThreadBase::mLock held
7663void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7664{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007665 track->terminate();
7666 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007667 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007668 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007669 removeTrack_l(track);
7670 }
7671}
7672
7673void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7674{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007675 String8 result;
7676 track->appendDump(result, false /* active */);
7677 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7678
Eric Laurent81784c32012-11-19 14:55:58 -08007679 mTracks.remove(track);
7680 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007681 if (track->isFastTrack()) {
7682 ALOG_ASSERT(!mFastTrackAvail);
7683 mFastTrackAvail = true;
7684 }
Eric Laurent81784c32012-11-19 14:55:58 -08007685}
7686
7687void AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
7688{
7689 dumpInternals(fd, args);
7690 dumpTracks(fd, args);
7691 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007692 dprintf(fd, " Local log:\n");
7693 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent81784c32012-11-19 14:55:58 -08007694}
7695
7696void AudioFlinger::RecordThread::dumpInternals(int fd, const Vector<String16>& args)
7697{
Glenn Kasten44182c22015-03-05 17:12:23 -08007698 dumpBase(fd, args);
7699
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007700 AudioStreamIn *input = mInput;
7701 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7702 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
7703 input, flags, inputFlagsToString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007704 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007705 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007706 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007707 }
Andy Hungbfa64962017-06-12 14:43:19 -07007708
7709 if (input != nullptr) {
7710 dprintf(fd, " Hal stream dump:\n");
7711 (void)input->stream->dump(fd);
7712 }
7713
Mikhail Naganovf4a342a2018-12-04 08:55:41 -08007714 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hung7f39f562018-08-08 17:30:20 -07007715 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
Andy Hung20bd30b2018-06-01 15:39:35 -07007716 if (latencyMs != 0.) {
7717 dprintf(fd, " NormalRecord latency ms: %.2lf\n", latencyMs);
7718 } else {
7719 dprintf(fd, " NormalRecord latency ms: unavail\n");
7720 }
7721
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007722 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007723 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007724
Glenn Kasten2f90c512015-12-02 11:40:09 -08007725 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7726 // while we are dumping it. It may be inconsistent, but it won't mutate!
7727 // This is a large object so we place it on the heap.
7728 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007729 const std::unique_ptr<FastCaptureDumpState> copy =
7730 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007731 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007732}
7733
Glenn Kasten0f11b512014-01-31 16:18:54 -08007734void AudioFlinger::RecordThread::dumpTracks(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007735{
Eric Laurent81784c32012-11-19 14:55:58 -08007736 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007737 size_t numtracks = mTracks.size();
7738 size_t numactive = mActiveTracks.size();
7739 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007740 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007741 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007742 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007743 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007744 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007745 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007746 for (size_t i = 0; i < numtracks ; ++i) {
7747 sp<RecordTrack> track = mTracks[i];
7748 if (track != 0) {
7749 bool active = mActiveTracks.indexOf(track) >= 0;
7750 if (active) {
7751 numactiveseen++;
7752 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007753 result.append(prefix);
7754 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007755 }
Eric Laurent81784c32012-11-19 14:55:58 -08007756 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007757 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007758 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007759 }
7760
Marco Nelissenb2208842014-02-07 14:00:50 -08007761 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007762 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007763 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007764 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007765 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007766 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007767 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007768 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007769 result.append(prefix);
7770 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007771 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007772 }
Eric Laurent81784c32012-11-19 14:55:58 -08007773
7774 }
7775 write(fd, result.string(), result.size());
7776}
7777
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007778void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7779{
7780 Mutex::Autolock _l(mLock);
7781 for (size_t i = 0; i < mTracks.size() ; i++) {
7782 sp<RecordTrack> track = mTracks[i];
7783 if (track != 0 && track->uid() == uid) {
7784 track->setSilenced(silenced);
7785 }
7786 }
7787}
Andy Hung73c02e42015-03-29 01:13:58 -07007788
7789void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7790{
7791 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7792 RecordThread *recordThread = (RecordThread *) threadBase.get();
7793 mRsmpInFront = recordThread->mRsmpInRear;
7794 mRsmpInUnrel = 0;
7795}
7796
7797void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7798 size_t *framesAvailable, bool *hasOverrun)
7799{
7800 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7801 RecordThread *recordThread = (RecordThread *) threadBase.get();
7802 const int32_t rear = recordThread->mRsmpInRear;
7803 const int32_t front = mRsmpInFront;
7804 const ssize_t filled = rear - front;
7805
7806 size_t framesIn;
7807 bool overrun = false;
7808 if (filled < 0) {
7809 // should not happen, but treat like a massive overrun and re-sync
7810 framesIn = 0;
7811 mRsmpInFront = rear;
7812 overrun = true;
7813 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7814 framesIn = (size_t) filled;
7815 } else {
7816 // client is not keeping up with server, but give it latest data
7817 framesIn = recordThread->mRsmpInFrames;
7818 mRsmpInFront = /* front = */ rear - framesIn;
7819 overrun = true;
7820 }
7821 if (framesAvailable != NULL) {
7822 *framesAvailable = framesIn;
7823 }
7824 if (hasOverrun != NULL) {
7825 *hasOverrun = overrun;
7826 }
7827}
7828
Eric Laurent81784c32012-11-19 14:55:58 -08007829// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007830status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007831 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007832{
Andy Hung73c02e42015-03-29 01:13:58 -07007833 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007834 if (threadBase == 0) {
7835 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007836 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007837 return NOT_ENOUGH_DATA;
7838 }
7839 RecordThread *recordThread = (RecordThread *) threadBase.get();
7840 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007841 int32_t front = mRsmpInFront;
Glenn Kasten85948432013-08-19 12:09:05 -07007842 ssize_t filled = rear - front;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007843 // FIXME should not be P2 (don't want to increase latency)
7844 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007845 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007846 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007847 front &= recordThread->mRsmpInFramesP2 - 1;
7848 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07007849 if (part1 > (size_t) filled) {
7850 part1 = filled;
7851 }
7852 size_t ask = buffer->frameCount;
7853 ALOG_ASSERT(ask > 0);
7854 if (part1 > ask) {
7855 part1 = ask;
7856 }
7857 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07007858 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07007859 buffer->raw = NULL;
7860 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07007861 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07007862 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08007863 }
7864
Andy Hung57446612015-04-19 23:56:46 -07007865 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07007866 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07007867 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08007868 return NO_ERROR;
7869}
7870
7871// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007872void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
7873 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007874{
Glenn Kasten85948432013-08-19 12:09:05 -07007875 size_t stepCount = buffer->frameCount;
7876 if (stepCount == 0) {
7877 return;
7878 }
Andy Hung73c02e42015-03-29 01:13:58 -07007879 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
7880 mRsmpInUnrel -= stepCount;
7881 mRsmpInFront += stepCount;
Glenn Kasten85948432013-08-19 12:09:05 -07007882 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08007883 buffer->frameCount = 0;
7884}
7885
Eric Laurentd8365c52017-07-16 15:27:05 -07007886void AudioFlinger::RecordThread::checkBtNrec()
7887{
7888 Mutex::Autolock _l(mLock);
7889 checkBtNrec_l();
7890}
7891
7892void AudioFlinger::RecordThread::checkBtNrec_l()
7893{
7894 // disable AEC and NS if the device is a BT SCO headset supporting those
7895 // pre processings
7896 bool suspend = audio_is_bluetooth_sco_device(mInDevice) &&
7897 mAudioFlinger->btNrecIsOff();
7898 if (mBtNrecSuspended.exchange(suspend) != suspend) {
7899 for (size_t i = 0; i < mEffectChains.size(); i++) {
7900 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
7901 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
7902 }
7903 }
7904}
7905
Andy Hung97a893e2015-03-29 01:03:07 -07007906
Eric Laurent10351942014-05-08 18:49:52 -07007907bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
7908 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007909{
7910 bool reconfig = false;
7911
Eric Laurent10351942014-05-08 18:49:52 -07007912 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007913
Eric Laurent10351942014-05-08 18:49:52 -07007914 audio_format_t reqFormat = mFormat;
7915 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07007916 // 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 -07007917 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
7918
7919 AudioParameter param = AudioParameter(keyValuePair);
7920 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07007921
7922 // scope for AutoPark extends to end of method
7923 AutoPark<FastCapture> park(mFastCapture);
7924
Eric Laurent10351942014-05-08 18:49:52 -07007925 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
7926 // channel count change can be requested. Do we mandate the first client defines the
7927 // HAL sampling rate and channel count or do we allow changes on the fly?
7928 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
7929 samplingRate = value;
7930 reconfig = true;
7931 }
7932 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07007933 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07007934 status = BAD_VALUE;
7935 } else {
7936 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08007937 reconfig = true;
7938 }
Eric Laurent10351942014-05-08 18:49:52 -07007939 }
7940 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
7941 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07007942 if (!audio_is_input_channel(mask) ||
7943 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07007944 status = BAD_VALUE;
7945 } else {
7946 channelMask = mask;
7947 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007948 }
Eric Laurent10351942014-05-08 18:49:52 -07007949 }
7950 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7951 // do not accept frame count changes if tracks are open as the track buffer
7952 // size depends on frame count and correct behavior would not be guaranteed
7953 // if frame count is changed after track creation
7954 if (mActiveTracks.size() > 0) {
7955 status = INVALID_OPERATION;
7956 } else {
7957 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08007958 }
Eric Laurent10351942014-05-08 18:49:52 -07007959 }
7960 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
7961 // forward device change to effects that have requested to be
7962 // aware of attached audio device.
7963 for (size_t i = 0; i < mEffectChains.size(); i++) {
7964 mEffectChains[i]->setDevice_l(value);
Eric Laurent81784c32012-11-19 14:55:58 -08007965 }
Eric Laurent81784c32012-11-19 14:55:58 -08007966
Eric Laurent10351942014-05-08 18:49:52 -07007967 // store input device and output device but do not forward output device to audio HAL.
7968 // Note that status is ignored by the caller for output device
7969 // (see AudioFlinger::setParameters()
7970 if (audio_is_output_devices(value)) {
7971 mOutDevice = value;
7972 status = BAD_VALUE;
7973 } else {
7974 mInDevice = value;
Eric Laurente8726fe2015-06-26 09:39:24 -07007975 if (value != AUDIO_DEVICE_NONE) {
7976 mPrevInDevice = value;
7977 }
Eric Laurentd8365c52017-07-16 15:27:05 -07007978 checkBtNrec_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007979 }
Eric Laurent10351942014-05-08 18:49:52 -07007980 }
7981 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
7982 mAudioSource != (audio_source_t)value) {
7983 // forward device change to effects that have requested to be
7984 // aware of attached audio device.
7985 for (size_t i = 0; i < mEffectChains.size(); i++) {
7986 mEffectChains[i]->setAudioSource_l((audio_source_t)value);
Eric Laurent81784c32012-11-19 14:55:58 -08007987 }
Eric Laurent10351942014-05-08 18:49:52 -07007988 mAudioSource = (audio_source_t)value;
7989 }
Glenn Kastene198c362013-08-13 09:13:36 -07007990
Eric Laurent10351942014-05-08 18:49:52 -07007991 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007992 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007993 if (status == INVALID_OPERATION) {
7994 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007995 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007996 }
7997 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007998 if (status == BAD_VALUE) {
7999 uint32_t sRate;
8000 audio_channel_mask_t channelMask;
8001 audio_format_t format;
8002 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8003 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8004 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8005 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8006 status = NO_ERROR;
8007 }
Eric Laurent81784c32012-11-19 14:55:58 -08008008 }
Eric Laurent10351942014-05-08 18:49:52 -07008009 if (status == NO_ERROR) {
8010 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008011 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008012 }
8013 }
Eric Laurent81784c32012-11-19 14:55:58 -08008014 }
Eric Laurent10351942014-05-08 18:49:52 -07008015
Eric Laurent81784c32012-11-19 14:55:58 -08008016 return reconfig;
8017}
8018
8019String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8020{
Eric Laurent81784c32012-11-19 14:55:58 -08008021 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008022 if (initCheck() == NO_ERROR) {
8023 String8 out_s8;
8024 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8025 return out_s8;
8026 }
Eric Laurent81784c32012-11-19 14:55:58 -08008027 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008028 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008029}
8030
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008031void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008032 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8033
8034 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008035
8036 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008037 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008038 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008039 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008040 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008041 desc->mChannelMask = mChannelMask;
8042 desc->mSamplingRate = mSampleRate;
8043 desc->mFormat = mFormat;
8044 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008045 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008046 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008047 break;
8048
Eric Laurent73e26b62015-04-27 16:55:58 -07008049 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008050 default:
8051 break;
8052 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008053 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008054}
8055
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008056void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008057{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008058 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8059 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008060 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008061 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8062 if (audio_is_linear_pcm(mFormat)) {
8063 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8064 mChannelCount, FCC_8);
8065 } else {
8066 // Can have more that FCC_8 channels in encoded streams.
8067 ALOGI("HAL format %#x is not linear pcm", mFormat);
8068 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008069 result = mInput->stream->getFrameSize(&mFrameSize);
8070 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8071 result = mInput->stream->getBufferSize(&mBufferSize);
8072 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008073 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008074 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8075 "mBufferSize=%lld, mFrameCount=%lld",
8076 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8077 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008078 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008079 // 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 -07008080 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008081 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008082 // A larger value should allow more old data to be read after a track calls start(),
8083 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008084 //
8085 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008086 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008087 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008088 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008089 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008090
8091 // TODO optimize audio capture buffer sizes ...
8092 // Here we calculate the size of the sliding buffer used as a source
8093 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8094 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8095 // be better to have it derived from the pipe depth in the long term.
8096 // The current value is higher than necessary. However it should not add to latency.
8097
Glenn Kasten85948432013-08-19 12:09:05 -07008098 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008099 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8100 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008101 // if posix_memalign fails, will segv here.
8102 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008103
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008104 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8105 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008106}
8107
Glenn Kasten5f972c02014-01-13 09:59:31 -08008108uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008109{
8110 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008111 uint32_t result;
8112 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8113 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008114 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008115 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008116}
8117
Eric Laurent4c415062016-06-17 16:14:16 -07008118// hasAudioSession_l() must be called with ThreadBase::mLock held
8119uint32_t AudioFlinger::RecordThread::hasAudioSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08008120{
Eric Laurent81784c32012-11-19 14:55:58 -08008121 uint32_t result = 0;
8122 if (getEffectChain_l(sessionId) != 0) {
8123 result = EFFECT_SESSION;
8124 }
8125
8126 for (size_t i = 0; i < mTracks.size(); ++i) {
8127 if (sessionId == mTracks[i]->sessionId()) {
8128 result |= TRACK_SESSION;
Eric Laurent4c415062016-06-17 16:14:16 -07008129 if (mTracks[i]->isFastTrack()) {
8130 result |= FAST_SESSION;
8131 }
Eric Laurent81784c32012-11-19 14:55:58 -08008132 break;
8133 }
8134 }
8135
8136 return result;
8137}
8138
Glenn Kastend848eb42016-03-08 13:42:11 -08008139KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008140{
Glenn Kastend848eb42016-03-08 13:42:11 -08008141 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008142 Mutex::Autolock _l(mLock);
8143 for (size_t j = 0; j < mTracks.size(); ++j) {
8144 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008145 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008146 if (ids.indexOfKey(sessionId) < 0) {
8147 ids.add(sessionId, true);
8148 }
8149 }
8150 return ids;
8151}
8152
8153AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8154{
8155 Mutex::Autolock _l(mLock);
8156 AudioStreamIn *input = mInput;
8157 mInput = NULL;
8158 return input;
8159}
8160
8161// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008162sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008163{
8164 if (mInput == NULL) {
8165 return NULL;
8166 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008167 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008168}
8169
8170status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8171{
8172 // only one chain per input thread
Eric Tan39ec8d62018-07-24 09:49:29 -07008173 if (!mEffectChains.isEmpty()) {
Eric Laurentaaa44472014-09-12 17:41:50 -07008174 ALOGW("addEffectChain_l() already one chain %p on thread %p", chain.get(), this);
Eric Laurent81784c32012-11-19 14:55:58 -08008175 return INVALID_OPERATION;
8176 }
8177 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008178 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008179 chain->setInBuffer(NULL);
8180 chain->setOutBuffer(NULL);
8181
8182 checkSuspendOnAddEffectChain_l(chain);
8183
Eric Laurent1b928682014-10-02 19:41:47 -07008184 // make sure enabled pre processing effects state is communicated to the HAL as we
8185 // just moved them to a new input stream.
8186 chain->syncHalEffectsState();
8187
Eric Laurent81784c32012-11-19 14:55:58 -08008188 mEffectChains.add(chain);
8189
8190 return NO_ERROR;
8191}
8192
8193size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8194{
8195 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
8196 ALOGW_IF(mEffectChains.size() != 1,
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008197 "removeEffectChain_l() %p invalid chain size %zu on thread %p",
Eric Laurent81784c32012-11-19 14:55:58 -08008198 chain.get(), mEffectChains.size(), this);
8199 if (mEffectChains.size() == 1) {
8200 mEffectChains.removeAt(0);
8201 }
8202 return 0;
8203}
8204
Eric Laurent1c333e22014-05-20 10:48:17 -07008205status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8206 audio_patch_handle_t *handle)
8207{
8208 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008209
8210 // store new device and send to effects
8211 mInDevice = patch->sources[0].ext.device.type;
François Gaffie0c280aa2018-07-25 10:02:15 +02008212 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent296fb132015-05-01 11:38:42 -07008213 mPatch = *patch;
Eric Laurent054d9d32015-04-24 08:48:48 -07008214 for (size_t i = 0; i < mEffectChains.size(); i++) {
8215 mEffectChains[i]->setDevice_l(mInDevice);
8216 }
8217
Eric Laurentd8365c52017-07-16 15:27:05 -07008218 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008219
8220 // store new source and send to effects
8221 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8222 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008223 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008224 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008225 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008226 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008227
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008228 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008229 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8230 status = hwDevice->createAudioPatch(patch->num_sources,
8231 patch->sources,
8232 patch->num_sinks,
8233 patch->sinks,
8234 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008235 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008236 char *address;
8237 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8238 address = audio_device_address_to_parameter(
8239 patch->sources[0].ext.device.type,
8240 patch->sources[0].ext.device.address);
8241 } else {
8242 address = (char *)calloc(1, 1);
8243 }
8244 AudioParameter param = AudioParameter(String8(address));
8245 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008246 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008247 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008248 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008249 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008250 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008251 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008252 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008253
François Gaffie0c280aa2018-07-25 10:02:15 +02008254 if ((mInDevice != mPrevInDevice) || (mDeviceId != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008255 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8256 mPrevInDevice = mInDevice;
François Gaffie0c280aa2018-07-25 10:02:15 +02008257 mDeviceId = deviceId;
Eric Laurente8726fe2015-06-26 09:39:24 -07008258 }
Eric Laurent296fb132015-05-01 11:38:42 -07008259
Eric Laurent1c333e22014-05-20 10:48:17 -07008260 return status;
8261}
8262
8263status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8264{
8265 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008266
8267 mInDevice = AUDIO_DEVICE_NONE;
8268
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008269 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008270 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8271 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008272 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008273 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008274 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008275 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008276 }
8277 return status;
8278}
8279
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008280void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008281{
8282 Mutex::Autolock _l(mLock);
8283 mTracks.add(record);
8284}
8285
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008286void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008287{
8288 Mutex::Autolock _l(mLock);
8289 destroyTrack_l(record);
8290}
8291
Mikhail Naganovdc769682018-05-04 15:34:08 -07008292void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008293{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008294 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008295 config->role = AUDIO_PORT_ROLE_SINK;
8296 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8297 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008298 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8299 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8300 config->flags.input = mInput->flags;
8301 }
Eric Laurent83b88082014-06-20 18:31:16 -07008302}
Eric Laurent1c333e22014-05-20 10:48:17 -07008303
Eric Laurent6acd1d42017-01-04 14:23:29 -08008304// ----------------------------------------------------------------------------
8305// Mmap
8306// ----------------------------------------------------------------------------
8307
8308AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8309 : mThread(thread)
8310{
Phil Burk9fabbf82017-08-03 12:02:00 -07008311 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008312}
8313
8314AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8315{
Phil Burk9fabbf82017-08-03 12:02:00 -07008316 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008317}
8318
8319status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8320 struct audio_mmap_buffer_info *info)
8321{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008322 return mThread->createMmapBuffer(minSizeFrames, info);
8323}
8324
8325status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8326{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008327 return mThread->getMmapPosition(position);
8328}
8329
Eric Laurenta54f1282017-07-01 19:39:32 -07008330status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008331 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008332
8333{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008334 return mThread->start(client, handle);
8335}
8336
8337status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8338{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008339 return mThread->stop(handle);
8340}
8341
Eric Laurent18b57012017-02-13 16:23:52 -08008342status_t AudioFlinger::MmapThreadHandle::standby()
8343{
Eric Laurent18b57012017-02-13 16:23:52 -08008344 return mThread->standby();
8345}
8346
Eric Laurent6acd1d42017-01-04 14:23:29 -08008347
8348AudioFlinger::MmapThread::MmapThread(
8349 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
8350 AudioHwDevice *hwDev, sp<StreamHalInterface> stream,
8351 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
8352 : ThreadBase(audioFlinger, id, outDevice, inDevice, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008353 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008354 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008355 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008356 mActiveTracks(&this->mLocalLog),
8357 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8358 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008359{
Eric Laurent18b57012017-02-13 16:23:52 -08008360 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008361 readHalParameters_l();
8362}
8363
8364AudioFlinger::MmapThread::~MmapThread()
8365{
Eric Laurent18b57012017-02-13 16:23:52 -08008366 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008367}
8368
8369void AudioFlinger::MmapThread::onFirstRef()
8370{
8371 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8372}
8373
8374void AudioFlinger::MmapThread::disconnect()
8375{
Eric Laurent331679c2018-04-16 17:03:16 -07008376 ActiveTracks<MmapTrack> activeTracks;
8377 {
8378 Mutex::Autolock _l(mLock);
8379 for (const sp<MmapTrack> &t : mActiveTracks) {
8380 activeTracks.add(t);
8381 }
8382 }
8383 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008384 stop(t->portId());
8385 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008386 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008387 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008388 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008389 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008390 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008391 }
8392}
8393
8394
8395void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8396 audio_stream_type_t streamType __unused,
8397 audio_session_t sessionId,
8398 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008399 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008400 audio_port_handle_t portId)
8401{
8402 mAttr = *attr;
8403 mSessionId = sessionId;
8404 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008405 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008406 mPortId = portId;
8407}
8408
8409status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8410 struct audio_mmap_buffer_info *info)
8411{
8412 if (mHalStream == 0) {
8413 return NO_INIT;
8414 }
Eric Laurent18b57012017-02-13 16:23:52 -08008415 mStandby = true;
8416 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008417 return mHalStream->createMmapBuffer(minSizeFrames, info);
8418}
8419
8420status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8421{
8422 if (mHalStream == 0) {
8423 return NO_INIT;
8424 }
8425 return mHalStream->getMmapPosition(position);
8426}
8427
Eric Laurent331679c2018-04-16 17:03:16 -07008428status_t AudioFlinger::MmapThread::exitStandby()
8429{
8430 status_t ret = mHalStream->start();
8431 if (ret != NO_ERROR) {
8432 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8433 return ret;
8434 }
8435 mStandby = false;
8436 return NO_ERROR;
8437}
8438
Eric Laurenta54f1282017-07-01 19:39:32 -07008439status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008440 audio_port_handle_t *handle)
8441{
Eric Laurenta54f1282017-07-01 19:39:32 -07008442 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8443 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008444 if (mHalStream == 0) {
8445 return NO_INIT;
8446 }
8447
8448 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008449
Eric Laurenta54f1282017-07-01 19:39:32 -07008450 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008451 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008452 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008453 }
8454
8455 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8456
8457 audio_io_handle_t io = mId;
8458 if (isOutput()) {
8459 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8460 config.sample_rate = mSampleRate;
8461 config.channel_mask = mChannelMask;
8462 config.format = mFormat;
8463 audio_stream_type_t stream = streamType();
8464 audio_output_flags_t flags =
8465 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008466 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008467 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008468 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8469 mSessionId,
8470 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008471 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008472 client.clientUid,
8473 &config,
8474 flags,
8475 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008476 &portId,
8477 &secondaryOutputs);
8478 ALOGD_IF(!secondaryOutputs.empty(),
8479 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008480 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008481 audio_config_base_t config;
8482 config.sample_rate = mSampleRate;
8483 config.channel_mask = mChannelMask;
8484 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008485 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008486 ret = AudioSystem::getInputForAttr(&mAttr, &io,
8487 mSessionId,
8488 client.clientPid,
8489 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008490 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008491 &config,
8492 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8493 &deviceId,
8494 &portId);
8495 }
8496 // APM should not chose a different input or output stream for the same set of attributes
8497 // and audo configuration
8498 if (ret != NO_ERROR || io != mId) {
8499 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8500 __FUNCTION__, ret, io, mId);
8501 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008502 }
8503
8504 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008505 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008506 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008507 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008508 }
8509
Eric Laurent331679c2018-04-16 17:03:16 -07008510 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008511 // abort if start is rejected by audio policy manager
8512 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008513 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008514 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008515 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008516 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008517 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008518 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008519 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008520 }
Eric Laurent331679c2018-04-16 17:03:16 -07008521 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008522 } else {
8523 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008524 }
8525 return PERMISSION_DENIED;
8526 }
8527
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008528 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8529 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Kevin Rocard5f2136e2018-05-11 22:03:00 -07008530 isOutput(), client.clientUid, client.clientPid, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008531
Eric Laurent4eb58f12018-12-07 16:41:02 -08008532 if (isOutput()) {
8533 // force volume update when a new track is added
8534 mHalVolFloat = -1.0f;
8535 } else if (!track->isSilenced_l()) {
8536 for (const sp<MmapTrack> &t : mActiveTracks) {
8537 if (t->isSilenced_l() && t->uid() != client.clientUid)
8538 t->invalidate();
8539 }
8540 }
8541
8542
Eric Laurent6acd1d42017-01-04 14:23:29 -08008543 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008544 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008545 if (chain != 0) {
8546 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8547 chain->incTrackCnt();
8548 chain->incActiveTrackCnt();
8549 }
8550
8551 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008552 broadcast_l();
8553
Eric Laurenta54f1282017-07-01 19:39:32 -07008554 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008555
8556 return NO_ERROR;
8557}
8558
8559status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8560{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008561 ALOGV("%s handle %d", __FUNCTION__, handle);
8562
8563 if (mHalStream == 0) {
8564 return NO_INIT;
8565 }
8566
Eric Laurenta54f1282017-07-01 19:39:32 -07008567 if (handle == mPortId) {
8568 mHalStream->stop();
8569 return NO_ERROR;
8570 }
8571
Eric Laurent331679c2018-04-16 17:03:16 -07008572 Mutex::Autolock _l(mLock);
8573
Eric Laurent6acd1d42017-01-04 14:23:29 -08008574 sp<MmapTrack> track;
8575 for (const sp<MmapTrack> &t : mActiveTracks) {
8576 if (handle == t->portId()) {
8577 track = t;
8578 break;
8579 }
8580 }
8581 if (track == 0) {
8582 return BAD_VALUE;
8583 }
8584
8585 mActiveTracks.remove(track);
8586
Eric Laurent331679c2018-04-16 17:03:16 -07008587 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008588 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008589 AudioSystem::stopOutput(track->portId());
8590 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008591 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008592 AudioSystem::stopInput(track->portId());
8593 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008594 }
Eric Laurent331679c2018-04-16 17:03:16 -07008595 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008596
8597 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8598 if (chain != 0) {
8599 chain->decActiveTrackCnt();
8600 chain->decTrackCnt();
8601 }
8602
8603 broadcast_l();
8604
Eric Laurent6acd1d42017-01-04 14:23:29 -08008605 return NO_ERROR;
8606}
8607
Eric Laurent18b57012017-02-13 16:23:52 -08008608status_t AudioFlinger::MmapThread::standby()
8609{
8610 ALOGV("%s", __FUNCTION__);
8611
8612 if (mHalStream == 0) {
8613 return NO_INIT;
8614 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008615 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008616 return INVALID_OPERATION;
8617 }
8618 mHalStream->standby();
8619 mStandby = true;
8620 releaseWakeLock();
8621 return NO_ERROR;
8622}
8623
Eric Laurent6acd1d42017-01-04 14:23:29 -08008624
8625void AudioFlinger::MmapThread::readHalParameters_l()
8626{
8627 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8628 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8629 mFormat = mHALFormat;
8630 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8631 result = mHalStream->getFrameSize(&mFrameSize);
8632 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8633 result = mHalStream->getBufferSize(&mBufferSize);
8634 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8635 mFrameCount = mBufferSize / mFrameSize;
8636}
8637
8638bool AudioFlinger::MmapThread::threadLoop()
8639{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008640 checkSilentMode_l();
8641
8642 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8643
8644 while (!exitPending())
8645 {
8646 Mutex::Autolock _l(mLock);
8647 Vector< sp<EffectChain> > effectChains;
8648
8649 if (mSignalPending) {
8650 // A signal was raised while we were unlocked
8651 mSignalPending = false;
8652 } else {
8653 if (mConfigEvents.isEmpty()) {
8654 // we're about to wait, flush the binder command buffer
8655 IPCThreadState::self()->flushCommands();
8656
8657 if (exitPending()) {
8658 break;
8659 }
8660
Eric Laurent6acd1d42017-01-04 14:23:29 -08008661 // wait until we have something to do...
8662 ALOGV("%s going to sleep", myName.string());
8663 mWaitWorkCV.wait(mLock);
8664 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008665
8666 checkSilentMode_l();
8667
8668 continue;
8669 }
8670 }
8671
8672 processConfigEvents_l();
8673
8674 processVolume_l();
8675
8676 checkInvalidTracks_l();
8677
8678 mActiveTracks.updatePowerState(this);
8679
Kevin Rocard069c2712018-03-29 19:09:14 -07008680 updateMetadata_l();
8681
Eric Laurent6acd1d42017-01-04 14:23:29 -08008682 lockEffectChains_l(effectChains);
8683 for (size_t i = 0; i < effectChains.size(); i ++) {
8684 effectChains[i]->process_l();
8685 }
8686 // enable changes in effect chain
8687 unlockEffectChains(effectChains);
8688 // Effect chains will be actually deleted here if they were removed from
8689 // mEffectChains list during mixing or effects processing
8690 }
8691
8692 threadLoop_exit();
8693
8694 if (!mStandby) {
8695 threadLoop_standby();
8696 mStandby = true;
8697 }
8698
Eric Laurent6acd1d42017-01-04 14:23:29 -08008699 ALOGV("Thread %p type %d exiting", this, mType);
8700 return false;
8701}
8702
8703// checkForNewParameter_l() must be called with ThreadBase::mLock held
8704bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8705 status_t& status)
8706{
8707 AudioParameter param = AudioParameter(keyValuePair);
8708 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008709 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008710 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008711 audio_devices_t device = (audio_devices_t)value;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008712 // forward device change to effects that have requested to be
8713 // aware of attached audio device.
Eric Laurente6e9a482017-07-25 19:26:02 -07008714 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008715 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurente6e9a482017-07-25 19:26:02 -07008716 mEffectChains[i]->setDevice_l(device);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008717 }
8718 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008719 if (audio_is_output_devices(device)) {
8720 mOutDevice = device;
8721 if (!isOutput()) {
8722 sendToHal = false;
8723 }
8724 } else {
8725 mInDevice = device;
8726 if (device != AUDIO_DEVICE_NONE) {
8727 mPrevInDevice = value;
8728 }
8729 // TODO: implement and call checkBtNrec_l();
8730 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008731 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008732 if (sendToHal) {
8733 status = mHalStream->setParameters(keyValuePair);
8734 } else {
8735 status = NO_ERROR;
8736 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008737
8738 return false;
8739}
8740
8741String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8742{
8743 Mutex::Autolock _l(mLock);
8744 String8 out_s8;
8745 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8746 return out_s8;
8747 }
8748 return String8();
8749}
8750
8751void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid) {
8752 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8753
8754 desc->mIoHandle = mId;
8755
8756 switch (event) {
8757 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008758 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008759 case AUDIO_INPUT_CONFIG_CHANGED:
8760 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008761 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008762 case AUDIO_OUTPUT_CONFIG_CHANGED:
8763 desc->mPatch = mPatch;
8764 desc->mChannelMask = mChannelMask;
8765 desc->mSamplingRate = mSampleRate;
8766 desc->mFormat = mFormat;
8767 desc->mFrameCount = mFrameCount;
8768 desc->mFrameCountHAL = mFrameCount;
8769 desc->mLatency = 0;
8770 break;
8771
8772 case AUDIO_INPUT_CLOSED:
8773 case AUDIO_OUTPUT_CLOSED:
8774 default:
8775 break;
8776 }
8777 mAudioFlinger->ioConfigChanged(event, desc, pid);
8778}
8779
8780status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8781 audio_patch_handle_t *handle)
8782{
8783 status_t status = NO_ERROR;
8784
8785 // store new device and send to effects
8786 audio_devices_t type = AUDIO_DEVICE_NONE;
8787 audio_port_handle_t deviceId;
8788 if (isOutput()) {
8789 for (unsigned int i = 0; i < patch->num_sinks; i++) {
8790 type |= patch->sinks[i].ext.device.type;
8791 }
8792 deviceId = patch->sinks[0].id;
8793 } else {
8794 type = patch->sources[0].ext.device.type;
8795 deviceId = patch->sources[0].id;
8796 }
8797
8798 for (size_t i = 0; i < mEffectChains.size(); i++) {
8799 mEffectChains[i]->setDevice_l(type);
8800 }
8801
8802 if (isOutput()) {
8803 mOutDevice = type;
8804 } else {
8805 mInDevice = type;
8806 // store new source and send to effects
8807 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8808 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8809 for (size_t i = 0; i < mEffectChains.size(); i++) {
8810 mEffectChains[i]->setAudioSource_l(mAudioSource);
8811 }
8812 }
8813 }
8814
8815 if (mAudioHwDev->supportsAudioPatches()) {
8816 status = mHalDevice->createAudioPatch(patch->num_sources,
8817 patch->sources,
8818 patch->num_sinks,
8819 patch->sinks,
8820 handle);
8821 } else {
8822 char *address;
8823 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8824 //FIXME: we only support address on first sink with HAL version < 3.0
8825 address = audio_device_address_to_parameter(
8826 patch->sinks[0].ext.device.type,
8827 patch->sinks[0].ext.device.address);
8828 } else {
8829 address = (char *)calloc(1, 1);
8830 }
8831 AudioParameter param = AudioParameter(String8(address));
8832 free(address);
8833 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8834 if (!isOutput()) {
8835 param.addInt(String8(AudioParameter::keyInputSource),
8836 (int)patch->sinks[0].ext.mix.usecase.source);
8837 }
8838 status = mHalStream->setParameters(param.toString());
8839 *handle = AUDIO_PATCH_HANDLE_NONE;
8840 }
8841
François Gaffie0c280aa2018-07-25 10:02:15 +02008842 if (isOutput() && (mPrevOutDevice != mOutDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008843 mPrevOutDevice = type;
8844 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008845 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008846 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008847 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008848 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008849 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008850 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008851 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008852 }
François Gaffie0c280aa2018-07-25 10:02:15 +02008853 if (!isOutput() && (mPrevInDevice != mInDevice || mDeviceId != deviceId)) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008854 mPrevInDevice = type;
8855 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Phil Burk7f6b40d2017-02-09 13:18:38 -08008856 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008857 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008858 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008859 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008860 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008861 }
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008862 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008863 }
8864 return status;
8865}
8866
8867status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8868{
8869 status_t status = NO_ERROR;
8870
8871 mInDevice = AUDIO_DEVICE_NONE;
8872
8873 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8874 supportsAudioPatches : false;
8875
8876 if (supportsAudioPatches) {
8877 status = mHalDevice->releaseAudioPatch(handle);
8878 } else {
8879 AudioParameter param;
8880 param.addInt(String8(AudioParameter::keyRouting), 0);
8881 status = mHalStream->setParameters(param.toString());
8882 }
8883 return status;
8884}
8885
Mikhail Naganovdc769682018-05-04 15:34:08 -07008886void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008887{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008888 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008889 if (isOutput()) {
8890 config->role = AUDIO_PORT_ROLE_SOURCE;
8891 config->ext.mix.hw_module = mAudioHwDev->handle();
8892 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
8893 } else {
8894 config->role = AUDIO_PORT_ROLE_SINK;
8895 config->ext.mix.hw_module = mAudioHwDev->handle();
8896 config->ext.mix.usecase.source = mAudioSource;
8897 }
8898}
8899
8900status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
8901{
8902 audio_session_t session = chain->sessionId();
8903
8904 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
8905 // Attach all tracks with same session ID to this chain.
8906 // indicate all active tracks in the chain
8907 for (const sp<MmapTrack> &track : mActiveTracks) {
8908 if (session == track->sessionId()) {
8909 chain->incTrackCnt();
8910 chain->incActiveTrackCnt();
8911 }
8912 }
8913
8914 chain->setThread(this);
8915 chain->setInBuffer(nullptr);
8916 chain->setOutBuffer(nullptr);
8917 chain->syncHalEffectsState();
8918
8919 mEffectChains.add(chain);
8920 checkSuspendOnAddEffectChain_l(chain);
8921 return NO_ERROR;
8922}
8923
8924size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
8925{
8926 audio_session_t session = chain->sessionId();
8927
8928 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
8929
8930 for (size_t i = 0; i < mEffectChains.size(); i++) {
8931 if (chain == mEffectChains[i]) {
8932 mEffectChains.removeAt(i);
8933 // detach all active tracks from the chain
8934 // detach all tracks with same session ID from this chain
8935 for (const sp<MmapTrack> &track : mActiveTracks) {
8936 if (session == track->sessionId()) {
8937 chain->decActiveTrackCnt();
8938 chain->decTrackCnt();
8939 }
8940 }
8941 break;
8942 }
8943 }
8944 return mEffectChains.size();
8945}
8946
8947// hasAudioSession_l() must be called with ThreadBase::mLock held
8948uint32_t AudioFlinger::MmapThread::hasAudioSession_l(audio_session_t sessionId) const
8949{
8950 uint32_t result = 0;
8951 if (getEffectChain_l(sessionId) != 0) {
8952 result = EFFECT_SESSION;
8953 }
8954
8955 for (size_t i = 0; i < mActiveTracks.size(); i++) {
8956 sp<MmapTrack> track = mActiveTracks[i];
8957 if (sessionId == track->sessionId()) {
8958 result |= TRACK_SESSION;
8959 if (track->isFastTrack()) {
8960 result |= FAST_SESSION;
8961 }
8962 break;
8963 }
8964 }
8965
8966 return result;
8967}
8968
8969void AudioFlinger::MmapThread::threadLoop_standby()
8970{
8971 mHalStream->standby();
8972}
8973
8974void AudioFlinger::MmapThread::threadLoop_exit()
8975{
Phil Burk7dce7282017-09-27 13:51:41 -07008976 // Do not call callback->onTearDown() because it is redundant for thread exit
8977 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08008978}
8979
8980status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
8981{
8982 return BAD_VALUE;
8983}
8984
8985bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
8986{
8987 return false;
8988}
8989
8990status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
8991 const effect_descriptor_t *desc, audio_session_t sessionId)
8992{
8993 // No global effect sessions on mmap threads
8994 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
8995 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
8996 desc->name, mThreadName);
8997 return BAD_VALUE;
8998 }
8999
9000 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9001 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9002 desc->name);
9003 return BAD_VALUE;
9004 }
9005 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009006 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9007 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009008 return BAD_VALUE;
9009 }
9010
9011 // Only allow effects without processing load or latency
9012 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9013 return BAD_VALUE;
9014 }
9015
9016 return NO_ERROR;
9017
9018}
9019
9020void AudioFlinger::MmapThread::checkInvalidTracks_l()
9021{
9022 for (const sp<MmapTrack> &track : mActiveTracks) {
9023 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009024 sp<MmapStreamCallback> callback = mCallback.promote();
9025 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009026 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009027 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009028 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009029 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9030 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9031 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009032 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009033 }
9034 }
9035}
9036
9037void AudioFlinger::MmapThread::dump(int fd, const Vector<String16>& args)
9038{
9039 dumpInternals(fd, args);
9040 dumpTracks(fd, args);
9041 dumpEffectChains(fd, args);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009042 dprintf(fd, " Local log:\n");
9043 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009044}
9045
9046void AudioFlinger::MmapThread::dumpInternals(int fd, const Vector<String16>& args)
9047{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009048 dumpBase(fd, args);
9049
9050 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9051 mAttr.content_type, mAttr.usage, mAttr.source);
9052 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009053 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009054 dprintf(fd, " No active clients\n");
9055 }
9056}
9057
9058void AudioFlinger::MmapThread::dumpTracks(int fd, const Vector<String16>& args __unused)
9059{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009060 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009061 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009062 dprintf(fd, " %zu Tracks\n", numtracks);
9063 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009064 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009065 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009066 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009067 for (size_t i = 0; i < numtracks ; ++i) {
9068 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009069 result.append(prefix);
9070 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009071 }
9072 } else {
9073 dprintf(fd, "\n");
9074 }
9075 write(fd, result.string(), result.size());
9076}
9077
9078AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9079 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9080 AudioHwDevice *hwDev, AudioStreamOut *output,
9081 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9082 : MmapThread(audioFlinger, id, hwDev, output->stream, outDevice, inDevice, systemReady),
9083 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009084 mStreamVolume(1.0),
9085 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009086 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009087{
9088 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9089 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9090 mMasterVolume = audioFlinger->masterVolume_l();
9091 mMasterMute = audioFlinger->masterMute_l();
9092 if (mAudioHwDev) {
9093 if (mAudioHwDev->canSetMasterVolume()) {
9094 mMasterVolume = 1.0;
9095 }
9096
9097 if (mAudioHwDev->canSetMasterMute()) {
9098 mMasterMute = false;
9099 }
9100 }
9101}
9102
9103void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9104 audio_stream_type_t streamType,
9105 audio_session_t sessionId,
9106 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009107 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009108 audio_port_handle_t portId)
9109{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009110 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009111 mStreamType = streamType;
9112}
9113
9114AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9115{
9116 Mutex::Autolock _l(mLock);
9117 AudioStreamOut *output = mOutput;
9118 mOutput = NULL;
9119 return output;
9120}
9121
9122void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9123{
9124 Mutex::Autolock _l(mLock);
9125 // Don't apply master volume in SW if our HAL can do it for us.
9126 if (mAudioHwDev &&
9127 mAudioHwDev->canSetMasterVolume()) {
9128 mMasterVolume = 1.0;
9129 } else {
9130 mMasterVolume = value;
9131 }
9132}
9133
9134void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9135{
9136 Mutex::Autolock _l(mLock);
9137 // Don't apply master mute in SW if our HAL can do it for us.
9138 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9139 mMasterMute = false;
9140 } else {
9141 mMasterMute = muted;
9142 }
9143}
9144
9145void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9146{
9147 Mutex::Autolock _l(mLock);
9148 if (stream == mStreamType) {
9149 mStreamVolume = value;
9150 broadcast_l();
9151 }
9152}
9153
9154float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9155{
9156 Mutex::Autolock _l(mLock);
9157 if (stream == mStreamType) {
9158 return mStreamVolume;
9159 }
9160 return 0.0f;
9161}
9162
9163void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9164{
9165 Mutex::Autolock _l(mLock);
9166 if (stream == mStreamType) {
9167 mStreamMute= muted;
9168 broadcast_l();
9169 }
9170}
9171
9172void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9173{
9174 Mutex::Autolock _l(mLock);
9175 if (streamType == mStreamType) {
9176 for (const sp<MmapTrack> &track : mActiveTracks) {
9177 track->invalidate();
9178 }
9179 broadcast_l();
9180 }
9181}
9182
9183void AudioFlinger::MmapPlaybackThread::processVolume_l()
9184{
9185 float volume;
9186
9187 if (mMasterMute || mStreamMute) {
9188 volume = 0;
9189 } else {
9190 volume = mMasterVolume * mStreamVolume;
9191 }
9192
9193 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009194
9195 // Convert volumes from float to 8.24
9196 uint32_t vol = (uint32_t)(volume * (1 << 24));
9197
9198 // Delegate volume control to effect in track effect chain if needed
9199 // only one effect chain can be present on DirectOutputThread, so if
9200 // there is one, the track is connected to it
9201 if (!mEffectChains.isEmpty()) {
9202 mEffectChains[0]->setVolume_l(&vol, &vol);
9203 volume = (float)vol / (1 << 24);
9204 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009205 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009206 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9207 mHalVolFloat = volume; // HW volume control worked, so update value.
9208 mNoCallbackWarningCount = 0;
9209 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009210 sp<MmapStreamCallback> callback = mCallback.promote();
9211 if (callback != 0) {
9212 int channelCount;
9213 if (isOutput()) {
9214 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9215 } else {
9216 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9217 }
9218 Vector<float> values;
9219 for (int i = 0; i < channelCount; i++) {
9220 values.add(volume);
9221 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009222 mHalVolFloat = volume; // SW volume control worked, so update value.
9223 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009224 mLock.unlock();
9225 callback->onVolumeChanged(mChannelMask, values);
9226 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009227 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009228 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9229 ALOGW("Could not set MMAP stream volume: no volume callback!");
9230 mNoCallbackWarningCount++;
9231 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009232 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009233 }
9234 }
9235}
9236
Kevin Rocard069c2712018-03-29 19:09:14 -07009237void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9238{
9239 if (mOutput == nullptr || mOutput->stream == nullptr ||
9240 !mActiveTracks.readAndClearHasChanged()) {
9241 return;
9242 }
9243 StreamOutHalInterface::SourceMetadata metadata;
9244 for (const sp<MmapTrack> &track : mActiveTracks) {
9245 // No track is invalid as this is called after prepareTrack_l in the same critical section
9246 metadata.tracks.push_back({
9247 .usage = track->attributes().usage,
9248 .content_type = track->attributes().content_type,
9249 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9250 });
9251 }
9252 mOutput->stream->updateSourceMetadata(metadata);
9253}
9254
Eric Laurent6acd1d42017-01-04 14:23:29 -08009255void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9256{
9257 if (!mMasterMute) {
9258 char value[PROPERTY_VALUE_MAX];
9259 if (property_get("ro.audio.silent", value, "0") > 0) {
9260 char *endptr;
9261 unsigned long ul = strtoul(value, &endptr, 0);
9262 if (*endptr == '\0' && ul != 0) {
9263 ALOGD("Silence is golden");
9264 // The setprop command will not allow a property to be changed after
9265 // the first time it is set, so we don't have to worry about un-muting.
9266 setMasterMute_l(true);
9267 }
9268 }
9269 }
9270}
9271
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009272void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9273{
9274 MmapThread::toAudioPortConfig(config);
9275 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9276 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9277 config->flags.output = mOutput->flags;
9278 }
9279}
9280
Eric Laurent6acd1d42017-01-04 14:23:29 -08009281void AudioFlinger::MmapPlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
9282{
9283 MmapThread::dumpInternals(fd, args);
9284
Glenn Kastend3bb6452016-12-05 18:14:37 -08009285 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9286 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009287 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9288}
9289
9290AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9291 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
9292 AudioHwDevice *hwDev, AudioStreamIn *input,
9293 audio_devices_t outDevice, audio_devices_t inDevice, bool systemReady)
9294 : MmapThread(audioFlinger, id, hwDev, input->stream, outDevice, inDevice, systemReady),
9295 mInput(input)
9296{
9297 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9298 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9299}
9300
Eric Laurent331679c2018-04-16 17:03:16 -07009301status_t AudioFlinger::MmapCaptureThread::exitStandby()
9302{
Phil Burkf054fc32018-12-06 09:45:59 -08009303 {
9304 // mInput might have been cleared by clearInput()
9305 Mutex::Autolock _l(mLock);
9306 if (mInput != nullptr && mInput->stream != nullptr) {
9307 mInput->stream->setGain(1.0f);
9308 }
9309 }
Eric Laurent331679c2018-04-16 17:03:16 -07009310 return MmapThread::exitStandby();
9311}
9312
Eric Laurent6acd1d42017-01-04 14:23:29 -08009313AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9314{
9315 Mutex::Autolock _l(mLock);
9316 AudioStreamIn *input = mInput;
9317 mInput = NULL;
9318 return input;
9319}
Kevin Rocard069c2712018-03-29 19:09:14 -07009320
Eric Laurent331679c2018-04-16 17:03:16 -07009321
9322void AudioFlinger::MmapCaptureThread::processVolume_l()
9323{
9324 bool changed = false;
9325 bool silenced = false;
9326
9327 sp<MmapStreamCallback> callback = mCallback.promote();
9328 if (callback == 0) {
9329 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9330 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9331 mNoCallbackWarningCount++;
9332 }
9333 }
9334
9335 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9336 // track is silenced and unmute otherwise
9337 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9338 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9339 changed = true;
9340 silenced = mActiveTracks[i]->isSilenced_l();
9341 }
9342 }
9343
9344 if (changed) {
9345 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9346 }
9347}
9348
Kevin Rocard069c2712018-03-29 19:09:14 -07009349void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9350{
9351 if (mInput == nullptr || mInput->stream == nullptr ||
9352 !mActiveTracks.readAndClearHasChanged()) {
9353 return;
9354 }
9355 StreamInHalInterface::SinkMetadata metadata;
9356 for (const sp<MmapTrack> &track : mActiveTracks) {
9357 // No track is invalid as this is called after prepareTrack_l in the same critical section
9358 metadata.tracks.push_back({
9359 .source = track->attributes().source,
9360 .gain = 1, // capture tracks do not have volumes
9361 });
9362 }
9363 mInput->stream->updateSinkMetadata(metadata);
9364}
9365
Eric Laurent331679c2018-04-16 17:03:16 -07009366void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9367{
9368 Mutex::Autolock _l(mLock);
9369 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9370 if (mActiveTracks[i]->uid() == uid) {
9371 mActiveTracks[i]->setSilenced_l(silenced);
9372 broadcast_l();
9373 }
9374 }
9375}
9376
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009377void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9378{
9379 MmapThread::toAudioPortConfig(config);
9380 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9381 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9382 config->flags.input = mInput->flags;
9383 }
9384}
9385
Glenn Kasten63238ef2015-03-02 15:50:29 -08009386} // namespace android